com.intellij.util.text.CharArrayUtil Java Examples

The following examples show how to use com.intellij.util.text.CharArrayUtil. 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: ParameterInfoController.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int adjustOffsetToInlay(int offset) {
  CharSequence text = myEditor.getDocument().getImmutableCharSequence();
  int hostWhitespaceStart = CharArrayUtil.shiftBackward(text, offset, WHITESPACE) + 1;
  int hostWhitespaceEnd = CharArrayUtil.shiftForward(text, offset, WHITESPACE);
  Editor hostEditor = myEditor;
  if (myEditor instanceof EditorWindow) {
    hostEditor = ((EditorWindow)myEditor).getDelegate();
    hostWhitespaceStart = ((EditorWindow)myEditor).getDocument().injectedToHost(hostWhitespaceStart);
    hostWhitespaceEnd = ((EditorWindow)myEditor).getDocument().injectedToHost(hostWhitespaceEnd);
  }
  List<Inlay> inlays = ParameterHintsPresentationManager.getInstance().getParameterHintsInRange(hostEditor, hostWhitespaceStart, hostWhitespaceEnd);
  for (Inlay inlay : inlays) {
    int inlayOffset = inlay.getOffset();
    if (myEditor instanceof EditorWindow) {
      if (((EditorWindow)myEditor).getDocument().getHostRange(inlayOffset) == null) continue;
      inlayOffset = ((EditorWindow)myEditor).getDocument().hostToInjected(inlayOffset);
    }
    return inlayOffset;
  }
  return offset;
}
 
Example #2
Source File: PasteHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ForLoopThatDoesntUseLoopVariable")
private static void indentPlainTextBlock(final Document document, final int startOffset, final int endOffset, final int indentLevel) {
  CharSequence chars = document.getCharsSequence();
  int spaceEnd = CharArrayUtil.shiftForward(chars, startOffset, " \t");
  int line = document.getLineNumber(startOffset);
  if (spaceEnd > endOffset || indentLevel <= 0 || line >= document.getLineCount() - 1 || chars.charAt(spaceEnd) == '\n') {
    return;
  }

  int linesToAdjustIndent = 0;
  for (int i = line + 1; i < document.getLineCount(); i++) {
    if (document.getLineStartOffset(i) >= endOffset) {
      break;
    }
    linesToAdjustIndent++;
  }

  String indentString = StringUtil.repeatSymbol(' ', indentLevel);

  for (; linesToAdjustIndent > 0; linesToAdjustIndent--) {
    int lineStartOffset = document.getLineStartOffset(++line);
    document.insertString(lineStartOffset, indentString);
  }
}
 
Example #3
Source File: IndentCalculator.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
protected String getBaseIndent(@Nonnull SemanticEditorPosition currPosition) {
  CharSequence docChars = myEditor.getDocument().getCharsSequence();
  int offset = currPosition.getStartOffset();
  if (offset > 0) {
    int indentLineOffset = myBaseLineOffsetCalculator.getOffsetInBaseIndentLine(currPosition);
    if (indentLineOffset > 0) {
      int indentStart = CharArrayUtil.shiftBackwardUntil(docChars, indentLineOffset, "\n") + 1;
      if (indentStart >= 0) {
        int indentEnd = CharArrayUtil.shiftForward(docChars, indentStart, " \t");
        if (indentEnd > indentStart) {
          return docChars.subSequence(indentStart, indentEnd).toString();
        }
      }
    }
  }
  return "";
}
 
