2

I have this nice set of vim mappings

" Drag Current Line/s Vertically
nnoremap <M-j> :m+<CR>
nnoremap <M-k> :m-2<CR>
inoremap <M-j> <Esc>:m+<CR>
inoremap <M-k> <Esc>:m-2<CR>
vnoremap <M-j> :m'>+<CR>gv

that I can't get to work on Mac/iTerm2/Tmux/vim combo. The problem I guess is in Alt key not getting mapped.

P.S. "Left option key acts as" is set to +Esc in iTerm session keys preferences

artemave
  • 6,786
  • 7
  • 47
  • 71
  • I can at least confirm this does not work for me with OSX10.6/iTerm2/tmux/vim over ssh (from putty), but DOES work for me with WindowsXP/GVim. – kenny Mar 01 '12 at 20:02
  • So that didn't make sense - as in that setup _putty_ would be my terminal, not iTerm2. I do have iTerm2 running at home, but that wouldn't have been part of my test. – kenny Mar 01 '12 at 21:00

2 Answers2

5

I'm throwing this up here after scouring through tons of SO questions and answers. This solution worked for me with iTerm2 + Mojave.

  1. In iTerm2, go to Preferences -> Profile -> Keys. In the bottom right, change your left (or right) option key to fire off an Esc+ sequence instead of Meta/Normal.
  2. Put the following code in your .vimrc:
execute "set <A-j>=\ej"
execute "set <A-k>=\ek"

nnoremap <A-j> :m .+1<
nnoremap <A-k> :m .-2<
inoremap <A-j> <Esc>:m .+1<CR>==
inoremap <A-k> <Esc>:m .-2<CR>==
vnoremap <A-j> :m '>+1<CR>gv=
vnoremap <A-k> :m '<-2<CR>gv=gv

What is this doing?

Admittedly, my understanding is not great. When you send an ALT+j command to Terminal, iTerm will receive it as ^[j which is an Escape sequence. When mapping it to Vim, ^[ ends up as \e. If you want to double check what your ALT+j (or ALT+k) is firing as, type sed -n l in a Terminal window and then hit ALT+j – you should see this output: ^[j

The execute set commands are remapping <A-j> and <A-k> mappings for Vim to fire off ^[j/^[k respectively to match what's being fired by iTerm.

This fixed it for me and I can now move line blocks like a pro. Hopefully it helps some people (sorry for my lackluster explanation–still learning the Vim ecosystem).

LMulvey
  • 1,662
  • 8
  • 14
1

I've already done some real life tests regarding this exact issue. My temporary and non-authoritative conclusion was/is that mappings using <M-> don't work in iTerm2 and that one should use alternative solutions instead.

I use <leader>.

Community
  • 1
  • 1
romainl
  • 186,200
  • 21
  • 280
  • 313
  • 1
    I just tried it without iTerm2. SSHing with putty to OSX10.6 in a tmux session, vim will not allow the mappings. This should effectively eliminate iTerm2 as the culprit. – kenny Mar 01 '12 at 21:02
  • Your question and the other one are both about Vim in iTerm2 but the culprit is Vim that doesn't work well with the Meta key *as sent by the shell*. – romainl Mar 01 '12 at 21:19