Java Code Examples for com.intellij.openapi.editor.Document#getLineEndOffset()

The following examples show how to use com.intellij.openapi.editor.Document#getLineEndOffset() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public boolean hasNonClosedLiteral(@NotNull Editor editor, @NotNull HighlighterIterator iterator, int offset) {
    Document document = editor.getDocument();
    int lineEndOffset = document.getLineEndOffset(document.getLineNumber(offset));
    if (offset < lineEndOffset) {
        CharSequence charSequence = document.getCharsSequence();
        char openQuote = charSequence.charAt(offset);
        int nextCharOffset = offset + 1;
        if (nextCharOffset < lineEndOffset && charSequence.charAt(nextCharOffset) == openQuote) {
            return true;
        }

        for (int i = nextCharOffset + 1; i < lineEndOffset; ++i) {
            if (charSequence.charAt(i) == openQuote) {
                return false;
            }
        }
    }

    return true;
}
 
Example 2
private static int calculateOffset(@Nonnull Document document,
                                   final int line,
                                   final int column,
                                   int tabSize) {
  int offset;
  if (0 <= line && line < document.getLineCount()) {
    final int lineStart = document.getLineStartOffset(line);
    final int lineEnd = document.getLineEndOffset(line);
    final CharSequence docText = document.getCharsSequence();

    offset = lineStart;
    int col = 0;
    while (offset < lineEnd && col < column) {
      col += docText.charAt(offset) == '\t' ? tabSize : 1;
      offset++;
    }
  }
  else {
    offset = document.getTextLength();
  }
  return offset;
}
 
Example 3
private int getOffset(Document document, InjectDirection injectDirection) {
    switch (injectDirection) {
        case BEFORE:
        case AFTER:
        case PREV_LINE:
        case NEXT_LINE:
        case REPLACE:
            return getDirectedOffset(document, injectDirection);
        case START_OF_FILE:
            return 0;
        case SOF_END_OF_LINE:
            return document.getLineEndOffset(0);
        case END_OF_FILE:
            return document.getText().length() - 1;
        case EOF_START_OF_LINE:
            return document.getLineStartOffset(document.getLineCount() - 1);
    }

    throw new RuntimeException("Unknown InjectDirection");
}
 
Example 4
@Override
public boolean hasNonClosedLiteral(Editor editor, HighlighterIterator iterator, int offset) {
  int start = iterator.getStart();
  try {
    Document doc = editor.getDocument();
    CharSequence chars = doc.getCharsSequence();
    int lineEnd = doc.getLineEndOffset(doc.getLineNumber(offset));

    while (!iterator.atEnd() && iterator.getStart() < lineEnd) {
      IElementType tokenType = iterator.getTokenType();

      if (myLiteralTokenSet.contains(tokenType)) {
        if (isNonClosedLiteral(iterator, chars)) return true;
      }
      iterator.advance();
    }
  }
  finally {
    while(iterator.atEnd() || iterator.getStart() != start) iterator.retreat();
  }

  return false;
}
 
Example 5
protected void createSuppression(@NotNull Project project, @NotNull PsiElement element, @NotNull PsiElement container) throws IncorrectOperationException {
    if (element.isValid()) {
        PsiFile psiFile = element.getContainingFile();
        if (psiFile != null) {
            psiFile = psiFile.getOriginalFile();
        }

        if (psiFile != null && psiFile.isValid()) {
            final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
            if (document != null) {
                int lineNo = document.getLineNumber(element.getTextOffset());
                final int lineEndOffset = document.getLineEndOffset(lineNo);
                CommandProcessor.getInstance().executeCommand(project, new Runnable() {
                    public void run() {
                        document.insertString(lineEndOffset, " //eslint-disable-line");
                    }
                }, null, null);
            }
        }
    }
}
 
