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

The following examples show how to use com.intellij.openapi.editor.Document#getLineStartOffset() . 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
Source File: CutLineBackwardAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, DataContext dataContext) {
  final Document document = editor.getDocument();
  int caretOffset = editor.getCaretModel().getOffset();
  if (caretOffset <= 0) {
    return;
  }
  
  // The main idea is to kill everything between the current line start and caret and the whole previous line.
  
  final int caretLine = document.getLineNumber(caretOffset);
  int start;
  
  if (caretLine <= 0) {
    start = 0;
  }
  else {
    start = document.getLineStartOffset(caretLine - 1);
  }
  KillRingUtil.cut(editor, start, caretOffset);
}
 
Example 2
Source File: HaskellDocumentationProvider.java    From intellij-haskforce with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public String generateDoc(PsiElement element, @Nullable PsiElement originalElement) {
    int startOffset = element.getTextRange().getStartOffset();
    int endOffset = element.getTextRange().getEndOffset();
    Module module = ModuleUtilCore.findModuleForPsiElement(element);
    FileDocumentManager fileDocumentManager= FileDocumentManager.getInstance();
    VirtualFile projectFile = element.getContainingFile().getVirtualFile();
    Document cachedDocument = fileDocumentManager.getCachedDocument(projectFile);
    if (cachedDocument == null) {
        return null;
    }
    int startLineNumber = cachedDocument.getLineNumber(startOffset);
    int endLineNumber = cachedDocument.getLineNumber(endOffset);
    int startColumn = startOffset - cachedDocument.getLineStartOffset(startLineNumber);
    int endColumn = endOffset - cachedDocument.getLineStartOffset(endLineNumber);

    // and also correct them for (0,0) vs (1,1) leftmost coordinate (intellij -> ghc)
    VisualPosition startPosition = TypeInfoUtil.correctFor0BasedVS1Based(new VisualPosition(startLineNumber, startColumn));
    VisualPosition endPosition = TypeInfoUtil.correctFor0BasedVS1Based(new VisualPosition(endLineNumber, endColumn));
    return TypeInfoUtil.getTypeInfo(module,startPosition,endPosition, projectFile);
}
 
Example 3
Source File: VcsAwareFormatChangedTextUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: CSharpStatementMover.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
private static PsiElement itIsTheClosingCurlyBraceWeAreMoving(final PsiFile file, final Editor editor)
{
	LineRange range = getLineRangeFromSelection(editor);
	if(range.endLine - range.startLine != 1)
	{
		return null;
	}
	int offset = editor.getCaretModel().getOffset();
	Document document = editor.getDocument();
	int line = document.getLineNumber(offset);
	int lineStartOffset = document.getLineStartOffset(line);
	String lineText = document.getText().substring(lineStartOffset, document.getLineEndOffset(line));
	if(!lineText.trim().equals("}"))
	{
		return null;
	}

	return file.findElementAt(lineStartOffset + lineText.indexOf('}'));
}
 
Example 5
Source File: SuppressActionFix.java    From eslint-plugin with MIT License 6 votes vote down vote up
@Override
    public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
//        final PsiFile file = element.getContainingFile();
        if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

//  InspectionManager inspectionManager = InspectionManager.getInstance(project);
//  ProblemDescriptor descriptor = inspectionManager.createProblemDescriptor(element, element, "", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false);

        final JSElement property = PsiTreeUtil.getParentOfType(element, JSElement.class);
        LOG.assertTrue(property != null);
        final int start = property.getTextRange().getStartOffset();

        @NonNls final Document doc = PsiDocumentManager.getInstance(project).getDocument(file);
        LOG.assertTrue(doc != null);
        final int line = doc.getLineNumber(start);
        final int lineStart = doc.getLineStartOffset(line);

        doc.insertString(lineStart, "/*eslint " + rule + ":0*/\n");
        DaemonCodeAnalyzer.getInstance(project).restart(file);
    }
 
