Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vim, is there a way to move an object/motion (word, character, visual selection, etc) horizontally in the line, shifting characters around it?

Tags:

vim

For instance, I have the following line:

object     => "plaintext",

I want to move the word 'object' over to the right (so it's one space away from the '=>'), like this:

    object => "plaintext",

The only way I know of doing it would be (starting at the beginning of the line): i <esc>ea4x, or the equivalent from another starting location. I'd love to do the same thing I do for moving lines, but horizontally:

" Move lines up/down
nnoremap <Down> :m+<CR>==
nnoremap <Up> :m-2<CR>==
vnoremap <Down> :m '>+1<CR>gv=gv
vnoremap <Up> :m '<-2<CR>gv=gv
like image 800
zhimsel Avatar asked Feb 09 '23 00:02

zhimsel


2 Answers

You could cut(delete) and paste(put) your whitespace. It's not glorious but it would work. However I feel like a better option would be to align your text by using tabular (Aligning text with Tabular.vim) or vim-easy-align.

Using tabular you can do the following:

:Tabularize/=>/r1l1l1

There is also exchange.vim, but that is just fancy delete and putting. Swapping two regions of text with exchange.vim

like image 133
Peter Rincker Avatar answered May 20 '23 15:05

Peter Rincker


Another option to just do the horizontal movement is the following:

  • Provided you have already selected the text you want to move:

    :vnoremap <A-S-l> xp`[v`]
    :vnoremap <A-S-h> xhhp`[v`]
    
  • In normal mode, to just move the word your cursor is over (in any character of that word). These mappings will let you in visual mode:

    :nnoremap <A-S-l> viwxp`[v`]
    :nnoremap <A-S-h> viwxhhp`[v`]
    
  • In insert mode, to just move the word your cursor is over (in any character of that word). These two mappings will let you in visual mode:

    :inoremap <A-S-l> <Esc>viwxp`[v`]
    :inoremap <A-S-h> <Esc>viwxhhp`[v`]
    

With these mappings, you can:

  • Move selected text to the right: Alt+Shift+l
  • Move selected text to the left: Alt+Shift+h

Basically, you just cut what you have selected, paste it appropriately and select again what you have just pasted.

Obviously you can select any mapping you like.

like image 41
Nicolás Ozimica Avatar answered May 20 '23 14:05

Nicolás Ozimica