Example 6
Source Project: consulo   File: UsageInfo2UsageAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
public String getPlainText() {
  int startOffset = getNavigationOffset();
  final PsiElement element = getElement();
  if (element != null && startOffset != -1) {
    final Document document = getDocument();
    if (document != null) {
      int lineNumber = document.getLineNumber(startOffset);
      int lineStart = document.getLineStartOffset(lineNumber);
      int lineEnd = document.getLineEndOffset(lineNumber);
      String prefixSuffix = null;

      if (lineEnd - lineStart > ChunkExtractor.MAX_LINE_LENGTH_TO_SHOW) {
        prefixSuffix = "...";
        lineStart = Math.max(startOffset - ChunkExtractor.OFFSET_BEFORE_TO_SHOW_WHEN_LONG_LINE, lineStart);
        lineEnd = Math.min(startOffset + ChunkExtractor.OFFSET_AFTER_TO_SHOW_WHEN_LONG_LINE, lineEnd);
      }
      String s = document.getCharsSequence().subSequence(lineStart, lineEnd).toString();
      if (prefixSuffix != null) s = prefixSuffix + s + prefixSuffix;
      return s;
    }
  }
  return UsageViewBundle.message("node.invalid");
}
 
Example 7
@Nonnull
private static List<TextRange> getChangedTextRanges(@Nonnull Document document, @Nonnull List<Range> changedRanges) {
  List<TextRange> ranges = ContainerUtil.newArrayList();
  for (Range range : changedRanges) {
    if (range.getType() != Range.DELETED) {
      int changeStartLine = range.getLine1();
      int changeEndLine = range.getLine2();

      int lineStartOffset = document.getLineStartOffset(changeStartLine);
      int lineEndOffset = document.getLineEndOffset(changeEndLine - 1);

      ranges.add(new TextRange(lineStartOffset, lineEndOffset));
    }
  }
  return ranges;
}
 
Example 8
Source Project: consulo   File: EditorComponentImpl.java    License: Apache License 2.0 6 votes vote down vote up
private int getWordAtOffsetEnd(int offset) {
  Document document = myEditor.getDocument();

  CharSequence text = document.getCharsSequence();
  if (offset >= document.getTextLength() - 1 || document.getLineCount() == 0) {
    return offset;
  }

  int newOffset = offset + 1;
  int lineNumber = myEditor.offsetToLogicalPosition(offset).line;
  int maxOffset = document.getLineEndOffset(lineNumber);
  if (newOffset > maxOffset) {
    if (lineNumber + 1 >= document.getLineCount()) {
      return offset;
    }
    maxOffset = document.getLineEndOffset(lineNumber + 1);
  }
  boolean camel = myEditor.getSettings().isCamelWords();
  for (; newOffset < maxOffset; newOffset++) {
    if (EditorActionUtil.isWordEnd(text, newOffset, camel)) {
      break;
    }
  }

  return newOffset;
}
 
Example 9
Source Project: consulo   File: InitialInfoBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isAffectedByFormatting(final Block block) {
  if (myAffectedRanges == null) return true;

  List<FormatTextRange> allRanges = myAffectedRanges.getRanges();
  Document document = myModel.getDocument();
  int docLength = document.getTextLength();

  for (FormatTextRange range : allRanges) {
    int startOffset = range.getStartOffset();
    if (startOffset >= docLength) continue;

    int lineNumber = document.getLineNumber(startOffset);
    int lineEndOffset = document.getLineEndOffset(lineNumber);

    int blockStartOffset = block.getTextRange().getStartOffset();
    if (blockStartOffset >= startOffset && blockStartOffset < lineEndOffset) {
      return true;
    }
  }

  return false;
}
 
Example 10
Source Project: consulo   File: DocumentUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static int getLineEndOffset(int offset, @Nonnull Document document) {
  if (offset < 0 || offset > document.getTextLength()) {
    return offset;
  }
  int lineNumber = document.getLineNumber(offset);
  return document.getLineEndOffset(lineNumber);
}
 
