TextRange (Editor editor, Caret caret) { int selectionStart = caret.getSelectionStart(); int selectionEnd = caret.getSelectionEnd(); int startOffset = EditorUtil.getNotFoldedLineStartOffset(editor, selectionStart, true); // There is a possible case that selection ends at the line start, i.e. something like below ([...] denotes selected text, // '|' is a line start): // |line 1 // |[line 2 // |]line 3 // We don't want to delete line 3 here. However, the situation below is different: // |line 1 // |[line 2 // |line] 3 // Line 3 must be removed here. if (selectionEnd > 0 && selectionEnd != selectionStart) selectionEnd--; int endOffset = EditorUtil.getNotFoldedLineEndOffset(editor, selectionEnd, true); if (endOffset < editor.getDocument().getTextLength()) { endOffset++; } else if (startOffset > 0) { startOffset--; } return new TextRange(startOffset, endOffset); }