views:

921

answers:

7

I want to write a command that specifies "the word under the cursor" in VIM. For instance, let's say I have the cursor on a word and I make it appear twice. For instance, if the word is "abc" and I want "abcabc" then I could type:

:s/\(abc\)/\1\1/

But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef":

:s/\(def\)/\1\1/

How can I write the command in the commandline so that it does this?

:s/\(*whatever is under the commandline*\)/\1\1
+4  A: 

<cword> is the word under the cursor (:help <cword>).

Sorry, I should have been more complete in this answer.

You can nmap a command to it, or this series of keystrokes for the lazy will work:

b #go to beginning of current word
yw #yank to register

Then, when you are typing in your pattern you can hit <control-r>0<enter> which will paste in your command the contents of the 0-th register.

You can also make a command for this like:

:nmap <leader>w :s/\(<c-r>=expand("<cword>")<cr>\)/

Which will map hitting '\' and 'w' at the same time to replace your command line with

:s/\(<currentword>\)/
hazzen
A: 

You need to escape the backslashes within the mapping. You can also include the substitution string within the mapping.

:nmap <leader>w :s/\\(<c-r>=expand("<cword>")<cr>\\)/\\1\\1<cr>
A: 
ywPx

will do what you describe.

ywPxw

will also advance the cursor to the next word.

--
bmb

bmb
A: 

yiwP

yiw: Yank inner word (the word under the cursor). This command also moves the cursor to the beginning of the word.

P: Paste before the cursor.

You can then map the e.g.: < ALT > - D to this command:

:nmap < ALT >-D yiwP

A: 

Another easy way to do this is to use the * command.

In regular mode, when over a word, type

*:s//\0\0<Enter>

* makes the search pattern the current word (e.g. \<abc\>).

:s// does a substitution using the current search pattern, and \0 in the replacement section is the matched string.

You can then repeat this behaviour, say over word "def", by either typing the same again, or by typing

*@:

@: just repeats the last ex command, without a need for an <Enter>, in this case the substitution.

You can also record a quick macro to do this using the q command

qd*:s//\0\0<Enter>q

Then repeat it to your hearts content by typing

@d

when over a word you want to double. As this is only one character less than the prior solution, it may not be worth it to you - unless you will be doing other ex-commands between the word-doubling, which would change the behaviour of @:

rampion
+4  A: 

CTRL-R CTRL-W

search for

:help c_CTRL-R

for all the registers.

César L
A: 

" count word  (case sensitive)
nmap  :%s/\(=expand("")\)//gn
could you comment on what this does?
Nathan Fellman