Example 11
Source Project: consulo   File: EmacsStyleIndentAction.java    License: Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void invoke(@Nonnull final Project project, @Nonnull final Editor editor, @Nonnull final PsiFile file) {
  if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return;
  PsiDocumentManager.getInstance(project).commitAllDocuments();

  if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
    return;
  }

  EmacsProcessingHandler emacsProcessingHandler = LanguageEmacsExtension.INSTANCE.forLanguage(file.getLanguage());
  if (emacsProcessingHandler != null) {
    EmacsProcessingHandler.Result result = emacsProcessingHandler.changeIndent(project, editor, file);
    if (result == EmacsProcessingHandler.Result.STOP) {
      return;
    }
  }

  final Document document = editor.getDocument();
  final int startOffset = editor.getCaretModel().getOffset();
  final int line = editor.offsetToLogicalPosition(startOffset).line;
  final int col = editor.getCaretModel().getLogicalPosition().column;
  final int lineStart = document.getLineStartOffset(line);
  final int initLineEnd = document.getLineEndOffset(line);
  try{
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    final int newPos = codeStyleManager.adjustLineIndent(file, lineStart);
    final int newCol = newPos - lineStart;
    final int lineInc = document.getLineEndOffset(line) - initLineEnd;
    if (newCol >= col + lineInc && newCol >= 0) {
      final LogicalPosition pos = new LogicalPosition(line, newCol);
      editor.getCaretModel().moveToLogicalPosition(pos);
      editor.getSelectionModel().removeSelection();
      editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    }
  }
  catch(IncorrectOperationException e){
    LOG.error(e);
  }
}
 
Example 12
Source Project: consulo   File: Bookmark.java    License: Apache License 2.0 5 votes vote down vote up
public void release() {
  int line = getLine();
  if (line < 0) {
    return;
  }
  final Document document = getDocument();
  if (document == null) return;
  MarkupModelEx markup = (MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true);
  final Document markupDocument = markup.getDocument();
  if (markupDocument.getLineCount() <= line) return;
  final int startOffset = markupDocument.getLineStartOffset(line);
  final int endOffset = markupDocument.getLineEndOffset(line);

  final Ref<RangeHighlighterEx> found = new Ref<RangeHighlighterEx>();
  markup.processRangeHighlightersOverlappingWith(startOffset, endOffset, new Processor<RangeHighlighterEx>() {
    @Override
    public boolean process(RangeHighlighterEx highlighter) {
      GutterMark renderer = highlighter.getGutterIconRenderer();
      if (renderer instanceof MyGutterIconRenderer && ((MyGutterIconRenderer)renderer).myBookmark == Bookmark.this) {
        found.set(highlighter);
        return false;
      }
      return true;
    }
  });
  if (!found.isNull()) found.get().dispose();
}
 
Example 13
Source Project: consulo   File: EditorComponentImpl.java    License: Apache License 2.0 5 votes vote down vote up
private int getLineAtOffsetEnd(int offset) {
  Document document = myEditor.getDocument();
  if (offset == 0) {
    return 0;
  }
  int lineNumber = myEditor.offsetToLogicalPosition(offset).line;
  return document.getLineEndOffset(lineNumber);
}
 
Example 14
Source Project: KodeBeagle   File: EditorDocOps.java    License: Apache License 2.0 5 votes vote down vote up
public final Pair<Integer, Integer> getLineOffSets(final Editor projectEditor,
                                                   final int distance) {
    Document document = projectEditor.getDocument();
    SelectionModel selectionModel = projectEditor.getSelectionModel();
    int head = 0;
    int tail = document.getLineCount() - 1;
    if (selectionModel.hasSelection()) {
        head = document.getLineNumber(selectionModel.getSelectionStart());
        tail = document.getLineNumber(selectionModel.getSelectionEnd());
        /*Selection model gives one more line if line is selected completely.
          By Checking if complete line is slected and decreasing tail*/
        if ((document.getLineStartOffset(tail) == selectionModel.getSelectionEnd())) {
            tail--;
        }

    } else {
        int currentLine = document.getLineNumber(projectEditor.getCaretModel().getOffset());

        if (currentLine - distance >= 0) {
            head = currentLine - distance;
        }

        if (currentLine + distance <= document.getLineCount() - 1) {
            tail = currentLine + distance;
        }
    }
    int start = document.getLineStartOffset(head);
    int end = document.getLineEndOffset(tail);
    Pair<Integer, Integer> pair = new Pair<>(start, end);
    return pair;
}
 
