# Reverse every word in a line in vim

Your task is to build a vim script or provide a sequence of keystrokes that will operate on a single line of text with up to 140 printable ASCII characters (anywhere in a file, with the cursor starting anywhere in the line) and reverse every space-separated string in the sentence while keeping the strings in the same order.

For example, the input:

roF emos nosaer m'I gnisu a retcarahc-041 timil no siht noitseuq neve hguoht ti t'nseod evlovni .rettiwT RACECAR


should return:

For some reason I'm using a 140-character limit on this question even though it doesn't involve Twitter. RACECAR


The script with the fewest characters, or the sequence of the fewest keystrokes, to achieve this result is the winner.

• "For the purposes of this question it's vim only" seems as arbitrary a language-restriction as posting a normal code golf challenge and asking only for answers in C. (And I don't seem to be alone with this opinion.) – Martin Ender Mar 28 '15 at 18:08
• Why is RACECAR not reversed? – orlp Mar 28 '15 at 19:02
• Because it's a palindrome. Try reversing it yourself. – Joe Z. Mar 28 '15 at 19:02
• Wow, I'm stupid. Derp. – orlp Mar 28 '15 at 19:03
• @orlp Lol. I thought you were joking. – mbomb007 Mar 29 '15 at 2:12

# 2825 24 keystrokes

:se ri<CR>^qqct <C-r>"<Esc>f l@qq@q


Recursive macro, I assume that Ctrl-r counts as one keystroke.

The hardest part was to make sure the macro stays on the same line and does not destroy the rest of the file.

• You could use cE instead of ct , if it wasn't ending the macro. But you can use W instead of f l to save 2 strokes. – Caek Mar 29 '15 at 23:43
• @Caek Wrong x2. Guess what cE does when the cursor is at the beginning of a retcarahc-041? And guess what W does when we're at the end of the line? – orlp Mar 30 '15 at 0:39
• Note the capital E. lowercase e would go until the dash, capital E would go until the next space. I just tried it to confirm. – Caek Mar 30 '15 at 0:46
• try: :set ri<Enter>^qqct <C-r>"<Esc>W@qq@q for 23. – Caek Mar 30 '15 at 0:49
• @Caek That won't work. And regarding E, I know what it does. I was referring that cE<C-r><Esc> would turn a retcarahc-041 into 140-character a, AKA it would swap the words. – orlp Mar 30 '15 at 1:13

# 24 keystrokes

ma:s/ /\r/g
V'a:!rev
gvJ


I know this question is very old, but I love vimgolf so I couldn't not post an answer on one of the few vim-specific challenges on the site. Plus this solution is tied with Orlp's.

Just like Orlp said, the hardest part was making sure that the rest of the buffer was unmodified. If it weren't for that restriction, we could simply do:

:s/ /\r/g
!{rev
V}J


(19 keystrokes) but we need a little bit more to keep it buffer-safe. This assumes a unix environment.