Example #4
Source File: FilteredIndentsHighlightingPass.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int findCodeConstructStartLine(int startLine) {
  DocumentEx document = myEditor.getDocument();
  CharSequence text = document.getImmutableCharSequence();
  int lineStartOffset = document.getLineStartOffset(startLine);
  int firstNonWsOffset = CharArrayUtil.shiftForward(text, lineStartOffset, " \t");
  FileType type = PsiUtilBase.getPsiFileAtOffset(myFile, firstNonWsOffset).getFileType();
  Language language = PsiUtilCore.getLanguageAtOffset(myFile, firstNonWsOffset);
  BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(type, language);
  HighlighterIterator iterator = myEditor.getHighlighter().createIterator(firstNonWsOffset);
  if (braceMatcher.isLBraceToken(iterator, text, type)) {
    int codeConstructStart = braceMatcher.getCodeConstructStart(myFile, firstNonWsOffset);
    return document.getLineNumber(codeConstructStart);
  }
  else {
    return startLine;
  }
}
 
Example #5
Source File: EnterHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Adjusts indentation of the line with {@code offset} in {@code document}.
 *
 * @param language used for code style extraction
 * @param document for indent adjustment
 * @param editor   used for code style extraction
 * @param offset   in {@code document} for indent adjustment
 * @return new offset in the {@code document} after commit-free indent adjustment or
 * {@code -1} if commit-free indent adjustment is unavailable in position.
 */
public static int adjustLineIndentNoCommit(Language language, @Nonnull Document document, @Nonnull Editor editor, int offset) {
  final CharSequence docChars = document.getCharsSequence();
  int indentStart = CharArrayUtil.shiftBackwardUntil(docChars, offset - 1, "\n") + 1;
  int indentEnd = CharArrayUtil.shiftForward(docChars, indentStart, " \t");
  String newIndent = CodeStyleFacade.getInstance(editor.getProject()).getLineIndent(editor, language, offset, false);
  if (newIndent == null) {
    return -1;
  }
  if (newIndent == LineIndentProvider.DO_NOT_ADJUST) {
    return offset;
  }
  int delta = newIndent.length() - (indentEnd - indentStart);
  document.replaceString(indentStart, indentEnd, newIndent);
  return offset <= indentEnd ? (indentStart + newIndent.length()) : (offset + delta);
}
 
Example #6
Source File: ConsoleViewImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void addFoldRegion(@Nonnull Document document, @Nonnull ConsoleFolding folding, int startLine, int endLine) {
  List<String> toFold = new ArrayList<>(endLine - startLine + 1);
  for (int i = startLine; i <= endLine; i++) {
    toFold.add(EditorHyperlinkSupport.getLineText(document, i, false));
  }

  int oStart = document.getLineStartOffset(startLine);
  if (oStart > 0 && folding.shouldBeAttachedToThePreviousLine()) oStart--;
  int oEnd = CharArrayUtil.shiftBackward(document.getImmutableCharSequence(), document.getLineEndOffset(endLine) - 1, " \t") + 1;

  String placeholder = folding.getPlaceholderText(getProject(), toFold);
  FoldRegion region = placeholder == null ? null : myEditor.getFoldingModel().addFoldRegion(oStart, oEnd, placeholder);
  if (region != null) {
    region.setExpanded(false);
    region.putUserData(USED_FOLDING_KEY, folding);
  }
}
 
Example #7
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 #8
Source File: DuplocatorUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean isIgnoredNode(PsiElement element) {
  // ex. "var i = 0" in AS: empty JSAttributeList should be skipped
  /*if (element.getText().length() == 0) {
    return true;
  }*/

  if (element instanceof PsiWhiteSpace || element instanceof PsiErrorElement || element instanceof PsiComment) {
    return true;
  }

  if (!(element instanceof LeafElement)) {
    return false;
  }

  if (CharArrayUtil.containsOnlyWhiteSpaces(element.getText())) {
    return true;
  }

  EquivalenceDescriptorProvider descriptorProvider = EquivalenceDescriptorProvider.getInstance(element);
  if (descriptorProvider == null) {
    return false;
  }

  final IElementType elementType = ((LeafElement)element).getElementType();
  return descriptorProvider.getIgnoredTokens().contains(elementType);
}
 
