private VerticalInfo createVerticalInfo(LogicalPosition position) { Document document = myEditor.getDocument(); int logicalLine = position.line; if (logicalLine >= document.getLineCount()) { logicalLine = Math.max(0, document.getLineCount() - 1); } int startOffset = document.getLineStartOffset(logicalLine); int endOffset = document.getLineEndOffset(logicalLine); // There is a possible case that active logical line is represented on multiple lines due to // soft wraps processing. // We want to highlight those visual lines as 'active' then, so, we calculate 'y' position for // the logical line start // and height in accordance with the number of occupied visual lines. VisualPosition visualPosition = myEditor.offsetToVisualPosition(document.getLineStartOffset(logicalLine)); int y = myEditor.visualPositionToXY(visualPosition).y; int lineHeight = myEditor.getLineHeight(); int height = lineHeight; List<? extends SoftWrap> softWraps = myEditor.getSoftWrapModel().getSoftWrapsForRange(startOffset, endOffset); for (SoftWrap softWrap : softWraps) { height += StringUtil.countNewLines(softWrap.getText()) * lineHeight; } return new VerticalInfo(y, height); }
public CaretModelImpl(EditorImpl editor) { myEditor = editor; myLogicalCaret = new LogicalPosition(0, 0); myVisibleCaret = new VisualPosition(0, 0); myCaretInfo = new VerticalInfo(0, 0); myOffset = 0; myVisualLineStart = 0; Document doc = editor.getDocument(); myVisualLineEnd = doc.getLineCount() > 1 ? doc.getLineStartOffset(1) : doc.getLineCount() == 0 ? 0 : doc.getLineEndOffset(0); DocumentBulkUpdateListener bulkUpdateListener = new DocumentBulkUpdateListener() { @Override public void updateStarted(Document doc) { if (doc != myEditor.getDocument()) return; savedBeforeBulkCaretMarker = doc.createRangeMarker(myOffset, myOffset); } @Override public void updateFinished(Document doc) { if (doc != myEditor.getDocument() || myIsInUpdate) return; if (savedBeforeBulkCaretMarker != null && savedBeforeBulkCaretMarker.isValid()) { moveToOffset(savedBeforeBulkCaretMarker.getStartOffset()); } releaseBulkCaretMarker(); } }; ApplicationManager.getApplication() .getMessageBus() .connect(this) .subscribe(DocumentBulkUpdateListener.TOPIC, bulkUpdateListener); }
private boolean isBlankLine(int line, CharSequence chars) { Document document = myDocument; if (document == null) { return true; } int startOffset = document.getLineStartOffset(line); int endOffset = document.getLineEndOffset(line); return CharArrayUtil.shiftForward(chars, startOffset, endOffset, " \t") >= myDocument.getLineEndOffset(line); }
@Nullable private static String getPropertyName(@NotNull Document document, int line) { int startOffset = document.getLineStartOffset(line); int endOffset = StringUtil.indexOf( document.getCharsSequence(), '=', startOffset, document.getLineEndOffset(line)); if (endOffset <= startOffset) { return null; } String propertyName = document.getCharsSequence().subSequence(startOffset, endOffset).toString().trim(); return propertyName.isEmpty() ? null : propertyName; }
@Override @NotNull public List<? extends SoftWrap> getSoftWrapsForLine(int documentLine) { if (!isSoftWrappingEnabled() || documentLine < 0) { return Collections.emptyList(); } Document document = myEditor.getDocument(); int start = document.getLineStartOffset(documentLine); int end = document.getLineEndOffset(documentLine); return getSoftWrapsForRange( start, end + 1 /* it's theoretically possible that soft wrap is registered just before the line feed, * hence, we add '1' here assuming that end line offset points to line feed symbol */); }
private static void logInitial( @NotNull Editor editor, @NotNull int[] startOffsets, @NotNull int[] endOffsets, int indentSymbolsToStrip, int firstLineStartOffset) { if (!Registry.is("editor.richcopy.debug")) { return; } StringBuilder buffer = new StringBuilder(); Document document = editor.getDocument(); CharSequence text = document.getCharsSequence(); for (int i = 0; i < startOffsets.length; i++) { int start = startOffsets[i]; int lineStart = document.getLineStartOffset(document.getLineNumber(start)); int end = endOffsets[i]; int lineEnd = document.getLineEndOffset(document.getLineNumber(end)); buffer .append(" region #") .append(i) .append(": ") .append(start) .append('-') .append(end) .append(", text at range ") .append(lineStart) .append('-') .append(lineEnd) .append(": \n'") .append(text.subSequence(lineStart, lineEnd)) .append("'\n"); } if (buffer.length() > 0) { buffer.setLength(buffer.length() - 1); } LOG.info( String.format( "Preparing syntax-aware text. Given: %s selection, indent symbols to strip=%d, first line start offset=%d, selected text:%n%s", startOffsets.length > 1 ? "block" : "regular", indentSymbolsToStrip, firstLineStartOffset, buffer)); }
public static String getNewText(PsiElement elt) { Project project = elt.getProject(); PsiFile psiFile = getContainingFile(elt); final Document doc = PsiDocumentManager.getInstance(project).getDocument(psiFile); if (doc == null) return null; final ImplementationTextSelectioner implementationTextSelectioner = LanguageImplementationTextSelectioner.INSTANCE.forLanguage(elt.getLanguage()); int start = implementationTextSelectioner.getTextStartOffset(elt); final int end = implementationTextSelectioner.getTextEndOffset(elt); final int lineStart = doc.getLineStartOffset(doc.getLineNumber(start)); final int lineEnd = end < doc.getTextLength() ? doc.getLineEndOffset(doc.getLineNumber(end)) : doc.getTextLength(); return doc.getCharsSequence().subSequence(lineStart, lineEnd).toString(); }
private int yPositionToOffset(int y, boolean beginLine) { if (myEditorScrollbarTop == -1 || myEditorTargetHeight == -1) { recalcEditorDimensions(); } final int safeY = Math.max(0, y - myEditorScrollbarTop); VisualPosition visual; if (myEditorSourceHeight < myEditorTargetHeight) { visual = myEditor.xyToVisualPosition(new Point(0, safeY)); } else { float fraction = Math.max(0, Math.min(1, safeY / (float) myEditorTargetHeight)); final int lineCount = myEditorSourceHeight / myEditor.getLineHeight(); visual = new VisualPosition((int) (fraction * lineCount), 0); } int line = myEditor.visualToLogicalPosition(visual).line; Document document = myEditor.getDocument(); if (line < 0) return 0; if (line >= document.getLineCount()) return document.getTextLength(); return beginLine ? document.getLineStartOffset(line) : document.getLineEndOffset(line); }
private static Pair<Integer /* start offset to use */, Integer /* indent symbols to strip */> calcIndentSymbolsToStrip(@NotNull Document document, int startOffset, int endOffset) { int startLine = document.getLineNumber(startOffset); int endLine = document.getLineNumber(endOffset); CharSequence text = document.getCharsSequence(); int maximumCommonIndent = Integer.MAX_VALUE; int firstLineStart = startOffset; int firstLineEnd = startOffset; for (int line = startLine; line <= endLine; line++) { int lineStartOffset = document.getLineStartOffset(line); int lineEndOffset = document.getLineEndOffset(line); if (line == startLine) { firstLineStart = lineStartOffset; firstLineEnd = lineEndOffset; } int nonWsOffset = lineEndOffset; for (int i = lineStartOffset; i < lineEndOffset && (i - lineStartOffset) < maximumCommonIndent && i < endOffset; i++) { char c = text.charAt(i); if (c != ' ' && c != '\t') { nonWsOffset = i; break; } } if (nonWsOffset >= lineEndOffset) { continue; // Blank line } int indent = nonWsOffset - lineStartOffset; maximumCommonIndent = Math.min(maximumCommonIndent, indent); if (maximumCommonIndent == 0) { break; } } int startOffsetToUse = Math.min(firstLineEnd, Math.max(startOffset, firstLineStart + maximumCommonIndent)); return Pair.create(startOffsetToUse, maximumCommonIndent); }
@Override @SuppressWarnings({"AssignmentToForLoopParameter"}) public void paint( @NotNull Editor editor, @NotNull RangeHighlighter highlighter, @NotNull Graphics g) { int startOffset = highlighter.getStartOffset(); final Document doc = highlighter.getDocument(); if (startOffset >= doc.getTextLength()) return; final int endOffset = highlighter.getEndOffset(); final int endLine = doc.getLineNumber(endOffset); int off; int startLine = doc.getLineNumber(startOffset); IndentGuideDescriptor descriptor = editor.getIndentsModel().getDescriptor(startLine, endLine); final CharSequence chars = doc.getCharsSequence(); do { int start = doc.getLineStartOffset(startLine); int end = doc.getLineEndOffset(startLine); off = CharArrayUtil.shiftForward(chars, start, end, " \t"); startLine--; } while (startLine > 1 && off < doc.getTextLength() && chars.charAt(off) == '\n'); final VisualPosition startPosition = editor.offsetToVisualPosition(off); int indentColumn = startPosition.column; // It's considered that indent guide can cross not only white space but comments, javadocs // etc. Hence, there is a possible // case that the first indent guide line is, say, single-line comment where comment // symbols ('//') are located at the first // visual column. We need to calculate correct indent guide column then. int lineShift = 1; if (indentColumn <= 0 && descriptor != null) { indentColumn = descriptor.indentLevel; lineShift = 0; } if (indentColumn <= 0) return; final FoldingModel foldingModel = editor.getFoldingModel(); if (foldingModel.isOffsetCollapsed(off)) return; final FoldRegion headerRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineEndOffset(doc.getLineNumber(off))); final FoldRegion tailRegion = foldingModel.getCollapsedRegionAtOffset( doc.getLineStartOffset(doc.getLineNumber(endOffset))); if (tailRegion != null && tailRegion == headerRegion) return; final boolean selected; final IndentGuideDescriptor guide = editor.getIndentsModel().getCaretIndentGuide(); if (guide != null) { final CaretModel caretModel = editor.getCaretModel(); final int caretOffset = caretModel.getOffset(); selected = caretOffset >= off && caretOffset < endOffset && caretModel.getLogicalPosition().column == indentColumn; } else { selected = false; } Point start = editor.visualPositionToXY( new VisualPosition(startPosition.line + lineShift, indentColumn)); final VisualPosition endPosition = editor.offsetToVisualPosition(endOffset); Point end = editor.visualPositionToXY(new VisualPosition(endPosition.line, endPosition.column)); int maxY = end.y; if (endPosition.line == editor.offsetToVisualPosition(doc.getTextLength()).line) { maxY += editor.getLineHeight(); } Rectangle clip = g.getClipBounds(); if (clip != null) { if (clip.y >= maxY || clip.y + clip.height <= start.y) { return; } maxY = Math.min(maxY, clip.y + clip.height); } final EditorColorsScheme scheme = editor.getColorsScheme(); g.setColor( selected ? scheme.getColor(EditorColors.SELECTED_INDENT_GUIDE_COLOR) : scheme.getColor(EditorColors.INDENT_GUIDE_COLOR)); // There is a possible case that indent line intersects soft wrap-introduced text. // Example: // this is a long line <soft-wrap> // that| is soft-wrapped // | // | <- vertical indent // // Also it's possible that no additional intersections are added because of soft wrap: // this is a long line <soft-wrap> // | that is soft-wrapped // | // | <- vertical indent // We want to use the following approach then: // 1. Show only active indent if it crosses soft wrap-introduced text; // 2. Show indent as is if it doesn't intersect with soft wrap-introduced text; if (selected) { g.drawLine(start.x + 2, start.y, start.x + 2, maxY); } else { int y = start.y; int newY = start.y; SoftWrapModel softWrapModel = editor.getSoftWrapModel(); int lineHeight = editor.getLineHeight(); for (int i = Math.max(0, startLine + lineShift); i < endLine && newY < maxY; i++) { List<? extends SoftWrap> softWraps = softWrapModel.getSoftWrapsForLine(i); int logicalLineHeight = softWraps.size() * lineHeight; if (i > startLine + lineShift) { logicalLineHeight += lineHeight; // We assume that initial 'y' value points just below the target // line. } if (!softWraps.isEmpty() && softWraps.get(0).getIndentInColumns() < indentColumn) { if (y < newY || i > startLine + lineShift) { // There is a possible case that soft wrap is located on // indent start line. g.drawLine(start.x + 2, y, start.x + 2, newY + lineHeight); } newY += logicalLineHeight; y = newY; } else { newY += logicalLineHeight; } FoldRegion foldRegion = foldingModel.getCollapsedRegionAtOffset(doc.getLineEndOffset(i)); if (foldRegion != null && foldRegion.getEndOffset() < doc.getTextLength()) { i = doc.getLineNumber(foldRegion.getEndOffset()); } } if (y < maxY) { g.drawLine(start.x + 2, y, start.x + 2, maxY); } } }
private void paintBorderEffect( Graphics2D g, ClipDetector clipDetector, int startOffset, int endOffset, TextAttributes attributes) { if (!clipDetector.rangeCanBeVisible(startOffset, endOffset)) return; int startLine = myDocument.getLineNumber(startOffset); int endLine = myDocument.getLineNumber(endOffset); if (startLine + 1 == endLine && startOffset == myDocument.getLineStartOffset(startLine) && endOffset == myDocument.getLineStartOffset(endLine)) { // special case of line highlighters endLine--; endOffset = myDocument.getLineEndOffset(endLine); } boolean rounded = attributes.getEffectType() == EffectType.ROUNDED_BOX; int lineHeight = myView.getLineHeight() - 1; g.setColor(attributes.getEffectColor()); VisualPosition startPosition = myView.offsetToVisualPosition(startOffset, true, false); VisualPosition endPosition = myView.offsetToVisualPosition(endOffset, false, true); if (startPosition.line == endPosition.line) { int y = myView.visualLineToY(startPosition.line); TFloatArrayList ranges = adjustedLogicalRangeToVisualRanges(startOffset, endOffset); for (int i = 0; i < ranges.size() - 1; i += 2) { int startX = (int) ranges.get(i); int endX = (int) ranges.get(i + 1); if (rounded) { UIUtil.drawRectPickedOut(g, startX, y, endX - startX, lineHeight); } else { g.drawRect(startX, y, endX - startX, lineHeight); } } } else { int maxWidth = myView.getMaxWidthInLineRange(startPosition.line, endPosition.line) - 1; TFloatArrayList leadingRanges = adjustedLogicalRangeToVisualRanges( startOffset, myView.visualPositionToOffset( new VisualPosition(startPosition.line, Integer.MAX_VALUE, true))); TFloatArrayList trailingRanges = adjustedLogicalRangeToVisualRanges( myView.visualPositionToOffset(new VisualPosition(endPosition.line, 0)), endOffset); if (!leadingRanges.isEmpty() && !trailingRanges.isEmpty()) { boolean containsInnerLines = endPosition.line > startPosition.line + 1; int leadingTopY = myView.visualLineToY(startPosition.line); int leadingBottomY = leadingTopY + lineHeight; int trailingTopY = myView.visualLineToY(endPosition.line); int trailingBottomY = trailingTopY + lineHeight; float start = 0; float end = 0; float leftGap = leadingRanges.get(0) - (containsInnerLines ? 0 : trailingRanges.get(0)); int adjustY = leftGap == 0 ? 2 : leftGap > 0 ? 1 : 0; // avoiding 1-pixel gap between aligned lines for (int i = 0; i < leadingRanges.size() - 1; i += 2) { start = leadingRanges.get(i); end = leadingRanges.get(i + 1); if (i > 0) { drawLine(g, leadingRanges.get(i - 1), leadingBottomY, start, leadingBottomY, rounded); } drawLine(g, start, leadingBottomY + (i == 0 ? adjustY : 0), start, leadingTopY, rounded); if ((i + 2) < leadingRanges.size()) { drawLine(g, start, leadingTopY, end, leadingTopY, rounded); drawLine(g, end, leadingTopY, end, leadingBottomY, rounded); } } end = Math.max(end, maxWidth); drawLine(g, start, leadingTopY, end, leadingTopY, rounded); drawLine(g, end, leadingTopY, end, trailingTopY - 1, rounded); float targetX = trailingRanges.get(trailingRanges.size() - 1); drawLine(g, end, trailingTopY - 1, targetX, trailingTopY - 1, rounded); adjustY = end == targetX ? -2 : -1; // for lastX == targetX we need to avoid a gap when rounding is used for (int i = trailingRanges.size() - 2; i >= 0; i -= 2) { start = trailingRanges.get(i); end = trailingRanges.get(i + 1); drawLine(g, end, trailingTopY + (i == 0 ? adjustY : 0), end, trailingBottomY, rounded); drawLine(g, end, trailingBottomY, start, trailingBottomY, rounded); drawLine(g, start, trailingBottomY, start, trailingTopY, rounded); if (i > 0) { drawLine(g, start, trailingTopY, trailingRanges.get(i - 1), trailingTopY, rounded); } } float lastX = start; if (containsInnerLines) { if (start > 0) { drawLine(g, start, trailingTopY, start, trailingTopY - 1, rounded); drawLine(g, start, trailingTopY - 1, 0, trailingTopY - 1, rounded); drawLine(g, 0, trailingTopY - 1, 0, leadingBottomY + 1, rounded); } else { drawLine(g, start, trailingTopY, 0, leadingBottomY + 1, rounded); } lastX = 0; } targetX = leadingRanges.get(0); if (lastX < targetX) { drawLine(g, lastX, leadingBottomY + 1, targetX, leadingBottomY + 1, rounded); } else { drawLine(g, lastX, leadingBottomY + 1, lastX, leadingBottomY, rounded); drawLine(g, lastX, leadingBottomY, targetX, leadingBottomY, rounded); } } } }
public void doWrapLongLinesIfNecessary( @NotNull final Editor editor, @NotNull final Project project, @NotNull Document document, int startOffset, int endOffset) { // Normalization. int startOffsetToUse = Math.min(document.getTextLength(), Math.max(0, startOffset)); int endOffsetToUse = Math.min(document.getTextLength(), Math.max(0, endOffset)); LineWrapPositionStrategy strategy = LanguageLineWrapPositionStrategy.INSTANCE.forEditor(editor); CharSequence text = document.getCharsSequence(); int startLine = document.getLineNumber(startOffsetToUse); int endLine = document.getLineNumber(Math.max(0, endOffsetToUse - 1)); int maxLine = Math.min(document.getLineCount(), endLine + 1); int tabSize = EditorUtil.getTabSize(editor); if (tabSize <= 0) { tabSize = 1; } int spaceSize = EditorUtil.getSpaceWidth(Font.PLAIN, editor); int[] shifts = new int[2]; // shifts[0] - lines shift. // shift[1] - offset shift. for (int line = startLine; line < maxLine; line++) { int startLineOffset = document.getLineStartOffset(line); int endLineOffset = document.getLineEndOffset(line); final int preferredWrapPosition = calculatePreferredWrapPosition( editor, text, tabSize, spaceSize, startLineOffset, endLineOffset, endOffsetToUse); if (preferredWrapPosition < 0 || preferredWrapPosition >= endLineOffset) { continue; } if (preferredWrapPosition >= endOffsetToUse) { return; } // We know that current line exceeds right margin if control flow reaches this place, so, wrap // it. int wrapOffset = strategy.calculateWrapPosition( document, editor.getProject(), Math.max(startLineOffset, startOffsetToUse), Math.min(endLineOffset, endOffsetToUse), preferredWrapPosition, false, false); if (wrapOffset < 0 // No appropriate wrap position is found. // No point in splitting line when its left part contains only white spaces, example: // line start -> | | <- right margin // | aaaaaaaaaaaaaaaa|aaaaaaaaaaaaaaaaaaaa() <- don't want to wrap this // line even if it exceeds right margin || CharArrayUtil.shiftBackward(text, startLineOffset, wrapOffset - 1, " \t") < startLineOffset) { continue; } // Move caret to the target position and emulate pressing <enter>. editor.getCaretModel().moveToOffset(wrapOffset); emulateEnter(editor, project, shifts); // We know that number of lines is just increased, hence, update the data accordingly. maxLine += shifts[0]; endOffsetToUse += shifts[1]; } }
public int getCaretOffset(Document document) { return document.getLineStartOffset(position.line) + position.column; }