TextRange (@NotNull Editor editor, @NotNull VisualPosition rangeStart, @NotNull VisualPosition rangeEnd) { TextRange range = EditorUtil.calcSurroundingTextRange(editor, rangeStart, rangeEnd); String s = editor.getDocument().getText(range); int offset = editor.getCaretModel().getOffset(); int newOffset = offset + range.getLength(); int selectionStart = range.getEndOffset(); if (!s.endsWith("\n")) { // last line s = "\n"+s; newOffset++; selectionStart++; } DocumentGuardedTextUtil.insertString(editor.getDocument(), range.getEndOffset(), s); editor.getCaretModel().moveToOffset(newOffset); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); return TextRange.create(selectionStart, range.getEndOffset() + s.length()); }