Example #9
Source File: MinusculeMatcherImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private FList<TextRange> matchBySubstring(@Nonnull String name) {
  boolean infix = isPatternChar(0, '*');
  char[] patternWithoutWildChar = filterWildcard(myPattern);
  if (name.length() < patternWithoutWildChar.length) {
    return null;
  }
  if (infix) {
    int index = StringUtil.indexOfIgnoreCase(name, new CharArrayCharSequence(patternWithoutWildChar, 0, patternWithoutWildChar.length), 0);
    if (index >= 0) {
      return FList.<TextRange>emptyList().prepend(TextRange.from(index, patternWithoutWildChar.length - 1));
    }
    return null;
  }
  if (CharArrayUtil.regionMatches(patternWithoutWildChar, 0, patternWithoutWildChar.length, name)) {
    return FList.<TextRange>emptyList().prepend(new TextRange(0, patternWithoutWildChar.length));
  }
  return null;
}
 
Example #10
Source File: HungryBackspaceAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(@Nonnull Editor editor, Caret caret, DataContext dataContext) {
  final Document document = editor.getDocument();
  final int caretOffset = editor.getCaretModel().getOffset();
  if (caretOffset < 1) {
    return;
  }

  final SelectionModel selectionModel = editor.getSelectionModel();
  final CharSequence text = document.getCharsSequence();
  final char c = text.charAt(caretOffset - 1);
  if (!selectionModel.hasSelection() && StringUtil.isWhiteSpace(c)) {
    int startOffset = CharArrayUtil.shiftBackward(text, caretOffset - 2, "\t \n") + 1;
    document.deleteString(startOffset, caretOffset);
  }
  else {
    final EditorActionHandler handler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_BACKSPACE);
    handler.execute(editor, caret, dataContext);
  }
}
 
Example #11
Source File: FormatterImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static int getLineStartOffset(final int offset, final WhiteSpace whiteSpace, final FormattingDocumentModel documentModel) {
  int lineStartOffset = offset;

  CharSequence text = getCharSequence(documentModel);
  lineStartOffset = CharArrayUtil.shiftBackwardUntil(text, lineStartOffset, " \t\n");
  if (lineStartOffset > whiteSpace.getStartOffset()) {
    if (lineStartOffset >= text.length()) lineStartOffset = text.length() - 1;
    final int wsStart = whiteSpace.getStartOffset();
    int prevEnd;

    if (text.charAt(lineStartOffset) == '\n' && wsStart <= (prevEnd = documentModel.getLineStartOffset(documentModel.getLineNumber(lineStartOffset - 1))) &&
        documentModel.getText(new TextRange(prevEnd, lineStartOffset)).toString().trim().length() == 0 // ws consists of space only, it is not true for <![CDATA[
    ) {
      lineStartOffset--;
    }
    lineStartOffset = CharArrayUtil.shiftBackward(text, lineStartOffset, "\t ");
    if (lineStartOffset < 0) lineStartOffset = 0;
    if (lineStartOffset != offset && text.charAt(lineStartOffset) == '\n') {
      lineStartOffset++;
    }
  }
  return lineStartOffset;
}
 
Example #12
Source File: OclCommenter.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
@NotNull
private TextRange expandRange(@NotNull CharSequence chars, int delOffset1, int delOffset2) {
    int offset1 = CharArrayUtil.shiftBackward(chars, delOffset1 - 1, " \t");
    if (offset1 < 0 || chars.charAt(offset1) == '\n' || chars.charAt(offset1) == '\r') {
        int offset2 = CharArrayUtil.shiftForward(chars, delOffset2, " \t");
        if (offset2 == chars.length() || chars.charAt(offset2) == '\r' || chars.charAt(offset2) == '\n') {
            delOffset1 = (offset1 < 0) ? offset1 + 1 : offset1;
            if (offset2 < chars.length()) {
                delOffset2 = offset2 + 1;
                if (chars.charAt(offset2) == '\r' && offset2 + 1 < chars.length() && chars.charAt(offset2 + 1) == '\n') {
                    delOffset2++;
                }
            }
        }
    }
    return new TextRange(delOffset1, delOffset2);
}
 
