Can I map Alt key in Vim?

To Mac users out there: for mapping ALT+hjkl, use instead the real character generated (find out which character using the combination while in INSERT mode), for example with my keyboard I get:

<ALT+j> ==> ª
<ALT+k> ==> º

and so on.
Solution found here on StackOverflow.

I used this to move lines up and down with ALT+k\j, using this on my .vimrc:

nnoremap ª :m .+1<CR>==
nnoremap º :m .-2<CR>==

inoremap ª <Esc>:m .+1<CR>==gi
inoremap º <Esc>:m .-2<CR>==gi

vnoremap ª :m '>+1<CR>gv=gv
vnoremap º :m '<-2<CR>gv=gv

as explained here.

Hope it’s useful, enjoy Vim 🙂

ADDENDUM BY Dylan_Larkin (2019): For this to work on a Mac, “Use Option as Meta Key” must be turned OFF in Terminal->Preferences->Keyboard

UPDATE 09/2021

I recently switched from a “British” keyboard to “ABC – Extended” and noticed this configuration doesn’t work as expected.
As an alternative, I mapped the <up> and <down> keys to do the same operation (which, I guess, also solves most of the complexity explained in other answers of this very question):

nnoremap <down> :m .+1<CR>==
nnoremap <up> :m .-2<CR>==

inoremap <down> <Esc>:m .+1<CR>==gi
inoremap <up> <Esc>:m .-2<CR>==gi

vnoremap <down> :m '>+1<CR>gv=gv
vnoremap <up> :m '<-2<CR>gv=gv

This is also a great way for beginners to rewire the habit of using the arrows and instead learn the much more efficient Vim motion way to move around the code. 😉

You can complete your transition mapping <left> and <right> to quickly move between tabs with:

nnoremap <left> gT
nnoremap <right> gt

Or whatever you fancy (even a brutal <NOP>, like I did at the beginning of my journey).

Leave a Comment