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

The following examples show how to use com.intellij.openapi.editor.Document#getLineNumber() . 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: SuppressLineActionFix.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 lineEnd = doc.getLineEndOffset(line);
        doc.insertString(lineEnd, " //eslint-disable-line " + rule);
        DaemonCodeAnalyzer.getInstance(project).restart(file);
    }
 
Example 2
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 3
Source File: InitialInfoBuilder.java    From consulo with 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 4
Source File: BashFoldingBuilder.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
private static ASTNode appendDescriptors(final ASTNode node, final Document document, final List<FoldingDescriptor> descriptors) {
    if (isFoldable(node)) {
        final IElementType type = node.getElementType();

        int startLine = document.getLineNumber(node.getStartOffset());

        TextRange adjustedFoldingRange = adjustFoldingRange(node);
        int endLine = document.getLineNumber(adjustedFoldingRange.getEndOffset());

        if (startLine + minumumLineOffset(type) <= endLine) {
            descriptors.add(new FoldingDescriptor(node, adjustedFoldingRange));
        }
    }

    if (mayContainFoldBlocks(node)) {
        //work on all child elements
        ASTNode child = node.getFirstChildNode();
        while (child != null) {
            child = appendDescriptors(child, document, descriptors).getTreeNext();
        }
    }

    return node;
}
 
Example 5
Source File: EnterHandler.java    From bamboo-soy with Apache License 2.0 6 votes vote down vote up
private static void handleEnterInComment(
    PsiElement element, @NotNull PsiFile file, @NotNull Editor editor) {
  if (element.getText().startsWith("/*")) {
    Document document = editor.getDocument();

    int caretOffset = editor.getCaretModel().getOffset();
    int lineNumber = document.getLineNumber(caretOffset);

    String lineTextBeforeCaret =
        document.getText(new TextRange(document.getLineStartOffset(lineNumber), caretOffset));
    String lineTextAfterCaret =
        document.getText(new TextRange(caretOffset, document.getLineEndOffset(lineNumber)));

    if (lineTextAfterCaret.equals("*/")) {
      return;
    }

    String toInsert = lineTextBeforeCaret.equals("") ? " * " : "* ";
    insertText(file, editor, toInsert, toInsert.length());
  }
}
 
Example 6
Source File: XBreakpointPanelProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public XBreakpoint<?> findBreakpoint(@Nonnull final Project project, @Nonnull final Document document, final int offset) {
  XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
  int line = document.getLineNumber(offset);
  VirtualFile file = FileDocumentManager.getInstance().getFile(document);
  if (file == null) {
    return null;
  }
  for (XLineBreakpointType<?> type : XDebuggerUtil.getInstance().getLineBreakpointTypes()) {
    XLineBreakpoint<? extends XBreakpointProperties> breakpoint = breakpointManager.findBreakpointAtLine(type, file, line);
    if (breakpoint != null) {
      return breakpoint;
    }
  }

  return null;
}
 
Example 7
Source File: LogConsoleBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
private synchronized void computeSelectedLineAndFilter() {
  // we have to do this in dispatch thread, because ConsoleViewImpl can flush something to document otherwise
  myOriginalDocument = getOriginalDocument();
  if (myOriginalDocument != null) {
    final Editor editor = getEditor();
    LOG.assertTrue(editor != null);
    final Document document = editor.getDocument();
    final int caretOffset = editor.getCaretModel().getOffset();
    myLineUnderSelection = null;
    myLineOffset = -1;
    if (caretOffset > -1 && caretOffset < document.getTextLength()) {
      int line;
      try {
        line = document.getLineNumber(caretOffset);
      }
      catch (IllegalStateException e) {
        throw new IllegalStateException("document.length=" + document.getTextLength() + ", caret offset = " + caretOffset + "; " + e.getMessage(), e);
      }
      if (line > -1 && line < document.getLineCount()) {
        final int startOffset = document.getLineStartOffset(line);
        myLineUnderSelection = document.getText().substring(startOffset, document.getLineEndOffset(line));
        myLineOffset = caretOffset - startOffset;
      }
    }
  }
  ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
    @Override
    public void run() {
      doFilter();
    }
  });
}
 
