Reverse a word in Vim
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.
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.
This Tip might help: http://vim.wikia.com/wiki/Reverse_letters
It says:
Simply enable visual mode (v), highlight the characters you want inverted, and hit \is
. For a single word you can use vw (or viw): viw\is
vnoremap <silent> <Leader>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>
There are more solutions in the comments.
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>
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.
If you have rev
installed (e.g. via MSys or Cygwin) then it's really not this difficult.
Select what you want to reverse and filter (%! <cmd>
) it:
:%! rev
This pipes your selection to your shell while passing it a command.
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.
Well you could use python itself to reverse the line through the filter command. Say the text you had written was:
Python
You could reverse it by issuing.
:1 ! python -c "print raw_input()[::-1]"
And your text will be replaced to become:
nohtyP
The "1" in the command tells vi to send line 1 to the python statement which we are executing: "print raw_input()[::-1]". So if you wanted some other line reversed, you would send that line number as argument. The python statement then reverses the line of input.
There is a tricky way to do this if you have Vim compiled with +rightleft
. You set 'allowrevins'
which let you hit Ctrl+_
in insert mode to start Reverse Insert mode. It was originally made for inserting bidirectional scripts.
Type your desired word in Insert mode, or move your cursor to the end of an already typed word. Hit Ctrl+_
and then pick a completion (i_Ctrl-x
) method which is the most likely not to return any results for your word. Ysing Ctrl+e to cancel in-place completion does not seem to work in this case.
I.e. for an unsyntactic text file you can hit in insert mode Ctrl+x Ctrl+d
which is guaranteed to fail to find any macro/function names in the current file (See :h i_CTRL-X_CTRL-D
and:h complete
for more information).
And voila! Completion lookup in reverse mode makes the looked up word reverse. Notice that the cursor will move to the beginning of that word (it's reversed direction of writing, remember?)
You should then hit Ctrl+_
again to get back to regular insert mode and keyboard layout and go on with editing.
Tip: You can set 'complete' exclusively (for the buffer, at least) to a completion option that is guaranteed to return no result. Just go over the options in :h 'complete'
. This will make the easy i_Ctrl-N / i_Ctrl-P
bindings available for a handy word reversal session. You can ofcourse further automate this with a macro, a function or a binding
Note: Setting/resetting 'paste'
and 'compatible'
can set/reset 'allowrevins'
. See :h allowrevins
.
If you have some time on your hands, you can bubble your way there by iteratively transposing characters (xp
)...
I realize I'm a little late to the game, but I thought I'd just add what I think is the simplest method.
It's two things:
- Vim's expression register
pyeval
(py3eval
on recent vim releases) function
So to reverse a word you would do the following:
"ayiw
yank word into registera
<C-r>=py3eval('"".join(reversed(str(' . @a ')))')
use vim's=
(expression) register to call thepy3eval
function which evaluates python code (duh) and returns the result, which is then fed via the expression register into our document.
For more info on the expression register see https://www.brianstorti.com/vim-registers/#the-expression-and-the-search-registers
you can use revins
mode in order to do it:
at the beginning type :set revins
. from now on every letter you type will be inserted in a reverse order, until you type :set norevins
to turn off. i.e, while revins
is set, typing word
will output drow
.
in order to change an existing word after revins
mode is set, and the cursor on beginning of the word, type:
dwi<C-r>"<ESC>
explanation:
dw
deleted a word.i
to enter insert mode<C-r>"
to paste the last deleted or yaked text in insert mode,<ESC>
to exit insert mode.
remember to :set norevins
at the end!
精彩评论