How do you move a single line in Vim with a shortcut, and make the indent always be correct, as is displayed here: https://twitter.com/manucorporat/status/885054730812223489?s=09

  • Don't forget to accept the answer if it meet your needs.
    – DrBeco
    Jul 15 '17 at 2:25

Easy peasy. To map CONTROL+DOWN and CONTROL+UP you can do the following:

To make it go down:

:nmap <C-DOWN> ddp==

To make it go up:

:nmap <C-UP> ddkP==

You can choose other keys to map, and you can just type the commands and repeat, no need to map. Very basic stuff.

Edited: as the answer by Naumann bellow pointed out, vim already have

  • ]p : p==
  • [p : P== (upper-case P)

So, if you still want to map the keys, you may use that instead of p== or P==

BTW, I made a video as well.


Edited: An explanation to this issue can be read here

This answer of how map ALT key also uses exactly this example to illustrate it.

  • doesnt work. so what do i put in the vimrc file?
    – john-jones
    Jul 15 '17 at 19:22
  • doesnt work doesn't tell much, does it? What is the error message? In the vimrc you don't need the colon. Just nmap <C-UP> ddkP==. Analogous to go down. Try first directly in the vim command line and test. It works here just fine.
    – DrBeco
    Jul 15 '17 at 23:53
  • it works. (: i do noremap though.
    – john-jones
    Jul 17 '17 at 19:15
  • Good that it works for you. ;) Suggestion: you may try nnoremap instead of noremap. Keep your insertion mode clean. But whatever works best for you.
    – DrBeco
    Jul 19 '17 at 21:18

Vim already has ]p and [p for this

  • ]p : like p, but adjust indent to current line
  • [p : adjust indent to current line

Read :help ]p and :help [p for more information.

  • Is this pure vim or the plugin unimpaired?
    – DrBeco
    Jul 15 '17 at 3:34
  • It is pure vim. Try :help ]p
    – Naumann
    Jul 15 '17 at 4:31
  • so how does one go about acquiring the functionality requested? i tried putting that in the vimrc, no luck.
    – john-jones
    Jul 17 '17 at 19:04

This might help:

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

EDIT: Thank dr-beco Indeed you need the following configuration in your vimrc file in order to have your alt key mapped.

"Make Alt key work
let c='a'
while c <= 'z'
  exec "set <A-".c.">=\e".c
  exec "imap \e".c." <A-".c.">"
  let c = nr2char(1+char2nr(c))

Then you can use it with alt-j / alt-k

  • Given the credits. Also, mapping ALT works better using <M-j> instead of <A-j>. It is not clear why, but I've experience with this problem in two systems (linux/mac).
    – DrBeco
    Jul 16 '17 at 0:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.