How to determine variable usages?
I have written a plugin called Identifier Highlighter that mimics what the built-in "Highlight Usages in File" feature does, but without having to hit CtrlShiftF7 all of the time. It performs the search upon text cursor movement. However, the way I am searching is using the PsiFile tree which just gives me back a dumb textual search. If there is more than one variable called count, for example, I would like to only search the particular instance of count that my text cursor is on, not all instances of the word count in the file. Here is how I am searching the file, can anyone tell me how to determine how to limit my results to just the instance of variable my text cursor is on?
//Get PsiFile parse tree
PsiFile pFile = PsiDocumentManager.getInstance(_editor.getProject()).getPsiFile(_editor.getDocument());
//Get element text cursor is over
PsiElement pElem = pFile.findElementAt(_editor.getCaretModel().getOffset());
PsiSearchHelper search = pElem.getManager().getSearchHelper();
LocalSearchScope localFileScope = new LocalSearchScope(pFile);
//Find all other instances of that element in the file
_elems = search.findIdentifiers(pElem.getText(),localFileScope, UsageSearchContext.ANY);
Please sign in to leave a comment.
I was thinking that I could use findReferenceAt to see if the text cursor is over something that is a reference. If so, I could call resolve to see what it points to. That should take me to the declaration of the variable. Once I am at the variable, I should be able to call getReferences() to see all usages of this variable.
All of this works except for the getReferences() call. It always returns null or empty list. What am I doing wrong?
I don't want to discourage you, but this feature has been announced to be implemented in IDEA 6.5. So maybe you shouldn't spend too much time on it...
Shawn, I'm using your plugin right now and was just looking at doing the same thing. :)
This isn't the ultimate answer, but changing the UsageSearchContext from ANY to IN_CODE would be a start.
Otherwise, I have a feeling it's to do with the search scope... I don't have the answer but I'm fiddling with your code right now.
I think I figured it out. I used ReferencesSearch and it seems to do what I want. I checked in a new version of the plugin 2.00 with this enhancement. Now Alt+Left will jump to the occurence where the variable is declared, as long as it is in the same file.