Example #13
Source File: LeafElement.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean textContains(char c) {
  final CharSequence text = myText;
  final int len = text.length();

  if (len > TEXT_MATCHES_THRESHOLD) {
    char[] chars = CharArrayUtil.fromSequenceWithoutCopying(text);
    if (chars != null) {
      for (char aChar : chars) {
        if (aChar == c) return true;
      }
      return false;
    }
  }

  for (int i = 0; i < len; ++i) {
    if (c == text.charAt(i)) return true;
  }

  return false;
}
 
Example #14
Source File: ZipEntryMap.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static boolean isTheOne(@Nonnull ArchiveHandler.EntryInfo entry, @Nonnull CharSequence relativePath) {
  int endIndex = relativePath.length();
  for (ArchiveHandler.EntryInfo e = entry; e != null; e = e.parent) {
    CharSequence shortName = e.shortName;
    if (!CharArrayUtil.regionMatches(relativePath, endIndex - shortName.length(), relativePath.length(), shortName)) {
      return false;
    }

    endIndex -= shortName.length();
    if (e.parent != null && e.parent.shortName.length() != 0 && endIndex != 0) {
      // match "/"
      if (relativePath.charAt(endIndex-1) == '/') {
        endIndex -= 1;
      }
      else {
        return false;
      }
    }

  }
  return endIndex==0;
}
 
Example #15
Source File: PsiFileBreadcrumbsCollector.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Finds first breadcrumb-rendering element, possibly shifting offset backwards, skipping whitespaces and grabbing previous element
 * This logic solves inconsistency with brace matcher. For example,
 * <pre><code>
 *   class Foo {
 *     public void bar() {
 *
 *     } &lt;caret&gt;
 *   }
 * </code></pre>
 * will highlight bar's braces, looking backwards. So it should include it to breadcrumbs, too.
 */
@Nullable
private static PsiElement findStartElement(Document document, int offset, VirtualFile file, Project project, BreadcrumbsProvider defaultInfoProvider, boolean checkSettings) {
  PsiElement middleElement = findFirstBreadcrumbedElement(offset, file, project, defaultInfoProvider, checkSettings);

  // Let's simulate brace matcher logic of searching brace backwards (see `BraceHighlightingHandler.updateBraces`)
  CharSequence chars = document.getCharsSequence();
  int leftOffset = CharArrayUtil.shiftBackward(chars, offset - 1, "\t ");
  leftOffset = leftOffset >= 0 ? leftOffset : offset - 1;

  PsiElement leftElement = findFirstBreadcrumbedElement(leftOffset, file, project, defaultInfoProvider, checkSettings);
  if (leftElement != null && (middleElement == null || PsiTreeUtil.isAncestor(middleElement, leftElement, true))) {
    return leftElement;
  }
  else {
    return middleElement;
  }
}
 
Example #16
Source File: IndentRangesCalculator.java    From consulo with Apache License 2.0 6 votes vote down vote up
public List<TextRange> calcIndentRanges() {
  int startLine = document.getLineNumber(startOffset);
  int endLine = document.getLineNumber(endOffset);
  CharSequence chars = document.getCharsSequence();

  List<TextRange> indentRanges = new ArrayList<>();

  for (int line = startLine; line <= endLine; line++) {
    int lineStartOffset = document.getLineStartOffset(line);
    int lineEndOffset = document.getLineEndOffset(line);
    int firstNonWsChar = CharArrayUtil.shiftForward(chars, lineStartOffset, lineEndOffset + 1, " \t");
    indentRanges.add(new TextRange(lineStartOffset, firstNonWsChar));
  }

  return indentRanges;
}
 