Example 6
Source File: CommentUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static IndentData getMinLineIndent(Document document, int line1, int line2, @Nonnull PsiFile file) {
  CharSequence chars = document.getCharsSequence();
  IndentData minIndent = null;
  for (int line = line1; line <= line2; line++) {
    int lineStart = document.getLineStartOffset(line);
    int textStart = CharArrayUtil.shiftForward(chars, lineStart, " \t");
    if (textStart >= document.getTextLength()) {
      textStart = document.getTextLength();
    }
    else {
      char c = chars.charAt(textStart);
      if (c == '\n' || c == '\r') continue; // empty line
    }
    IndentData indent = IndentData.createFrom(chars, lineStart, textStart, CodeStyle.getIndentOptions(file).TAB_SIZE);
    minIndent = IndentData.min(minIndent, indent);
  }
  if (minIndent == null && line1 == line2 && line1 < document.getLineCount() - 1) {
    return getMinLineIndent(document, line1 + 1, line1 + 1, file);
  }
  return minIndent;
}
 
Example 7
Source File: CallerChooserBase.java    From consulo with 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 8
Source File: FileUrlProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * @param project     Project instance
 * @param virtualFile VirtualFile instance to locate
 * @param lineNum     one-based line number to locate inside {@code virtualFile},
 *                    a non-positive line number doesn't change text caret position inside the file
 * @param columnNum   one-based column number to locate inside {@code virtualFile},
 *                    a non-positive column number doesn't change text caret position inside the file
 * @return Location instance, or null if not found
 */
@javax.annotation.Nullable
public static Location createLocationFor(@Nonnull Project project, @Nonnull VirtualFile virtualFile, int lineNum, int columnNum) {
  final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
  if (psiFile == null) {
    return null;
  }
  if (lineNum <= 0) {
    return PsiLocation.fromPsiElement(psiFile);
  }

  final Document doc = PsiDocumentManager.getInstance(project).getDocument(psiFile);
  if (doc == null) {
    return null;
  }

  if (lineNum > doc.getLineCount()) {
    return PsiLocation.fromPsiElement(psiFile);
  }

  final int lineStartOffset = doc.getLineStartOffset(lineNum - 1);
  final int endOffset = doc.getLineEndOffset(lineNum - 1);

  int offset = Math.min(lineStartOffset + Math.max(columnNum - 1, 0), endOffset);
  PsiElement elementAtLine = null;
  while (offset <= endOffset) {
    elementAtLine = psiFile.findElementAt(offset);
    if (!(elementAtLine instanceof PsiWhiteSpace)) break;
    int length = elementAtLine.getTextLength();
    offset += length > 1 ? length - 1 : 1;
  }

  return PsiLocation.fromPsiElement(project, elementAtLine != null ? elementAtLine : psiFile);
}
 
Example 9
Source File: MarkupModelImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static TextRangeInterval roundToLineBoundaries(@Nonnull Document document, int startOffset, int endOffset) {
  int textLength = document.getTextLength();
  int lineStartOffset = startOffset <= 0 ? 0 : startOffset > textLength ? textLength : document.getLineStartOffset(document.getLineNumber(startOffset));
  int lineEndOffset = endOffset <= 0 ? 0 : endOffset >= textLength ? textLength : document.getLineEndOffset(document.getLineNumber(endOffset));
  return new TextRangeInterval(lineStartOffset, lineEndOffset);
}
 
Example 10
Source File: FixLineSeparatorsAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean areSeparatorsBroken(Document document) {
  final int count = document.getLineCount();
  for (int i = 1; i < count; i += 2) {
    if (document.getLineStartOffset(i) != document.getLineEndOffset(i)) {
      return false;
    }
  }
  return true;    
}
 
