I’m working on implementing inline code completion using the com.intellij.codeInsight.inline.completion API. While the InlineCompletionElement interface provides skip and insert components for basic operations, I’m encountering scenarios where I need to: Delete existing characters or Replace specific ranges of text.
example:
// original
addThreeNumbers(x, y, z)
// user input
addTwoNumbers(x, y, z)
// we want to suggest
// delete ', z'
addTwoNumbers(x, y)
Questions:
Is there a dedicated API or component for text deletion/replacement within inline completion?
2.If not, do you have any suggestions?
Hello @josondi! The Inline Completion API was designed only for completion purposes. When designing the API, we didn’t (and still don’t) consider deletion or replacement as part of the completion. For us, it looks like ‘completion’ itself is only about additions. Deletions and replacements are kind of againts completion’s nature.
Unfortunately, there is no dedicated API to directly show deletion or replacement in an inline mode.
However, I have a proposal how to render deletions. You can use:
// add deletion indicator
val highlighter = editor.markupModel.addRangeHighlighter(
startOffset,
endOffset,
HighlighterLayer.ERROR + 1,
YOUR_ATTRUBUTES, // set the background color to red
HighlighterTargetArea.EXACT_RANGE,
)
....
// some code
...
// when you need to remove the highlighting
editor.markupModel.removeHighlighter(highlighter)
This approach will highlight the code in [startOffset, endOffset) with custom attributes (like red background for deletions).
But keep in mind, that you need to customly maintain its lifecycle: trigger on typings, remove on typings, remove on caret movements and etc. Unfortunately, there is no easy way to achieve it.
There is a chance that it’s possible to bind its lifecycle to the InlineCompletionSession lifecycle, but not sure that it’s achievable. When you understand that you need to remove characters inside getSuggestion within your inline completion provider:
Render deletion and make it dispose when InlineCompletionSession is disposed. Something like: InlineCompletionSession.getOrNull(editor).whenDisposed { Disposer.dispose(myDisposable) }
Return some fake suggestion from the provider.
BUT. I’m not sure that it will work.
Regarding the ‘replacement’ UX, I’m sorry, I don’t have an idea how to render it.