Example 15
Source Project: consulo   File: LineLayout.java    License: Apache License 2.0 5 votes vote down vote up
private static List<BidiRun> createFragments(@Nonnull EditorView view, int line, boolean skipBidiLayout) {
  Document document = view.getEditor().getDocument();
  int lineStartOffset = document.getLineStartOffset(line);
  int lineEndOffset = document.getLineEndOffset(line);
  if (lineEndOffset <= lineStartOffset) return Collections.emptyList();
  if (skipBidiLayout) return Collections.singletonList(new BidiRun(lineEndOffset - lineStartOffset));
  CharSequence text = document.getImmutableCharSequence().subSequence(lineStartOffset, lineEndOffset);
  char[] chars = CharArrayUtil.fromSequence(text);
  return createRuns(view, chars, lineStartOffset);
}
 
Example 16
Source Project: consulo   File: KillToWordEndAction.java    License: Apache License 2.0 5 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
  CaretModel caretModel = editor.getCaretModel();
  int caretOffset = caretModel.getOffset();
  Document document = editor.getDocument();
  if (caretOffset >= document.getTextLength()) {
    return;
  }

  int caretLine = caretModel.getLogicalPosition().line;
  int lineEndOffset = document.getLineEndOffset(caretLine);
  CharSequence text = document.getCharsSequence();
  boolean camel = editor.getSettings().isCamelWords();
  for (int i = caretOffset + 1; i < lineEndOffset; i++) {
    if (EditorActionUtil.isWordEnd(text, i, camel)) {
      KillRingUtil.cut(editor, caretOffset, i);
      return;
    }
  }
  
  int end = lineEndOffset;
  if (caretLine < document.getLineCount() - 1) {
    // No word end found between the current position and line end, hence, remove line feed sign if possible.
    end++;
  }

  if (end > caretOffset) {
    KillRingUtil.cut(editor, caretOffset, end);
  }
}
 
Example 17
Source Project: consulo   File: CallerChooserBase.java    License: Apache License 2.0 5 votes vote down vote up
private String getText(final M method) {
  if (method == null) return "";
  final PsiFile file = method.getContainingFile();
  Document document = PsiDocumentManager.getInstance(myProject).getDocument(file);
  if (document != null) {
    final int start = document.getLineStartOffset(document.getLineNumber(method.getTextRange().getStartOffset()));
    final int end = document.getLineEndOffset(document.getLineNumber(method.getTextRange().getEndOffset()));
    return document.getText().substring(start, end);
  }
  return "";
}
 
Example 18
Source Project: consulo   File: HighlightHandlerBase.java    License: Apache License 2.0 5 votes vote down vote up
public static String getLineTextErrorStripeTooltip(Document document, int offset, boolean escape) {
  final int lineNumber = document.getLineNumber(offset);
  int lineStartOffset = document.getLineStartOffset(lineNumber);
  int lineEndOffset = document.getLineEndOffset(lineNumber);
  int lineFragmentEndOffset = Math.min(lineStartOffset + 140, lineEndOffset);
  String lineText = document.getText().substring(lineStartOffset, lineFragmentEndOffset);
  if (lineFragmentEndOffset != lineEndOffset) {
    lineText = lineText.trim() + "...";
  }
  return "  " + (escape ? StringUtil.escapeXml(lineText.trim()) : lineText.trim()) + "  ";
}
 
