How can I reverse a word in Vim? Preferably with a regex or normal-mode commands, but other methods are welcome too:
word => drow
Thanks for your help! PS: I'm in windows XP
Python is built in supported in my vim, but not Perl.
How can I reverse a word in Vim? Preferably with a regex or normal-mode commands, but other methods are welcome too:
word => drow
Thanks for your help! PS: I'm in windows XP
Python is built in supported in my vim, but not Perl.
This VIM Cookbook includes some techniques for manipulating words, including reversing them. The example can probably be relatively easily extended to reverse characters within a word.
if your version of VIM supports it you can do vw\is
or viw\is
(put your cursor at the first letter of the word before typing the command)... but I have had a lot of compatibility issues with that. Not sure what has to be compiled in or turned on but this only works sometimes.
EDIT:
\is
is:
:<C-U>let old_reg_a=@a<CR>
\ :let old_reg=@"<CR>
\ gv"ay :let @a=substitute(@a, '.\(.*\)\@=', '\=@a[strlen(submatch(1))]', 'g')<CR>
\ gvc<C-R>a<Esc> :let @a=old_reg_a<CR>
\ :let @"=old_reg<CR>
Didn't remember where it came from but a google search come this article on vim.wikia.com. Which shows the same thing so I guess that's it.
Assuming you've got perl support built in to vim, you can do this:
command! ReverseWord call ReverseWord()
function! ReverseWord()
perl << EOF
$curword = VIM::Eval('expand("<cword>")');
$reversed = reverse($curword);
VIM::Msg("$curword => $reversed");
VIM::DoCommand("norm lbcw$reversed");
EOF
endfun
And potentially bind that to a keystroke like so:
nmap ,r :ReverseWord<CR>
If you have some time on your hands, you can bubble your way there by iteratively transposing characters (xp
)...
I don't have Python supported on my VIM, but it looks like it would be pretty simple to do it with Python. This article seems like a good explanation of how to use Python in VIM and I'm guessing you'd do something like this:
:python 'word'[::-1]
The article indicates that the result will appear in the status bar, which would be non-optimal if you were trying to replace the string in a document, but if you just want to check that your girlfriend is properly reversing strings in her head, this should be fine.
Here is another (pythonic) solution based on how this works:
:echo join(reverse(split('hello', '.\zs')), '')
olleh
If you want to replace all words in the buffer,
:%s/\(\<.\{-}\>\)/\=join(reverse(split(submatch(1), '.\zs')), '')/g
This works by first creating a list of characters in the word, which is reversed and joined back to form the word. The substitute command finds each word and then passes the word to the expressions and uses the result as replacement.