Is there a shortcut in Vim for going to the next word which is the same as the word cursor is on? It should work without typing the word with search command /.
* goes to the next matching word and # goes to the previous matching word. * is so useful it's sometimes called the super star.
* and # are your friends ( forward and backward directions respectively )
While all the answers here are correct, I thought it may be useful to provide a little more info.
What * actually does is perform a forward search for \<word-under-the-cursor\>. Because this is just a search operation, you can then navigate forwards and backwards to the next occurrences using n and N. This also means your previous search is lost. # is exactly the same as * except it performs a reverse search.
The \< and \> in the search string are word boundaries in vim's regex language which is what makes this work so nicely. It's also important to note that what is considered a "word" is determined by the iskeyword option. See :help word for more information.
To search the current word under the cursor use '*'.
to search backwards for current cursor word use '#'
gd and its variants are also very handy. It works slightly differently from *, in that it searches for the local declaration of the word under the cursor (or global declaration if none local exists). You can then search through the results with n like you can with superstar, and it will skip comments. It can be helpful when you're editing code.
:help gd
Related
I used this map:
map ,w v/\([^ a-z0-9]\|[^ A-Z0-9]\)*<cr>h
the idea is to select
in the words
mysuperTest
MYSUPER_TEST
mysuper_test
to always select the part that says mysuper
but it doesnt work, not sure why
I would use something like the below:
nnoremap ,w v/\C\%#.\([a-z]\+\<bar>[A-Z]\+\)\zs<cr>h
One point to notice is that in a mapping you need to use <bar> (or escape | with an extra backslash) since otherwise | is recognized as a command separator (see :help map-bar.)
Another one to notice is that you want the match to start at the first character outside the word (so you'll land at the end of the word with the h). The visual selection will expand to the start of the match in a search. I suggest using \zs to set the start of the match explicitly (see :help /\zs.)
Finally, beware of 'ignorecase' or 'smartcase' settings. Use \C to explicitly request a case-sensitive match (see :help /\C.)
I also like the idea of using a stronger anchor for the start of the match, so I'm using \%# to match the current cursor position (see :help /\%#), so you're always sure to match the current word only and not end up wandering through the buffer.
Putting it all together:
\C Case-sensitive search
\%# From cursor position
. Skip first character
\( Either one of:
[a-z]\+ One or more lowercase letters
\| (\<bar>) Or:
[A-Z]\+ One or more uppercase letters
\) End group
\zs Set match position here
I'm skipping the first character under the cursor, since in a CamelCase word, the first character won't match capitalization of the remainder of the word.
I kept your original idea of finding the first character after the word then using h to go back one to the left. But that might be a problem if, for example, the word is at the end of the line.
You can actually match the last character of the word instead with something like [a-z]\+\zs[a-z], which will set the start of the match on the last lowercase character. You can do this for both sides of the group (you can have more than one \zs in your pattern, last wins.) If you structure your match that way, you won't need the final h to go back.
I didn't handle numbers, I'll leave those as an exercise to the reader.
Finally, consider there are quite a few corner cases that can make such a mapping quite tricky to get right. Rather than coming up with your own, why not look at plug-ins which add support for handling CamelCase words that have been battle-tested and will cover use cases a lot more advanced than the simple expression you're using here?
There's the excellent vim-scripts/camelcasemotion by Ingo Karkat which sets up a ,w mapping to move to the start of the next CamelCase word, but also i,w to select the current one. You can use powerful combinations such as v3i,w to visually select the current and next two CamelCase words.
You might also check Tim Pope's tpope/vim-abolish which, among other features, defines a set of cr mappings to do coercion from camelCase to MixedCase, snake_case, UPPER_CASE, etc. (Not directly about selecting them, but still related and you might find it useful.)
When I type /foo and then enter, is there a way to mark occurrence for all highlighted words? Right now, the /search seems pretty useless compared to the regular atom search, since it only highlights but doesn't let you replace.
The key / is used for searching, whereas :s for substitutions (i.e. replacements). So to replace foo with bar you can do:
:%s/foo/bar/gc
Here % means look for replacements in the entire file, and the last gc are replacement flags. The Vim documentation provides a great explanation of the topic and it can be accessed by typing :help subs. To learn more about replacement flags: :h flags.
Some more suggestions for a good workflow (at least in Vim itself):
After using /foo to locate a match, and you only want to replace that one: As the cursor is at the start of the match, you can use ce, cE or more generally cgn (gn selects the current / next match; it's a recent addition in version 8.0).
If you want to replace all matches, you don't need to repeat the search pattern in the :substitute command; an empty {pattern} there will recall the search pattern. So, you can briefly write :%s//bar/g (+ c to interactively influence replacements).
It seems I can't mark occurrence if I press enter. However, I can do some things if I haven't pressed enter.
cmd-o marks all search occurrences
ctr-cmd-c waits for you to specify a range, and then changes all search occurrences
I'm writing a document with vim and latex. I recently noticed a word that I use ("tree"), but which is incorrect in the context of my document. I corrected it on the whole document. However, I have the habit to use this word instead of the correct one, when writing.
Is it possible to declare this word as a temporary wrong word (until the buffer is closed, this is enough), to make the spell-checker highlight it?
I have tried to mark it as definitive wrong word. This is not a solution as "tree" is in fact a correct word and should not be highlight in other documents. I also tried to search it: my vim is configured to automatically highlight it when I write it. This is a half-solution, as it needs that my last search be "tree", and handles difficultly many words if I have really wrong habits.
Vim spell cheat sheet:
]s / [s - next / previous misspelled word
]S / [S - next / previous bad word (i.e. as above, but ignore rare words and the like)
zg - add good word to the first dictionary in spellfile; remove it with zug
zG - add good word to the internal wordlist; remove it with zuG
zw - add bad word to the first dictionary; remove it with zuw
zW - add bad word to the internal wordlist; remove it with zuW
z= - suggest correctly spelled word.
According to the documentation,
The internal word list is used for all buffers where 'spell' is set. It is
not stored, it is lost when you exit Vim. It is also cleared when 'encoding'
is set.
So this is what you are looking for.
Please see :help spell-quickstart for more details.
You can set a match in your buffer, which will vanish when you close it.
:match Error /tree/
To only match the whole word "tree", use \< to match the beginning of the word and \> to match the end.
:match Error /\<tree\>/
:match documentation: http://vimdoc.sourceforge.net/htmldoc/pattern.html#:match
I would like to know if/how I can make vim look for the next occurrence of a variable. Let's say the variable's name is simply 'n', then /n would give me all occurrences of that letter, which isn't always terribly helpful. I guess I could create a regex to solve the problem, but I wondered whether there was some command/keystroke I simply don't yet know about; and as all my googling has been to no avail I decided to put a question on here.
Thanks a lot for your help!
If you have the cursor over the variable in question, you can press * and it will search for the next occurrence or # will search for the previous one.
This is equivalent to typing:
/\<n\>
(\< matches on the start of a word and \> matches on the end of word). The only difference (for reasons I'm not sure of) is that * and # don't pay attention to the 'smartcase' option.
See:
:help *
:help /\<
If you press n in command mode it will give you the next match of your search.
More detail:
/ will start forward search
? will start backward search
n will give you the next result in the direction you are searching
N will give you the previous result wrt the direction you are searching in
I am using Vim to read through a lot of C and Perl code containing many single letter variable names.
It would be nice to have some command to change the name of a variable to something more meaningful while I’m in the process of reading the code, so that I could read the rest of it faster.
Is there some command in Vim which could let me do this quickly?
I don’t think regexes would work because:
the same single letter name might have different purposes in different scoping blocks; and
the same combination of letters could be part of another longer variable name, a string literal, or a comment.
Are there any known solutions?
The following is how to rename a variable which is defined in the current scope {}.
Move your cursor to the variable usage. Press gd. Which means - move cursor to the definition.
Now Press [{ - this will bring you to the scope begin.
Press V - will turn on Visual Line selection.
Press % - will jump to the opposite } thus will select the whole scope.
Press :s/ - start of the substitute command.
<C-R>/ - will insert pattern that match variable name (that name you were on before pressing gd).
/newname/gc<CR> - will initiate search and replace with confirmation on every match.
Now you have to record a macros or even better - map a key.
Here are the final mappings:
" For local replace
nnoremap gr gd[{V%::s/<C-R>///gc<left><left><left>
" For global replace
nnoremap gR gD:%s/<C-R>///gc<left><left><left>
Put this to your .vimrc or just execute.
After this pressing gr on the local variable will bring you to :s command where you simply should enter new_variable_name and press Enter.
I know it's an old question, and #mykola-golubyev's way obviously IS the best answer for the particular case in the OP question (which, I assume is going through obfuscated code where you're likely to have multiple blocks with same var names); but with the question name like that many people coming here from google searches probably look for less situation-specific ways to rename variables in VIM -- and those can be more concise
I'm surprised no one suggested this way:
* :s// NEWNAME /gc
The * is the same as gn - search the next occurrence of the word under the cursor AND make it the last searched pattern; you can then omit the search pattern in the substitute command and VIM will assume that last one is the pattern to search for.
For small amounts of var copies, here's an even quicker one:
* cw NEWNAME <esc> then repeat n. for other occurrences
* is search for occurrences, cw is change word, n goes to the next occurrence of the last searched term and . repeats the last command (which is now change word to NEWNAME)
(Credits for me knowing all this go to #doomedbunnies on Reddit)
Another cool trick: (credits to #nobe4)
* cgn NEWNAME <esc> then repeat . for other occurrences
cgn is "change whatever is the result of (find next occurrence)". Now that this is the last command, you don't need the n to go to the next occurrence, so fewer strokes again, and, more importantly, no need to alternate n and .. But, obviously, this one has the drawback of not having a way to skip an occurrence.
Here are some benefits of these over other similar approaches, or language-specific plugins with refactoring support:
no command mapping, no fiddling with .vimrc(or init.vim), so you can use it in any VIM copy you come across (e.g. a quick task on some VPS or your friend's machine where configuring VIM your way would defeat the purpose of 'quick')
using * or gn for word selection is very quick -- just one keystroke (well, let's say 1.5)
using * or gn makes sure you don't get any matches inside other words, just as :%s/<C-R>//gc does. Beats typing the :%s/\<OLDNAME\>/NEWNAME/gc by hand: I personally tend to forget to use the \< things to limit matches to whole words only.
Not using a scope will only result in a few extra strokes of n to skip unwanted matches -- probably even fewer than the extra strokes needed to limit the scope to a certain code block. Under normal circumstances, your variables are most likely somewhat localised to a certain code block anyway.
AFAIK, there is no actual refactoring support in VIM. When doing a rename with the intent of a refactor I usually take the following precautions:
Limit the scope of the change my using marks.
When entering the regex, bracket the name with \< and >. This will make it match an entire word which reduces the types of incorrect renames that will occur.
Don't do a multiline replace to reduce chances of a bad replace
Look through the code diff carefully if it's anything other than a small change.
My end change looks something like this
:'a,'bs/\<foo\>/bar
I would love to be wrong about there not being a refactoring tool for VIM but I haven't seen it.
Put this in your .vimrc
" Function to rename the variable under the cursor
function! Rnvar()
let word_to_replace = expand("<cword>")
let replacement = input("new name: ")
execute '%s/\(\W\)' . word_to_replace . '\(\W\)/\1' . replacement . '\2/gc'
endfunction
Call it with :call Rnvar()
expand("<cword>") gets the word under the cursor. The search string uses % for file-scope, and the \(\W\) patterns look for non-word characters at the boundary of the word to replace, and save them in variables \1 and \2 so as to be re-inserted in the replacement pattern.
You could use the 'c' modifier in the global search and replace that would ask you for confirmation for each replace. It would take longer but it might work for a non-humongous code file:
%s/\$var/\$foo/gc
The c stands for confirm.
In c, you may be able to make some progress using cscope. It makes an attempt at understanding syntax, so would have a chance of knowing when the letter was a variable.
If this is across multiple files, you may consider taking a look at sed. Use find to grab your files and xargs plus sed for a replace. Say you want to replace a with a_better_name in all files matching *.c, you could do
find . -name "*.c" | xargs sed -i -e 's/a/a_better_name/g'
Bear in mind that this will replace ALL occurrences of a, so you may want a more robust regex.