How to get current editor line content

Answered

Hello,

I need to get text from current line. I tried something like this

val caretModel: CaretModel = editor.caretModel

val psiFile = PsiManager.getInstance(project).findFile(virtualFile) ?: return

val currentLinePsiElement = psiFile.findElementAt(caretModel.offset)

But it return only current PsiElement, not an full text.

 

Could someone help? 


Thank you!

0
2 comments

Hello, If we are talking about the content of a particular line (from the startOffset to the endOffset), then it would be more correct to use the document:

val offset = editor.caretModel.offset
val document = editor.document
val line = document.getLineNumber(offset)
val textRange = TextRange(document.getLineStartOffset(line), document.getLineEndOffset(line))
document.getText(textRange)
0

This is exactly what is needed. Thank you so much!

0

Please sign in to leave a comment.