Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to reverse a comma-separated list in vim?

Tags:

vim

I frequently must correct the following rails code:

assert_equal value, expected

The two arguments to assert_equal are out of order, and should read:

assert_equal expected, value

In vim, what is the most efficient way of going from the first line to the second?

like image 895
ben.orenstein Avatar asked Apr 16 '09 18:04

ben.orenstein


4 Answers

Via regex:

:s/\v([^, ]+)(\s*,\s*)([^, ]+)/\3\2\1/

If you do it often you can make a map out of it, e.g.:

:nmap <F5> :s/\v([^, ]+)(\s*,\s*)([^, ]+)/\3\2\1/<CR>

Put the cursor on the line you want to flip and hit F5.

like image 50
Brian Carper Avatar answered Oct 05 '22 16:10

Brian Carper


This one swaps the word your cursor is on with the next one - just press F9 in command mode:

:map <F9> "qdiwdwep"qp
  • "qdiw: Put the word your cursor is on into buffer 'q'
  • dw: Delete all chars to the beginning of the next word (possibly comma + space)
  • e: Go to end of word
  • p: Paste (comma + space)
  • "qp: Paste buffer 'q' (the first word)
like image 20
soulmerge Avatar answered Oct 05 '22 16:10

soulmerge


Map a key combination to perform the command:

:s/^assert_equal \(.*\), \(.*\)$/assert_equal \2, \1
like image 31
Chad Birch Avatar answered Oct 05 '22 16:10

Chad Birch


I've always liked regular expression search and replace for these type of tasks:

:s/\(\w*\), \(\w*\)/\2, \1/

Will swap the first word with second in a comma separated list.

like image 30
skinp Avatar answered Oct 05 '22 15:10

skinp