0

I want to write a Vim Script which can achieve the following function, which is my favorite feature in some IDE. Say I have the following example code:

I'm a line and I just stay here.
I'm another line and I also stay here.

I'm the line to be selected and swapped upward 1.    (1)
I'm the line to be selected and swapped upward 2.    (2)

Then I can move the cursor to line (1) and Vj to select both (1), (2), then now I can hold some custom key combination, say + option + k, and I hit these combination twice, then the expected result will be:

I'm the line to be selected and swapped upward 1.    (3)
I'm the line to be selected and swapped upward 2.    (4)
I'm a line and I just stay here.
I'm another line and I also stay here.
                                                     (1)
                                                     (2)

(The idea of swap selected lines downward is similar so I skip it.)

To avoid re-invent the wheel, is there any plugin already done this feature for us? If not, what are required for me to learn to write the above function?

1

There are too many plugins to move lines of text to mention them here.

An example to exchange (move) selected lines, more or less like in tpope/vim-unimpaired:

xnoremap <expr><silent>[e printf(":move '<--%d<CR>gv", v:count1)
xnoremap <expr><silent>]e printf(":move '>+%d<CR>gv", v:count1)

So [count][e moves selection by [count] lines up, and [count]]e moves down.

Of course, you can do the same simply by selecting block and then typing :m N, where N is the number of line to put the block after.

Also, to swap two adjacent :h paragraph(s) quickly: dap}p or dap2{p. Creating a mapping that also accepts count is left as an excercise.

1

My own mappings for this purpose:

" Bubble single lines up and down
nnoremap - :.move +1<CR>
nnoremap _ :.move -2<CR>
" Bubble lines up and down in visual mode
vnoremap - :'<,'>move '>+1 \| normal! gv<CR>
vnoremap _ :'<,'>move '<-2 \| normal! gv<CR>

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.