Tip: #520 - Searching for Identifiers
Created: July 30, 2003 10:12 Complexity: intermediate Author: MightyByte Version: 5.7 Karma: 20/7 Imported from: Tip#520
The problem:
It's always annoying trying to do a search and replace for identifiers in C when the identifier that you are searching for is a substring of other identifiers or keywords in the program. For instance, let's say you want to search for every place you access the ubiquitous loop variable 'i'. If you do a search, you'll hit all the i's in the "if" and "while" keywords and any other identifiers that contain the letter i. For awhile I have been looking for some way to do this in vim. Other IDE's that I have seen have a "whole word" option where the text must be the whole word. Vim has the "]CTRL-I" command, but that is useless for search and replace because when you replace one instance, you won't have the original identifier under your cursor any more. Until recently, I didn't know how to do it in vim without manually typing the whole regular expression for C identifiers.
The solution:
Use the "\<" and "\>" in your search. Evidently, these respresent the start and end of words. So, to search for all occurrences of the variable 'i', you would use the following command:
/\<i\>
If you want all identifiers that start with 'i', you use "/\<i" and similarly, for all identifiers ending in 'i', use "/i\>".
If anyone knows a better solution, I would love to know about it.
Comments
You can also use the '*' key in command mode. Check tip # 1 for more details.
'gd' will bring you to the first occurence of the word under the cursor.
Anonymous , July 30, 2003 10:43
No Evidently about it, see ":h \<" and ":h \>"
What I like to do is highlight the var I want to replace as a search string (say via '*' or the like) this allows me to visually (and easily) see what I am about to replace.
I then linewise visual (:h linewise-visual) the section of code I wish to change (say all of a for loop).
It is then a simple matter of ":s//new_value_here/g"
Sreny--AT--SverGbc.Pbz (Rot13ed) , July 30, 2003 12:30
For those as lazy as myself:<br> If you happen to already have at least one occurrence of your variable onscreen, you can place your cursor over it and use Shift+# and it will automatically do a search for the word using the \<mystring\> notation.
linnc--AT--cs.arizona.edu , July 31, 2003 14:43