Example #17
Source File: ArrangementEntryWrapper.java    From consulo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("AssignmentToForLoopParameter")
public void updateBlankLines(@Nonnull Document document) {
  int startLine = document.getLineNumber(getStartOffset());
  myBlankLinesBefore = 0;
  if (startLine <= 0) {
    return;
  }
  
  CharSequence text = document.getCharsSequence();
  int lastLineFeed = document.getLineStartOffset(startLine) - 1;
  for (int i = lastLineFeed - 1; i >= 0; i--) {
    i = CharArrayUtil.shiftBackward(text, i, " \t");
    if (text.charAt(i) == '\n') {
      ++myBlankLinesBefore;
    }
    else {
      break;
    }
  }
}
 
Example #18
Source File: CodeStyleManagerRunnable.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static TextRange getSignificantRange(final PsiFile file, final int offset) {
  final ASTNode elementAtOffset = SourceTreeToPsiMap.psiElementToTree(CodeStyleManagerImpl.findElementInTreeWithFormatterEnabled(file, offset));
  if (elementAtOffset == null) {
    int significantRangeStart = CharArrayUtil.shiftBackward(file.getText(), offset - 1, "\n\r\t ");
    return new TextRange(Math.max(significantRangeStart, 0), offset);
  }

  final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(file);
  if (builder != null) {
    final TextRange textRange = builder.getRangeAffectingIndent(file, offset, elementAtOffset);
    if (textRange != null) {
      return textRange;
    }
  }

  final TextRange elementRange = elementAtOffset.getTextRange();
  if (isWhiteSpace(elementAtOffset)) {
    return extendRangeAtStartOffset(file, elementRange);
  }

  return elementRange;
}
 
Example #19
Source File: SyntaxInfoBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void iterate(MyMarkupIterator iterator, int endOffset) {
  while (!iterator.atEnd()) {
    iterator.advance();
    int startOffset = iterator.getStartOffset();
    if (startOffset >= endOffset) {
      break;
    }
    if (myStartOffset < 0) {
      myStartOffset = startOffset;
    }

    boolean whiteSpacesOnly = CharArrayUtil.isEmptyOrSpaces(myText, startOffset, iterator.getEndOffset());

    processBackground(startOffset, iterator.getBackgroundColor());
    if (!whiteSpacesOnly) {
      processForeground(startOffset, iterator.getForegroundColor());
      processFontFamilyName(startOffset, iterator.getFontFamilyName());
      processFontStyle(startOffset, iterator.getFontStyle());
    }
  }
  addTextIfPossible(endOffset);
}
 
Example #20
Source File: LeafElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
public int copyTo(@Nullable char[] buffer, int start) {
  final int length = myText.length();
  if (buffer != null) {
    CharArrayUtil.getChars(myText, buffer, start, length);
  }
  return start + length;
}
 
Example #21
Source File: LineLayout.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static List<BidiRun> createFragments(@Nonnull EditorView view, @Nonnull CharSequence text, @JdkConstants.FontStyle int fontStyle) {
  if (text.length() == 0) return Collections.emptyList();

  FontFallbackIterator ffi = new FontFallbackIterator().setPreferredFonts(view.getEditor().getColorsScheme().getFontPreferences()).setFontStyle(fontStyle).setFontRenderContext(view.getFontRenderContext());

  char[] chars = CharArrayUtil.fromSequence(text);
  List<BidiRun> runs = createRuns(view, chars, -1);
  for (BidiRun run : runs) {
    for (Chunk chunk : run.getChunks(text, 0)) {
      chunk.fragments = new ArrayList<>();
      addFragments(run, chunk, chars, chunk.startOffset, chunk.endOffset, null, ffi);
    }
  }
  return runs;
}
 
Example #22
Source File: LazyParseableElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
public int copyTo(@Nullable char[] buffer, int start) {
  CharSequence text = myText();
  if (text == null) return -1;

  if (buffer != null) {
    CharArrayUtil.getChars(text, buffer, start);
  }
  return start + text.length();
}
 
