String (@NotNull Project project, @NotNull Editor editor) { TextRange selectedRange = EditorUtil.getSelectionInAnyMode(editor); Document document = editor.getDocument(); if (!selectedRange.isEmpty()) { return document.getText(selectedRange); } int line = document.getLineNumber(selectedRange.getStartOffset()); int lineStart = document.getLineStartOffset(line); int lineEnd = document.getLineEndOffset(line); String lineText = document.getText(TextRange.create(lineStart, lineEnd)); // try to detect a non-trivial composite PSI element if there's a PSI file PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file != null && !StringUtil.isEmptyOrSpaces(lineText)) { int start = lineStart, end = lineEnd; while (start < end && Character.isWhitespace(lineText.charAt(start - lineStart))) start ++; while (end > start && Character.isWhitespace(lineText.charAt(end - 1 - lineStart))) end --; PsiElement e1 = file.findElementAt(start); PsiElement e2 = file.findElementAt(end > start ? end - 1 : end); PsiElement parent = e1 != null && e2 != null ? PsiTreeUtil.findCommonParent(e1, e2) : ObjectUtils.chooseNotNull(e1, e2); if (parent != null && parent != file) { TextRange combined = parent.getTextRange().union(TextRange.create(lineStart, lineEnd)); editor.getSelectionModel().setSelection(combined.getStartOffset(), combined.getEndOffset()); return document.getText(combined); } } return lineText; }