3

I have some mappings in my .vimrc with ALT. They are:

nnoremap <A-J> :m .+1<CR>==
nnoremap <A-K> :m .-2<CR>==

Expected behavior: These two mappings are supposed to move a line up and down. But they are not working. I am not even getting any error or warning. But when I use shift, they are working fine. Below are given the working mappings.

nnoremap <A-J> :m .+1<CR>==
nnoremap <A-K> :m .-2<CR>==

Why isn't ALT working?

halfer
  • 19,824
  • 17
  • 99
  • 186
odbhut.shei.chhele
  • 5,834
  • 16
  • 69
  • 109

3 Answers3

6

Firstly, add this to your zsh file

alias vim="stty stop '' -ixoff ; vim"

This is not necessary but it does get rid of vim mapping issues. Secondly, start by viewing the key code your terminal is sending to vim:

$ sed -n l

I am on Ubuntu, and Alt+j leads to

^[j

This basically prints out the combination of keycodes that is being sent to vim from your terminal. Note that the first part ^[ is the Escape key and not part of the key pressed.

Add this to your .vimrc

map <Esc>j <A-j>

Afterwards, you can use this to map to other functions:

nnoremap <A-j> :m .+1<CR>==

Source: https://vim.fandom.com/wiki/Mapping_fast_keycodes_in_terminal_Vim

Raza
  • 3,147
  • 2
  • 31
  • 35
4

Start by viewing the key code your terminal is sending to vim:

$ sed -n l

I am on Ubuntu, and Alt+j leads to

^[j

This basically prints out the combination of keycodes that is being sent to vim from your terminal.

If you are having difficulties with the <A+j> key combination, you can get what is sending to vim and then use that in the .vimrc.

as follows:

nnoremap ^[j :m .+1<CR>==

This will map <Alt + J> to moving a line up.

Note: Don't copy and paste nnoremap ^[j :m .+1<CR>== into your .vimrc. You will have to find what keycodes are being sent this in your terminal, and it could be very different from ^[j as each terminal might send different keycodes to vim. I am using Putty + Ubuntu running on a VM.

alpha_989
  • 4,882
  • 2
  • 37
  • 48
  • Trying this on Ubuntu under windows using WSL. The keycodes being sent are ^[j and ^[k just like you. however adding the line mentioned in my vimrc does nothing – Nicolas May 17 '19 at 15:31
  • yep same experience/problem - also on Ubuntu (WSL2) does not help a bit. still just throws me out eg out of INSERT mode to NORMAL mode but nothing more (eg in NORMAL or VISUAL mode since I also added inoremap and vnoremap)) – GWD Jun 20 '20 at 20:03
0

To map Alt you must use M instead of A.

nnoremap <M-J> :m .+1<CR>==
nnoremap <J-K> :m .-2<CR>==
SergioAraujo
  • 11,069
  • 3
  • 50
  • 40