Hiding Inlay Hints when code is folded

Answered

I am working on a plugin for a language that uses numeric values to reference constant values. To aid in understanding code at a glance, I have enabled inlay hints which give a text name to the number.

Today I decided I wanted to make some of the condition statements easier to read. To do this I used code folding. It works well except that the inlay hint for the last value in the condition still shows its inlay hint, despite the actual value being folded.

Is there a way to hide the inlay hint when the code is folded?. Or at least a way to tell if an element is inside a fold so I can return null for the inlay text if needed?

Thank you for your time

0
3 comments

I realized I should start by looking at the editor, not the folding regions. This led me to creating the following function, but I am not sure if there is a better, more efficient way.

val PsiElement.isFolded:Boolean get() {
val editor = editor(this)
val startOffset = textRange.startOffset
return editor.foldingModel.allFoldRegions.any {
!it.isExpanded && startOffset in it.startOffset .. it.endOffset
}
}
fun editor(element:PsiElement) : Editor? {
val document = document(element) ?: return null
return EditorFactory.getInstance().getEditors(document, element.project).firstOrNull()
}
fun document(element: PsiElement) : Document? {
val containingFile = element.containingFile ?: return null
val psiDocumentManager = PsiDocumentManager.getInstance(element.project)
return psiDocumentManager.getDocument(containingFile)
}
0

Unfortunately, at the moment there's no way to control folding behaviour for inline inlay elements. They are currently hidden if the anchor offset is 'inside' the collapsed fold region or equals to the region's start offset.
It's possible to optimise your code a bit (e.g. by using `FoldingModelEx.fetchTopLevel()` instead of `FoldingModel.getAllFoldRegions()` to process only 'top-level' collapsed fold regions, or using `FoldingModel.isOffsetCollapsed` which will perform a binary search internally), but it won't work reliably in case there are multiple editors for the same document (e.g. if the editor is split) - folding state can be different in different editors.

0

Thank you for your reply, I decided to go with FoldingModelEx.fetchTopLevel(), and it works well. I wasn't sure if multiple editors would ever be needed, but I decided to err on the side of caution. Thank you very much for your help though. I was worried about having to traverse so many folds.

0

Please sign in to leave a comment.