Example 11
Source File: EditorDocOps.java    From KodeBeagle with Apache License 2.0 5 votes vote down vote up
public final String getContentsInLines(final String fileContents,
                                       final List<Integer> lineNumbersList) {
    Document document = EditorFactory.getInstance().createDocument(fileContents);
    Set<Integer> lineNumbersSet = new TreeSet<Integer>(lineNumbersList);

    StringBuilder stringBuilder = new StringBuilder();
    int prev = lineNumbersSet.iterator().next();

    for (int line : lineNumbersSet) {
        //Document is 0 indexed
        line = line - 1;
        if (line < document.getLineCount() - 1) {
            if (prev != line - 1) {
                stringBuilder.append(System.lineSeparator());
                prev = line;
            }
            int startOffset = document.getLineStartOffset(line);
            int endOffset = document.getLineEndOffset(line)
                    + document.getLineSeparatorLength(line);
            String code = document.getCharsSequence().
                    subSequence(startOffset, endOffset).
                    toString().trim()
                    + System.lineSeparator();
            stringBuilder.append(code);
        }
    }
    return stringBuilder.toString();
}
 
Example 12
Source File: TextWithMarkupProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static Pair<Integer/* start offset to use */, Integer /* indent symbols to strip */> calcIndentSymbolsToStrip(@Nonnull 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);
}
 
Example 13
Source File: EditorDocOps.java    From KodeBeagle with 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 14
Source File: LogicalPositionCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
private int offsetToLogicalColumn(@Nonnull Document document, int line, int tabSize, int offset) {
  offset = Math.min(offset, document.getLineEndOffset(line));
  int lineStartOffset = document.getLineStartOffset(line);
  int relOffset = offset - lineStartOffset;
  if (columnCache == null) return relOffset;
  int cacheIndex = relOffset / CACHE_FREQUENCY;
  int startOffset = lineStartOffset + cacheIndex * CACHE_FREQUENCY;
  int startColumn = cacheIndex == 0 ? 0 : columnCache[cacheIndex - 1];
  return calcColumn(document.getImmutableCharSequence(), startOffset, startColumn, offset, tabSize);
}
 
Example 15
Source File: MarkdownUtils.java    From markdown-image-kit with MIT License 5 votes vote down vote up
/**
 * 解析每一行数据, 是有效的 Image mark 才解析
 *
 * @param project     the project           当前项目
 * @param document    the document          当前文本
 * @param virtualFile the virtual file      当前处理的文件
 * @return the list
 */
private static List<MarkdownImage> getImageInfoFromFiles(Project project, Document document, VirtualFile virtualFile) {
    List<MarkdownImage> markdownImageList = new ArrayList<>();

    if (document != null) {
        int lineCount = document.getLineCount();
        // 解析每一行文本
        for (int line = 0; line < lineCount; line++) {
            // 获取指定行的第一个字符在全文中的偏移量,行号的取值范围为:[0,getLineCount()-1]
            int startOffset = document.getLineStartOffset(line);
            // 获取指定行的最后一个字符在全文中的偏移量,行号的取值范围为:[0,getLineCount()-1]
            int endOffset = document.getLineEndOffset(line);
            TextRange currentLineTextRange = TextRange.create(startOffset, endOffset);
            String originalLineText = document.getText(currentLineTextRange);

            if (illegalImageMark(project, originalLineText)) {
                continue;
            }
            log.trace("originalLineText: {}", originalLineText);
            MarkdownImage markdownImage;
            if ((markdownImage = analysisImageMark(virtualFile, originalLineText, line)) != null) {
                markdownImageList.add(markdownImage);
            }
        }
    }
    return markdownImageList;
}
 
Example 16
Source File: CopyPasteIndentProcessor.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static int getLineStartSafeOffset(final Document document, int line) {
  if (line >= document.getLineCount()) return document.getTextLength();
  return document.getLineStartOffset(line);
}
 
