merlin2011
merlin2011

Reputation: 75585

Is there a native way to shift text vertically in Vim while exchanging with an adjacent line?

Consider the following text file:

--> Foobar
    Barfoo

I would like to transform this text to

    Foobar
--> Barfoo

There are several ways to do this. One possibility is to use REPLACE mode to overwrite the first line with three spaces, and then use REPLACE mode.

However, I'm wondering if there's a native way to select the array text (maybe in visual block mode) and pull it down to an adjacent line.

Upvotes: 2

Views: 400

Answers (3)

unrealapex
unrealapex

Reputation: 630

You could use a binding:

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

With this bind, you can use Alt + j and Alt + k to move a line up or down in normal and visual mode(for multiple lines). This binding was taken from the Vim Wiki.

Upvotes: 0

gregory
gregory

Reputation: 12953

While sticking to native vim has it merits, sometimes it's not worth being such a purist. Visual blocks are one area worth enhancing with plugins. In your case, I recommend vim-schlepp based on Damian Conway's dragvisuals.vim plugin which makes dragging and duplication of visual blocks a joy. For more ideas on visual block plugins, just watch Conway's demo here.

Upvotes: 1

merlin2011
merlin2011

Reputation: 75585

After learning about visual re-selection (gv), I figured out how to do this in a way that generalizes to any kind of visual selection (the first step is different depending on what one wants to select and move).

  1. Select the block visually: 0vf>
  2. Yank the block into a register: y
  3. Re-select the block: gv
  4. Replace all the text with a space character: r[Space]
  5. Move down a line: j
  6. Enter Replacement mode with [Shift]R.
  7. Paste the register contents [Control]R"

I recorded this as a macro and it works reasonably well.

Upvotes: 2

Related Questions