Example #23
Source File: JsonInsertValueHandler.java    From intellij-swagger with MIT License 5 votes vote down vote up
private void handleEndingQuote(final InsertionContext insertionContext) {
  final int caretOffset = insertionContext.getEditor().getCaretModel().getOffset();
  final CharSequence chars = insertionContext.getDocument().getCharsSequence();

  final boolean hasEndingQuote = CharArrayUtil.regionMatches(chars, caretOffset, "\"");
  if (!hasEndingQuote) {
    insertionContext.getDocument().insertString(caretOffset, "\"");
    EditorModificationUtil.moveCaretRelatively(insertionContext.getEditor(), 1);
  }
}
 
Example #24
Source File: WidgetIndentsHighlightingPass.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
boolean updateSelected(@NotNull Editor editor, @NotNull RangeHighlighter highlighter, Caret carat) {
  if (carat == null) {
    return setSelection(false);
  }
  final CaretModel caretModel = editor.getCaretModel();
  final int startOffset = highlighter.getStartOffset();
  final Document doc = highlighter.getDocument();
  final int caretOffset = carat.getOffset();

  if (startOffset < 0 || startOffset >= doc.getTextLength()) {
    return setSelection(false);
  }

  final int endOffset = highlighter.getEndOffset();

  int off;
  int startLine = doc.getLineNumber(startOffset);
  {
    final CharSequence chars = doc.getCharsSequence();
    do {
      final int start = doc.getLineStartOffset(startLine);
      final 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);
  final int indentColumn = startPosition.column;

  final LogicalPosition logicalPosition = caretModel.getLogicalPosition();
  if (logicalPosition.line == startLine + 1 && descriptor.widget != null) {
    // Be more permissive about what constitutes selection for the first
    // line within a widget constructor.
    return setSelection(caretModel.getLogicalPosition().column >= indentColumn);
  }
  return setSelection(
    caretOffset >= off && caretOffset < endOffset && caretModel.getLogicalPosition().column == indentColumn);
}
 
Example #25
Source File: SmartEnterProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
protected PsiElement getStatementAtCaret(Editor editor, PsiFile psiFile) {
  int caret = editor.getCaretModel().getOffset();

  final Document doc = editor.getDocument();
  CharSequence chars = doc.getCharsSequence();
  int offset = caret == 0 ? 0 : CharArrayUtil.shiftBackward(chars, caret - 1, " \t");
  if (doc.getLineNumber(offset) < doc.getLineNumber(caret)) {
    offset = CharArrayUtil.shiftForward(chars, caret, " \t");
  }

  return psiFile.findElementAt(offset);
}
 
Example #26
Source File: CommentByLineCommentHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static Language getLineEndLanguage(@Nonnull PsiFile file, @Nonnull Editor editor, int line) {
  Document document = editor.getDocument();
  int lineEndOffset = document.getLineEndOffset(line) - 1;
  lineEndOffset = Math.max(0, CharArrayUtil.shiftBackward(document.getCharsSequence(), lineEndOffset < 0 ? 0 : lineEndOffset, " \t"));
  return PsiUtilCore.getLanguageAtOffset(file, lineEndOffset);
}
 
Example #27
Source File: LeafElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public char[] textToCharArray() {
  final char[] buffer = new char[myText.length()];
  CharArrayUtil.getChars(myText, buffer, 0);
  return buffer;
}
 
Example #28
Source File: ExtendWordSelectionHandlerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static List<TextRange> expandToWholeLinesWithBlanks(CharSequence text, TextRange range) {
  List<TextRange> result = ContainerUtil.newArrayList();
  result.addAll(expandToWholeLine(text, range, true));

  TextRange last = result.isEmpty() ? range : result.get(result.size() - 1);
  int start = last.getStartOffset();
  int end = last.getEndOffset();
  while (true) {
    int blankLineEnd = CharArrayUtil.shiftForward(text, end, " \t");
    if (blankLineEnd >= text.length() || text.charAt(blankLineEnd) != '\n') {
      break;
    }
    end = blankLineEnd + 1;
  }
  if (end == last.getEndOffset()) {
    while (start > 0 && text.charAt(start - 1) == '\n') {
      int blankLineStart = CharArrayUtil.shiftBackward(text, start - 2, " \t");
      if (blankLineStart <= 0 || text.charAt(blankLineStart) != '\n') {
        break;
      }
      start = blankLineStart + 1;
    }
  }
  if (start != last.getStartOffset() || end != last.getEndOffset()) {
    result.add(new TextRange(start, end));
  }

  return result;
}
 
Example #29
Source File: FormatterImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static int adjustLineIndent(final int offset,
                                    final FormattingDocumentModel documentModel,
                                    final FormatProcessor processor,
                                    final CommonCodeStyleSettings.IndentOptions indentOptions,
                                    final FormattingModel model,
                                    final WhiteSpace whiteSpace,
                                    ASTNode nodeAfter) {
  boolean wsContainsCaret = whiteSpace.getStartOffset() <= offset && offset < whiteSpace.getEndOffset();

  int lineStartOffset = getLineStartOffset(offset, whiteSpace, documentModel);

  final IndentInfo indent = calcIndent(offset, documentModel, processor, whiteSpace);

  final String newWS = whiteSpace.generateWhiteSpace(indentOptions, lineStartOffset, indent).toString();
  if (!whiteSpace.equalsToString(newWS)) {
    try {
      if (model instanceof FormattingModelEx) {
        ((FormattingModelEx)model).replaceWhiteSpace(whiteSpace.getTextRange(), nodeAfter, newWS);
      }
      else {
        model.replaceWhiteSpace(whiteSpace.getTextRange(), newWS);
      }
    }
    finally {
      model.commitChanges();
    }
  }

  final int defaultOffset = offset - whiteSpace.getLength() + newWS.length();

  if (wsContainsCaret) {
    final int ws = whiteSpace.getStartOffset() + CharArrayUtil.shiftForward(newWS, Math.max(0, lineStartOffset - whiteSpace.getStartOffset()), " \t");
    return Math.max(defaultOffset, ws);
  }
  else {
    return defaultOffset;
  }
}
 
Example #30
Source File: PsiBuilderImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private PsiBuilderImpl(@Nullable Project project,
                       @Nullable PsiFile containingFile,
                       @Nonnull LanguageVersion languageVersion,
                       @Nonnull ParserDefinition parserDefinition,
                       @Nonnull Lexer lexer,
                       @Nullable CharTable charTable,
                       @Nonnull CharSequence text,
                       @Nullable ASTNode originalTree,
                       @Nullable CharSequence lastCommittedText,
                       @Nullable MyTreeStructure parentLightTree,
                       @Nullable Object parentCachingNode) {
  myProject = project;
  myFile = containingFile;
  myLanguageVersion = languageVersion;
  myText = text;
  myTextArray = CharArrayUtil.fromSequenceWithoutCopying(text);
  myLexer = lexer;

  myWhitespaces = parserDefinition.getWhitespaceTokens(languageVersion);
  myComments = parserDefinition.getCommentTokens(languageVersion);
  myCharTable = charTable;
  myOriginalTree = originalTree;
  myLastCommittedText = lastCommittedText;
  if ((originalTree == null) != (lastCommittedText == null)) {
    throw new IllegalArgumentException("originalTree and lastCommittedText must be null/notnull together but got: originalTree=" +
                                       originalTree +
                                       "; lastCommittedText=" +
                                       (lastCommittedText == null ? null : "'" + StringUtil.first(lastCommittedText, 80, true) + "'"));
  }
  myParentLightTree = parentLightTree;
  myOffset = parentCachingNode instanceof LazyParseableToken ? ((LazyParseableToken)parentCachingNode).getStartOffset() : 0;

  cacheLexemes(parentCachingNode);
}