Example 8
Source File: EditorComponentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int getElementIndex(int i) {
  // For the root element this asks for the index of the offset, which
  // means the line number
  Document document = myEditor.getDocument();
  return document.getLineNumber(i);
}
 
Example 9
Source File: GutterIntentionMenuContributor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void collectActions(@Nonnull Editor hostEditor, @Nonnull PsiFile hostFile, @Nonnull ShowIntentionsPass.IntentionsInfo intentions, int passIdToShowIntentionsFor, int offset) {
  final Project project = hostFile.getProject();
  final Document hostDocument = hostEditor.getDocument();
  final int line = hostDocument.getLineNumber(offset);
  MarkupModelEx model = (MarkupModelEx)DocumentMarkupModel.forDocument(hostDocument, project, true);
  List<RangeHighlighterEx> result = new ArrayList<>();
  Processor<RangeHighlighterEx> processor = Processors.cancelableCollectProcessor(result);
  model.processRangeHighlightersOverlappingWith(hostDocument.getLineStartOffset(line), hostDocument.getLineEndOffset(line), processor);

  for (RangeHighlighterEx highlighter : result) {
    addActions(project, highlighter, intentions.guttersToShow, ((EditorEx)hostEditor).getDataContext());
  }
}
 
Example 10
Source File: UpdatePsiFileCopyright.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean isLineComment(Commenter commenter, PsiComment comment, Document doc) {
  final String lineCommentPrefix = commenter.getLineCommentPrefix();
  if (lineCommentPrefix != null) {
    return comment.getText().startsWith(lineCommentPrefix);
  }
  final TextRange textRange = comment.getTextRange();
  return doc.getLineNumber(textRange.getStartOffset()) == doc.getLineNumber(textRange.getEndOffset());
}
 
Example 11
Source File: VcsSelection.java    From consulo with Apache License 2.0 5 votes vote down vote up
public VcsSelection(Document document, TextRange textRange, String actionName) {
  myDocument = document;
  int startOffset = textRange.getStartOffset();
  mySelectionStartLineNumber = document.getLineNumber(startOffset);
  int endOffset = textRange.getEndOffset();
  mySelectionEndLineNumber = endOffset >= document.getTextLength() ? document.getLineCount() - 1 : document.getLineNumber(endOffset);
  myActionName = VcsBundle.message("show.history.action.name.template", actionName);
  myDialogTitle = VcsBundle.message("show.history.dialog.title.template", actionName);
}
 
Example 12
Source File: CSharpIntroduceHandler.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
public void performAction(CSharpIntroduceOperation operation)
{
	final PsiFile file = operation.getFile();
	if(!CommonRefactoringUtil.checkReadOnlyStatus(file))
	{
		return;
	}
	final Editor editor = operation.getEditor();
	if(editor.getSettings().isVariableInplaceRenameEnabled())
	{
		final TemplateState templateState = TemplateManagerImpl.getTemplateState(operation.getEditor());
		if(templateState != null && !templateState.isFinished())
		{
			return;
		}
	}

	PsiElement element1 = null;
	PsiElement element2 = null;
	final SelectionModel selectionModel = editor.getSelectionModel();
	if(selectionModel.hasSelection())
	{
		element1 = file.findElementAt(selectionModel.getSelectionStart());
		element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1);
		if(element1 instanceof PsiWhiteSpace)
		{
			int startOffset = element1.getTextRange().getEndOffset();
			element1 = file.findElementAt(startOffset);
		}
		if(element2 instanceof PsiWhiteSpace)
		{
			int endOffset = element2.getTextRange().getStartOffset();
			element2 = file.findElementAt(endOffset - 1);
		}
	}
	else
	{
		if(smartIntroduce(operation))
		{
			return;
		}
		final CaretModel caretModel = editor.getCaretModel();
		final Document document = editor.getDocument();
		int lineNumber = document.getLineNumber(caretModel.getOffset());
		if((lineNumber >= 0) && (lineNumber < document.getLineCount()))
		{
			element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
			element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1);
		}
	}
	final Project project = operation.getProject();
	if(element1 == null || element2 == null)
	{
		showCannotPerformError(project, editor);
		return;
	}

	element1 = CSharpRefactoringUtil.getSelectedExpression(project, file, element1, element2);
	if(element1 == null)
	{
		showCannotPerformError(project, editor);
		return;
	}

	if(!checkIntroduceContext(file, editor, element1))
	{
		return;
	}
	operation.setElement(element1);
	performActionOnElement(operation);
}
 
