Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cyclically rotate a selected array in vim

Tags:

vim

Is there an easy command in vim to cyclically rotate arrays?

For example, selecting "1, 2, 3" in the text and pressing a shortcut should replace the selected text to "2, 3, 1".

Ideally the command should allow for arbitrary cyclic shifts.

like image 753
Der Gnirreh Avatar asked Aug 08 '26 21:08

Der Gnirreh


2 Answers

You mean something like:

function! s:Rotate(list, rot)
   let res = a:list[a:rot :] + a:list[: (a:rot-1)]
   return res
endfunction

xnoremap <silent> <c-x>r s<c-r>=join(s:Rotate(split(@", ', *'), v:count1), ', ')<cr><esc>gv

Visually select your list. Hit CTRL-X then r and tada!. If you want to rotate more than of one element at a time, type first the number of shifts you want (the number must be in between -len(list) and +len(list)) before CTRL-X_r

like image 193
Luc Hermitte Avatar answered Aug 11 '26 20:08

Luc Hermitte


Argumentative.vim plugin allows shifting arguments. The idea being you shift the first argument with an overly large count, e.g. 99.

99>,

This will move the first argument to the end of the array. Then you can get back to the first argument with a similar trick using a boundary motion, [,

99[,

You may also want to take a look a sideways.vim which provides similar functionality to argumentative.vim.

like image 29
Peter Rincker Avatar answered Aug 11 '26 19:08

Peter Rincker