Example 17
Source File: InspectorService.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static InspectorService.Location outlineToLocation(Project project,
                                                          VirtualFile file,
                                                          FlutterOutline outline,
                                                          Document document) {
  if (file == null) return null;
  if (document == null) return null;
  if (outline == null || outline.getClassName() == null) return null;
  final int documentLength = document.getTextLength();
  int nodeOffset = Math.max(0, Math.min(outline.getCodeOffset(), documentLength));
  final int nodeEndOffset = Math.max(0, Math.min(outline.getCodeOffset() + outline.getCodeLength(), documentLength));

  // The DartOutline will give us the offset of
  // 'child: Foo.bar(...)'
  // but we need the offset of 'bar(...)' for consistentency with the
  // Flutter kernel transformer.
  if (outline.getClassName() != null) {
    final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (psiFile != null) {
      final PsiElement element = psiFile.findElementAt(nodeOffset);
      final DartCallExpression callExpression = PsiTreeUtil.getParentOfType(element, DartCallExpression.class);
      PsiElement match = null;
      if (callExpression != null) {
        final DartExpression expression = callExpression.getExpression();
        if (expression instanceof DartReferenceExpression) {
          final DartReferenceExpression referenceExpression = (DartReferenceExpression)expression;
          final PsiElement[] children = referenceExpression.getChildren();
          if (children.length > 1) {
            // This case handles expressions like 'ClassName.namedConstructor'
            // and 'libraryPrefix.ClassName.namedConstructor'
            match = children[children.length - 1];
          }
          else {
            // this case handles the simple 'ClassName' case.
            match = referenceExpression;
          }
        }
      }
      if (match != null) {
        nodeOffset = match.getTextOffset();
      }
    }
  }
  final int line = document.getLineNumber(nodeOffset);
  final int lineStartOffset = document.getLineStartOffset(line);
  final int column = nodeOffset - lineStartOffset;
  return new InspectorService.Location(file, line + 1, column + 1, nodeOffset);
}
 
Example 18
Source File: ChunkExtractor.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private TextChunk[] extractChunks(@Nonnull UsageInfo2UsageAdapter usageInfo2UsageAdapter, @Nonnull PsiFile file) {
  int absoluteStartOffset = usageInfo2UsageAdapter.getNavigationOffset();
  if (absoluteStartOffset == -1) return TextChunk.EMPTY_ARRAY;

  Document visibleDocument = myDocument instanceof DocumentWindow ? ((DocumentWindow)myDocument).getDelegate() : myDocument;
  int visibleStartOffset = myDocument instanceof DocumentWindow ? ((DocumentWindow)myDocument).injectedToHost(absoluteStartOffset) : absoluteStartOffset;

  int lineNumber = myDocument.getLineNumber(absoluteStartOffset);
  int visibleLineNumber = visibleDocument.getLineNumber(visibleStartOffset);
  int visibleColumnNumber = visibleStartOffset - visibleDocument.getLineStartOffset(visibleLineNumber);
  final List<TextChunk> result = new ArrayList<TextChunk>();
  appendPrefix(result, visibleLineNumber, visibleColumnNumber);

  int fragmentToShowStart = myDocument.getLineStartOffset(lineNumber);
  int fragmentToShowEnd = fragmentToShowStart < myDocument.getTextLength() ? myDocument.getLineEndOffset(lineNumber) : 0;
  if (fragmentToShowStart > fragmentToShowEnd) return TextChunk.EMPTY_ARRAY;

  final CharSequence chars = myDocument.getCharsSequence();
  if (fragmentToShowEnd - fragmentToShowStart > MAX_LINE_LENGTH_TO_SHOW) {
    final int lineStartOffset = fragmentToShowStart;
    fragmentToShowStart = Math.max(lineStartOffset, absoluteStartOffset - OFFSET_BEFORE_TO_SHOW_WHEN_LONG_LINE);

    final int lineEndOffset = fragmentToShowEnd;
    Segment segment = usageInfo2UsageAdapter.getUsageInfo().getSegment();
    int usage_length = segment != null ? segment.getEndOffset() - segment.getStartOffset() : 0;
    fragmentToShowEnd = Math.min(lineEndOffset, absoluteStartOffset + usage_length + OFFSET_AFTER_TO_SHOW_WHEN_LONG_LINE);

    // if we search something like a word, then expand shown context from one symbol before / after at least for word boundary
    // this should not cause restarts of the lexer as the tokens are usually words
    if (usage_length > 0 && StringUtil.isJavaIdentifierStart(chars.charAt(absoluteStartOffset)) && StringUtil.isJavaIdentifierStart(chars.charAt(absoluteStartOffset + usage_length - 1))) {
      while (fragmentToShowEnd < lineEndOffset && StringUtil.isJavaIdentifierStart(chars.charAt(fragmentToShowEnd - 1))) ++fragmentToShowEnd;
      while (fragmentToShowStart > lineStartOffset && StringUtil.isJavaIdentifierStart(chars.charAt(fragmentToShowStart))) --fragmentToShowStart;
      if (fragmentToShowStart != lineStartOffset) ++fragmentToShowStart;
      if (fragmentToShowEnd != lineEndOffset) --fragmentToShowEnd;
    }
  }
  if (myDocument instanceof DocumentWindow) {
    List<TextRange> editable = InjectedLanguageManager.getInstance(file.getProject()).intersectWithAllEditableFragments(file, new TextRange(fragmentToShowStart, fragmentToShowEnd));
    for (TextRange range : editable) {
      createTextChunks(usageInfo2UsageAdapter, chars, range.getStartOffset(), range.getEndOffset(), true, result);
    }
    return result.toArray(new TextChunk[result.size()]);
  }
  return createTextChunks(usageInfo2UsageAdapter, chars, fragmentToShowStart, fragmentToShowEnd, true, result);
}
 