Example 19
@Override
public Result preprocessEnter(@Nonnull PsiFile file,
                              @Nonnull Editor editor,
                              @Nonnull Ref<Integer> caretOffset,
                              @Nonnull Ref<Integer> caretAdvance,
                              @Nonnull DataContext dataContext,
                              EditorActionHandler originalHandler) {
  if (!CodeInsightSettings.getInstance().SMART_INDENT_ON_ENTER) {
    return Result.Continue;
  }

  Document document = editor.getDocument();
  CharSequence text = document.getCharsSequence();
  int line = document.getLineNumber(caretOffset.get());
  int start = document.getLineStartOffset(line);
  int end = document.getLineEndOffset(line);

  CodeDocumentationUtil.CommentContext commentContext = CodeDocumentationUtil.tryParseCommentContext(file, text, caretOffset.get(), start);
  if (!commentContext.docAsterisk) {
    return Result.Continue;
  }

  Context context = parse(text, start, end, caretOffset.get());
  if (!context.shouldGenerateLine()) {
    return context.shouldIndent() ? Result.DefaultForceIndent : Result.Continue;
  }

  String indentInsideJavadoc = CodeDocumentationUtil.getIndentInsideJavadoc(document, caretOffset.get());

  boolean restoreCaret = false;
  if (caretOffset.get() != context.endTagStartOffset) {
    editor.getCaretModel().moveToOffset(context.endTagStartOffset);
    restoreCaret = true;
  }

  originalHandler.execute(editor, dataContext);
  Project project = editor.getProject();
  if (indentInsideJavadoc != null && project != null && CodeStyleSettingsManager.getSettings(project).JD_LEADING_ASTERISKS_ARE_ENABLED) {
    document.insertString(editor.getCaretModel().getOffset(), "*" + indentInsideJavadoc);
  }

  if (restoreCaret) {
    editor.getCaretModel().moveToOffset(caretOffset.get());
  }

  return Result.DefaultForceIndent;
}
 
Example 20
@Override
protected void doBeforeCharDeleted(char c, PsiFile file, Editor editor) {
  Project project = file.getProject();
  Document document = editor.getDocument();
  CharSequence charSequence = document.getImmutableCharSequence();
  CaretModel caretModel = editor.getCaretModel();
  int caretOffset = caretModel.getOffset();
  LogicalPosition pos = caretModel.getLogicalPosition();
  int lineStartOffset = document.getLineStartOffset(pos.line);
  int beforeWhitespaceOffset = CharArrayUtil.shiftBackward(charSequence, caretOffset - 1, " \t") + 1;
  if (beforeWhitespaceOffset != lineStartOffset) {
    myReplacement = null;
    return;
  }
  PsiDocumentManager.getInstance(project).commitDocument(document);
  CodeStyleFacade codeStyleFacade = CodeStyleFacade.getInstance(project);
  myReplacement = codeStyleFacade.getLineIndent(document, lineStartOffset);
  if (myReplacement == null) {
    return;
  }
  int tabSize = codeStyleFacade.getTabSize(file.getFileType());
  int targetColumn = getWidth(myReplacement, tabSize);
  int endOffset = CharArrayUtil.shiftForward(charSequence, caretOffset, " \t");
  LogicalPosition logicalPosition = caretOffset < endOffset ? editor.offsetToLogicalPosition(endOffset) : pos;
  int currentColumn = logicalPosition.column;
  if (currentColumn > targetColumn) {
    myStartOffset = lineStartOffset;
  }
  else if (logicalPosition.line == 0) {
    myStartOffset = 0;
    myReplacement = "";
  }
  else {
    int prevLineEndOffset = document.getLineEndOffset(logicalPosition.line - 1);
    myStartOffset = CharArrayUtil.shiftBackward(charSequence, prevLineEndOffset - 1, " \t") + 1;
    if (myStartOffset != document.getLineStartOffset(logicalPosition.line - 1)) {
      int spacing = CodeStyleManager.getInstance(project).getSpacing(file, endOffset);
      myReplacement = StringUtil.repeatSymbol(' ', Math.max(0, spacing));
    }
  }
}