CaretModel and SelectionModel doesnt trigger variable highlight

Answered

Question: How can i trigger highlight of all variable reference for variable under the caret (cursor) which was set manually with SelectionModel?

I create a plugin to count word-frequency and display it in JTable.When a row is clicked, it move the caret to the first instance of the word in the editor.

The problem is that the all of the reference to that variable is not highlighted (see Picture 1 below). This is different when I moved the caret manually to that variable (Picture 2).

I did that with this function

 

Kotlin Code:

val caretModel: CaretModel = this.editor.caretModel
caretModel.moveToLogicalPosition(LogicalPosition(line, column))

val selModel: SelectionModel = this.editor.selectionModel
selModel.selectWordAtCaret(true)

 

 

Picture 1: Editor selection with `SelectionModel` and `caretModel` does not highlight all "variableName" instance

 

Picture 2: Manually move the caret to variableName highlight all variableName instance.

1 comment
Comment actions Permalink
Official comment

I think that 'variableName' is highlighted in the latter screenshot because you've enabled Settings|Editor|general|highlight usages under caret.

To reproduce this behaviour in the code is not trivial because there are many languages with different takes on what to highlight how, e.g. in java method all the exit statements are highlighted when the caret is on the "return" keyword.

(See IdentifierHighlighterPass for details)

Generally you should

- find all the references of the element under the caret, in this case local variable "variableName". 

- by invoking e.g. com.intellij.psi.search.searches.ReferencesSearch#search(com.intellij.psi.PsiElement)

- then highlight all found references by e.g. com.intellij.codeInsight.highlighting.HighlightUsagesHandler#highlightReferences

Please sign in to leave a comment.