InsertHandler#handleInsert Get Line Content At Caret

I currently implement my own InsertHandler:

LookupElementBuilder element = LookupElementBuilder.create("STH").withInsertHandler(new InsertHandler<LookupElement>() {
    public void handleInsert(InsertionContext insertionContext, LookupElement lookupElement) {
        // TODO get line content at caret
        String currentText = ElementManipulators.getValueText(completionParameters.getOriginalFile());
        // ...

Now the problem is that I would like to have the line content at the caret position. If I have the following content in my file and my caret is at [CARET]:

something something
some/cool/dir/ [CARET]
sthelse sthelse

I would like to have "some/cool/dir/ " as a result in my currentText variable above. Unfortunately, no matter what I tried, I only get a very weird text: "some/cool/dir/MY_COMPLETION_STRING". This is very strange:

  1. The whitespace is completely ignored.
  2. The string which is going to be autocompleted is already in that text.

Any idea how I can get the text I want?


Comment actions Permalink

You shouldn't use CompletionParameters in InsertHandler (it's not guaranteed to work), you have InsertionContext with all the necessary information. In particular, it has getStartOffset and getTailOffset and getDocument, which in turn has getLineNumber(offset), getLineStart/EndOffset, getCharSequence. A combination of these methods can help getting the text of the current line.

Before InsertHandler is invoked, the variant's lookupString is already inserted into the document. getStartOffset is before that string, getTailOffset — after it.

Comment actions Permalink

Thanks Peter! That indeed helps. insertionContext.getDocument().getText() also contains the text "some/cool/dir/MY_COMPLETION_STRING". With the following code, it is possible to get "some/cool/dir/".

String currentText = insertionContext.getDocument().getText().substring(0, insertionContext.getStartOffset());

But the whitespace is completely ignored. Mind that the string is "some/cool/dir/ [CARET]" with a whitespace after the last slash. I do not see any possibility how to get the text with the whitespace. The correct string would be "some/cool/dir/ " with a whitespace at the end. Why is the whitespace ignored/deleted? Any idea?

Comment actions Permalink

The best way to tell that is to debug. A breakpoint in DocumentImpl#changedUpdate will show all changes to all documents during completion.


Please sign in to leave a comment.