user1249065
user1249065

Reputation: 185

vim move a block of selected code up or down

There is a way to move highlighted code up or down with arrow keys. Even the indentation would be correct on dropping the block.

For the life of me I do not remember how to do it.

Can someone please tell me how to do it.( suitably embarrassed asking this).

Upvotes: 5

Views: 6359

Answers (5)

Dr Neo
Dr Neo

Reputation: 824

Here is my configurations, There is a nice configuration that I am using to map Ctrl+J to move a block of code up and Ctrl+K to move a block down. I am using currently NVIM but I think the same configuration setting is applicable for VIM as well.

  • Setting on NVIM The location that I am using on macOS Catalina for the NVIM is located at:

    .config/nvim/init.vim

    nnoremap K :m .-2<CR>==
    nnoremap J :m .+1<CR>==
    vnoremap K :m '<-2<CR>gv==gv
    vnoremap J :m '>+1<CR>gv=gv

for vim I think you can change the setting on .vimrc located under the home directory.

Upvotes: 0

ADJenks
ADJenks

Reputation: 3424

Cutting a block of text in visual mode and then pasting:

  1. Go to command mode by pressing Esc if you're not already in it
  2. Move to the start or end of where you want to go
  3. Press V to switch to visual mode
  4. Move with arrows or H,J,K,L to the other end of the block you want to move
  5. Press D to cut it, it will switch back into command mode
  6. Move to where you want to put it and press P to paste what you cut

It seems like a lot of steps but it's just a verbose explanation.

Upvotes: 1

Dan Lowe
Dan Lowe

Reputation: 56518

If you want to do it with arrow keys, you can try Tim Pope's vim-unimpaired plugin, which you can find on Github.

Then you can use mappings similar to these (except map them to whatever keys you like).

" ^U moves lines up, ^D moves lines down.
" Works in normal or visual select modes.
nmap <C-u> [e
nmap <C-d> ]e
vmap <C-u> [egv
vmap <C-d> ]egv

Upvotes: 2

NitheshKHP
NitheshKHP

Reputation: 391

Here's the link that'll help you

link

You can move a line, or a block of lines, with the :m command. Examples:

:m 12 move current line to after line 12

To move a block of lines, use the same command but visually select the lines before entering the move command. You can also use arbitrary ranges with the move command. Examples:

:5,7m 21 move lines 5, 6 and 7 to after line 21

Upvotes: 8

dannyliu
dannyliu

Reputation: 131

why not use d+p if you had chosen the block code

Upvotes: 1

Related Questions