Example 19
Source File: DocumentUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static int getFirstNonSpaceCharOffset(@Nonnull Document document, int line) {
  int startOffset = document.getLineStartOffset(line);
  int endOffset = document.getLineEndOffset(line);
  return getFirstNonSpaceCharOffset(document, startOffset, endOffset);
}
 
Example 20
Source File: EnterAfterUnmatchedBraceHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Formats the code block between caret and inserted braces.
 *
 * @param file                target PSI file
 * @param document            target document
 * @param caretOffset         target caret offset
 * @param rBracesInsertOffset target position to insert
 * @param generatedRBraces    string of '}' to insert
 */
protected void formatCodeFragmentBetweenBraces(@Nonnull PsiFile file,
                                               @Nonnull Document document,
                                               int caretOffset,
                                               int rBracesInsertOffset,
                                               String generatedRBraces) {
  Project project = file.getProject();
  long stamp = document.getModificationStamp();
  boolean closingBraceIndentAdjusted;
  try {
    PsiDocumentManager.getInstance(project).commitDocument(document);
    CodeStyleManager.getInstance(project).adjustLineIndent(file, new TextRange(caretOffset, rBracesInsertOffset + 2));
  }
  catch (IncorrectOperationException e) {
    LOG.error(e);
  }
  finally {
    closingBraceIndentAdjusted = stamp != document.getModificationStamp();
    // do you remember that we insert the '\n'? here we take it back!
    document.deleteString(caretOffset, caretOffset + 1);
  }

  // There is a possible case that formatter was unable to adjust line indent for the closing brace (that is the case for plain text
  // document for example). Hence, we're trying to do the manually.
  if (!closingBraceIndentAdjusted) {
    int line = document.getLineNumber(rBracesInsertOffset);
    StringBuilder buffer = new StringBuilder();
    int start = document.getLineStartOffset(line);
    int end = document.getLineEndOffset(line);
    final CharSequence text = document.getCharsSequence();
    for (int i = start; i < end; i++) {
      char c = text.charAt(i);
      if (c != ' ' && c != '\t') {
        break;
      }
      else {
        buffer.append(c);
      }
    }
    if (buffer.length() > 0) {
      document.insertString(rBracesInsertOffset + 1, buffer);
    }
  }
}