String (@NotNull Editor editor, @NotNull PsiFile psiFile) { Editor hostEditor = editor instanceof EditorWindow ? ((EditorWindow)editor).getDelegate() : editor; List<Pair<Integer, String>> markers = new ArrayList<>(); Alarm alarm = new Alarm(); try { new BraceHighlightingHandler(psiFile.getProject(), editor, alarm, psiFile).updateBraces(); RangeHighlighter[] highlighters = editor.getMarkupModel().getAllHighlighters(); for (RangeHighlighter highlighter : highlighters) { if (highlighter.getLayer() == BraceHighlightingHandler.LAYER) { markers.add(Pair.create(highlighter.getStartOffset(), "<brace>")); markers.add(Pair.create(highlighter.getEndOffset(), "</brace>")); } } } finally { Disposer.dispose(alarm); } hostEditor.getCaretModel().getAllCarets().forEach(it -> markers.add(Pair.create(it.getOffset(), "<caret>"))); StringBuilder result = new StringBuilder(hostEditor.getDocument().getCharsSequence()); markers.stream() .sorted(Comparator.comparingInt(it -> -it.first)) .forEach(it -> result.insert(it.first, it.second)); return result.toString(); }