Highlighting arbitrary text range in editor

Answered

I am building a pair programming plugin where one of the features should be to show what text the remote programmer has selected. The intuitive way to implement this would be to highlight the remote programmer's selected range with a specific colour.

I must have searched everything but can't find any tutorials/documentation for a suitable api. The closest I got is in the Annotator, but that seems to be a dead end for I understand Annotators are used for highlighting specific tokens, not arbitrary ranges.

Does your SDK have an api to highlight an arbitrary range of text with a specific colour?

For example, I would like to allow highlighting as shown between [ and ] below:

```
var na[me = 'Jetbrains';
console.log(`Come on ${name}, surely this api mu]st exist!`)
```

0
4 comments

You may try with the RangeHighlighter

Keep in mind that user may place a multiple carets/select multiple ranges of text thanks to the Multiple carets feature.

0
Avatar
Permanently deleted user

Jakub, thanks! I had tried RangeHighlighter before but didn't achieve what I was after. The only two methods that seemed relevant were setErrorStripeMarkColor and setLineSeparatorColor. Neither highlights the background of the exact range for a highlighter obtained like so:

RangeHighlighter highlighter = editor.getMarkupModel().addRangeHighlighter(1, 3, 9999, null, HighlighterTargetArea.EXACT_RANGE);

The setErrorStripeMarkColor doesn't make any visible changes and the setLineSeparatorColor underlines the whole line that corresponds to the given range.

Now that you pointed me back to it I tried setCustomRendered, but that simply exposes the low-level graphics and, as far as I can tell, I'd have do non-trivial calculations to compute the highlight rectangle, draw it directly using the graphics and update it whenever the within the range changes. If that is the only way I'll go ahead, but I was hoping there would be a more convenient way to highlight the background of a specific text range?

And thanks for reminding me about the multiple carets. It is indeed my plan to support multi-caret selection. First, I need to figure out how to use RangeHighlighter efficiently. Further help is appreciated!

0

The fourth argument is supposed to be a TextAttributes instance. I.e. with:

editor.markupModel.addRangeHighlighter(1, 3, 9999, TextAttributes(null, Color.red, null, null, Font.PLAIN), HighlighterTargetArea.EXACT_RANGE)

it looks like:

 

1
Avatar
Permanently deleted user

Fantastic, thank you!

0

Please sign in to leave a comment.