Moving lines up or down in a file

Moving lines up or down in a file

From Vim Tips Wiki

Tip 646 Previous Next created 2004 · complexity basic · author Frank Butler · version 6.0


The following mappings in your vimrc provide a quick way to move lines of text up or down. The mappings work in normal, insert and visual modes, allowing you to move the current line or a selected block of lines.

nnoremap <M-j> mz:m+<CR>`z==
nnoremap <M-k> mz:m-2<CR>`z==
inoremap <M-j> <Esc>:m+<CR>==gi
inoremap <M-k> <Esc>:m-2<CR>==gi
vnoremap <M-j> :m'>+<CR>gv=`<my`>mzgv`yo`z
vnoremap <M-k> :m'<-2<CR>gv=`>my`<mzgv`yo`z

Press Alt-j to move the current line down, or press Alt-k to move the current line up. The == re-indents the line to suit its new position.

Explanation

The command :m 5 moves the current line to below line 5. If the number starts with + or -, it is relative to the current line, so :m +5 moves the current line down by 5 lines (+5 is interpreted as .+5 where . means the current line). The space after :m is not required, and the +1 can be written as + (the 1 is assumed).

See also

Comments

 TO DO 

  • A quick test shows that this is very nice, and if polished, it could be a featured tip.
  • Why does it use a mark? I only tried the normal-mode mapping, but it seemed to work fine with the mz and `z removed.
  • Need to improve my above explanation.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值