Example 13
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 14
Source File: LineCol.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static LineCol fromOffset(@Nonnull Document document, int offset) {
  int line = document.getLineNumber(offset);
  int column = offset - document.getLineStartOffset(line);
  return new LineCol(line, column);
}
 
Example 15
Source File: ArrangementUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Tries to build a text range on the given arguments basis. Expands to the line start/end if possible.
 * <p/>
 * This method is expected to be used in a situation when we want to arrange complete rows.
 * Example:
 * <pre>
 *   class Test {
 *        void test() {
 *        }
 *      int i;
 *   }
 * </pre>
 * Suppose, we want to locate fields before methods. We can move the exact field and method range then but indent will be broken,
 * i.e. we'll get the result below:
 * <pre>
 *   class Test {
 *        int i;
 *      void test() {
 *        }
 *   }
 * </pre>
 * We can expand field and method range to the whole lines and that would allow to achieve the desired result:
 * <pre>
 *   class Test {
 *      int i;
 *        void test() {
 *        }
 *   }
 * </pre>
 * However, this method is expected to just return given range if there are multiple distinct elements at the same line:
 * <pre>
 *   class Test {
 *     void test1(){} void test2() {} int i;
 *   }
 * </pre>
 *
 * @param initialRange  anchor range
 * @param document      target document against which the ranges are built
 * @return              expanded range if possible; <code>null</code> otherwise
 */
@Nonnull
public static TextRange expandToLineIfPossible(@Nonnull TextRange initialRange, @Nonnull Document document) {
  CharSequence text = document.getCharsSequence();
  String ws = " \t";

  int startLine = document.getLineNumber(initialRange.getStartOffset());
  int lineStartOffset = document.getLineStartOffset(startLine);
  int i = CharArrayUtil.shiftBackward(text, lineStartOffset + 1, initialRange.getStartOffset() - 1, ws);
  if (i != lineStartOffset) {
    return initialRange;
  }

  int endLine = document.getLineNumber(initialRange.getEndOffset());
  int lineEndOffset = document.getLineEndOffset(endLine);
  i = CharArrayUtil.shiftForward(text, initialRange.getEndOffset(), lineEndOffset, ws);

  return i == lineEndOffset ? TextRange.create(lineStartOffset, lineEndOffset) : initialRange;
}
 
Example 16
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 17
Source File: BuildEnterHandler.java    From intellij with Apache License 2.0 4 votes vote down vote up
private static int getIndent(Document doc, PsiElement element) {
  int offset = element.getNode().getStartOffset();
  int lineNumber = doc.getLineNumber(offset);
  return offset - doc.getLineStartOffset(lineNumber);
}
 
Example 18
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 19
Source File: JsonRpcHelpers.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
public static int[] toLine(Document buffer, int offset) {
    int line = buffer.getLineNumber(offset);
    int column = offset - buffer.getLineStartOffset(line);
    return new int[] { line, column };
}
 
Example 20
Source File: DocumentUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static int getStartLine(RangeMarker range) {
  final Document doc = range.getDocument();
  if (doc.getTextLength() == 0) return 0;

  return doc.getLineNumber(range.getStartOffset());
}