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

The following examples show how to use com.intellij.openapi.editor.Document#deleteString() . 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: EventLog.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void removeJavaNewLines(Document document, List<RangeMarker> lineSeparators, String indent, boolean hasHtml) {
  CharSequence text = document.getCharsSequence();
  int i = 0;
  while (true) {
    i = StringUtil.indexOf(text, '\n', i);
    if (i < 0) break;
    int j = i + 1;
    if (StringUtil.startsWith(text, j, indent)) {
      j += indent.length();
    }
    document.deleteString(i, j);
    if (!hasHtml) {
      lineSeparators.add(document.createRangeMarker(TextRange.from(i, 0)));
    }
  }
}
 
Example 2
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 3
Source File: Change.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Applies the text from the original marker to the target marker.
 * @return the resulting TextRange from the target document, or null if the document if not writable.
 */
@Nullable
private static TextRange modifyDocument(@Nonnull Project project, @Nonnull RangeMarker original, @Nonnull RangeMarker target) {
  Document document = target.getDocument();
  if (!ReadonlyStatusHandler.ensureDocumentWritable(project, document)) { return null; }
  if (DocumentUtil.isEmpty(original)) {
    int offset = target.getStartOffset();
    document.deleteString(offset, target.getEndOffset());
  }
  String text = DocumentUtil.getText(original);
  int startOffset = target.getStartOffset();
  if (DocumentUtil.isEmpty(target)) {
    document.insertString(startOffset, text);
  } else {
    document.replaceString(startOffset, target.getEndOffset(), text);
  }
  return new TextRange(startOffset, startOffset + text.length());
}
 
Example 4
Source File: LSPIJUtils.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
public static void applyEdit(Editor editor, TextEdit textEdit, Document document) {
    RangeMarker marker = document.createRangeMarker(LSPIJUtils.toOffset(textEdit.getRange().getStart(), document), LSPIJUtils.toOffset(textEdit.getRange().getEnd(), document));
    int startOffset = marker.getStartOffset();
    int endOffset = marker.getEndOffset();
    String text = textEdit.getNewText();
    if (text != null) {
        text = text.replaceAll("\r", "");
    }
    if (text == null || "".equals(text)) {
        document.deleteString(startOffset, endOffset);
    } else if (endOffset - startOffset <= 0) {
        document.insertString(startOffset, text);
    } else {
        document.replaceString(startOffset, endOffset, text);
    }
    if (text != null && !"".equals(text)) {
        editor.getCaretModel().moveCaretRelatively(text.length(), 0, false, false, true);
    }
    marker.dispose();
}
 
Example 5
Source File: BuildLookupElement.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * If we're wrapping with quotes, handle the (very common) case where we have a closing quote
 * after the caret -- we want to remove this quote.
 */
@Override
public void handleInsert(InsertionContext context) {
  if (!wrapWithQuotes || !insertClosingQuotes()) {
    super.handleInsert(context);
    return;
  }
  Document document = context.getDocument();
  context.commitDocument();
  PsiElement suffix = context.getFile().findElementAt(context.getTailOffset());
  if (suffix != null && suffix.getText().startsWith(quoteWrapping.quoteString)) {
    int offset = suffix.getTextOffset();
    document.deleteString(offset, offset + 1);
    context.commitDocument();
  }
  if (caretInsideQuotes()) {
    context.getEditor().getCaretModel().moveCaretRelatively(-1, 0, false, false, true);
  }
}
 
Example 6
Source File: BuildEnterHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static void removeTrailingWhitespace(Document doc, PsiFile file, int offset) {
  CharSequence chars = doc.getCharsSequence();
  int start = offset;
  while (offset < chars.length() && chars.charAt(offset) == ' ') {
    PsiElement element = file.findElementAt(offset);
    if (element == null || !(element instanceof PsiWhiteSpace)) {
      break;
    }
    offset++;
  }
  if (start != offset) {
    doc.deleteString(start, offset);
  }
}
 
Example 7
Source File: DeleteToWordEndAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void deleteToWordEnd(Editor editor, boolean camelMode) {
  int startOffset = editor.getCaretModel().getOffset();
  int endOffset = getWordEndOffset(editor, startOffset, camelMode);
  if(endOffset > startOffset) {
    Document document = editor.getDocument();
    document.deleteString(startOffset, endOffset);
  }
}
 
Example 8
Source File: MergeOperations.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static Runnable removeModification(final TextRange range, final Document document) {
  return new Runnable(){
    public void run() {
      document.deleteString(range.getStartOffset(), range.getEndOffset());
    }
  };
}
 
Example 9
Source File: ConsoleLog.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
private static void removeJavaNewLines(Document document, List<RangeMarker> lineSeparators, boolean hasHtml) {
    CharSequence text = document.getCharsSequence();
    int i = 0;
    while(true) {
        i = StringUtil.indexOf(text, '\n', i);
        if(i < 0) {
            break;
        }
        document.deleteString(i, i + 1);
        if(!hasHtml) {
            lineSeparators.add(document.createRangeMarker(TextRange.from(i, 0)));
        }
    }
}
 
Example 10
Source File: ApiCommenter.java    From ApiDebugger with Apache License 2.0 5 votes vote down vote up
@Override
public void uncommentBlockComment(final int startOffset, final int endOffset, final Document document, final CommenterDataHolder data) {
    if (CharArrayUtil.regionMatches(document.getCharsSequence(), startOffset, BLOCK_COMMENT_PREFIX) && CharArrayUtil.regionMatches(document.getCharsSequence(), endOffset - BLOCK_COMMENT_SUFFIX.length(), BLOCK_COMMENT_SUFFIX)) {
        document.deleteString(startOffset, BLOCK_COMMENT_PREFIX.length());
        document.deleteString(endOffset - BLOCK_COMMENT_SUFFIX.length(), endOffset);
    }
}
 
Example 11
Source File: ApiCommenter.java    From ApiDebugger with Apache License 2.0 5 votes vote down vote up
@Override
public void uncommentLine(final int line, final int offset, @NotNull final Document document, @NotNull final CommenterDataHolder data) {
    if (document == null) {
        $$$reportNull$$$0(6);
    }
    if (data == null) {
        $$$reportNull$$$0(7);
    }
    if (CharArrayUtil.regionMatches(document.getCharsSequence(), offset, LINE_COMMENT_PREFIX)) {
        document.deleteString(offset, offset + LINE_COMMENT_PREFIX.length());
    }
}
 
Example 12
Source File: RemoveUnusedAtFixBase.java    From bamboo-soy with Apache License 2.0 5 votes vote down vote up
static void deleteElement(PsiElement element, Document document) {
  ASTNode atParamNode = element.getNode();
  PsiElement nextMeaningfulNode = PsiTreeUtil
      .skipSiblingsForward(element, PsiWhiteSpace.class);
  nextMeaningfulNode = nextMeaningfulNode == null ? null
      : WhitespaceUtils.getFirstNonWhitespaceChild(nextMeaningfulNode);
  TextRange rangeToDelete = computeRangeToDelete(element, atParamNode, nextMeaningfulNode);
  document.deleteString(rangeToDelete.getStartOffset(), rangeToDelete.getEndOffset());
}
 
Example 13
Source File: BuildEnterHandler.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Override
public Result preprocessEnter(
    PsiFile file,
    Editor editor,
    Ref<Integer> caretOffset,
    Ref<Integer> caretAdvance,
    DataContext dataContext,
    EditorActionHandler originalHandler) {
  int offset = caretOffset.get();
  if (editor instanceof EditorWindow) {
    file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
    editor = InjectedLanguageUtil.getTopLevelEditor(editor);
    offset = editor.getCaretModel().getOffset();
  }
  if (!isApplicable(file, dataContext)) {
    return Result.Continue;
  }

  // Previous enter handler's (e.g. EnterBetweenBracesHandler) can introduce a mismatch
  // between the editor's caret model and the offset we've been provided with.
  editor.getCaretModel().moveToOffset(offset);

  Document doc = editor.getDocument();
  PsiDocumentManager.getInstance(file.getProject()).commitDocument(doc);

  // #api173: get file, language specific settings instead
  CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(file.getProject());
  Integer indent = determineIndent(file, editor, offset, settings);
  if (indent == null) {
    return Result.Continue;
  }

  removeTrailingWhitespace(doc, file, offset);
  originalHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), dataContext);
  LogicalPosition position = editor.getCaretModel().getLogicalPosition();
  if (position.column == indent) {
    return Result.Stop;
  }
  if (position.column > indent) {
    // default enter handler has added too many spaces -- remove them
    int excess = position.column - indent;
    doc.deleteString(
        editor.getCaretModel().getOffset() - excess, editor.getCaretModel().getOffset());
  } else if (position.column < indent) {
    String spaces = StringUtil.repeatSymbol(' ', indent - position.column);
    doc.insertString(editor.getCaretModel().getOffset(), spaces);
  }
  editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(position.line, indent));
  return Result.Stop;
}
 
Example 14
Source File: HaxeImportOptimizer.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
private static void reorderImports(final PsiFile file) {
  HaxeFileModel fileModel = HaxeFileModel.fromElement(file);
  List<HaxeImportStatement> allImports = fileModel.getImportStatements();

  if (allImports.size() < 2) {
    return;
  }

  final HaxeImportStatement firstImport = allImports.get(0);
  int startOffset = firstImport.getStartOffsetInParent();
  final HaxeImportStatement lastImport = allImports.get(allImports.size() - 1);
  int endOffset = lastImport.getStartOffsetInParent() + lastImport.getText().length();

  // We assume the common practice of placing all imports in a single "block" at the top of a file. If there is something else (comments,
  // code, etc) there we just stop reordering to prevent data loss.
  for (PsiElement child : file.getChildren()) {
    int childOffset = child.getStartOffsetInParent();
    if (childOffset >= startOffset && childOffset <= endOffset
        && !(child instanceof HaxeImportStatement)
        && !(child instanceof PsiWhiteSpace)) {
      return;
    }
  }

  List<String> sortedImports = new ArrayList<>();

  for (HaxeImportStatement currentImport : allImports) {
    sortedImports.add(currentImport.getText());
  }

  sortedImports.sort(String::compareToIgnoreCase);

  final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(file.getProject());
  final Document document = psiDocumentManager.getDocument(file);
  if (document != null) {
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(file.getProject());

    /* This operation trims the document if necessary (e.g. it happens with "\n" at the very beginning).
       Need to reevaluate offsets here.
     */
    documentManager.doPostponedOperationsAndUnblockDocument(document);

    // Reevaluating offset values according to the previous comment.
    startOffset = firstImport.getStartOffsetInParent();
    endOffset = lastImport.getStartOffsetInParent() + lastImport.getText().length();

    document.deleteString(startOffset, endOffset);

    StringBuilder sortedImportsText = new StringBuilder();
    for (String sortedImport : sortedImports) {
      sortedImportsText.append(sortedImport);
      sortedImportsText.append("\n");
    }
    // Removes last "\n".
    CharSequence sortedImportsTextTrimmed = sortedImportsText.subSequence(0, sortedImportsText.length() - 1);

    documentManager.doPostponedOperationsAndUnblockDocument(document);
    document.insertString(startOffset, sortedImportsTextTrimmed);
  }

  // TODO Reorder usings.
}
 
Example 15
Source File: InsertHandlerUtils.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
private static void removeNamespaceAndColon(InsertionContext context, Document document, PsiElement elementBeforeColon) {
    if (elementBeforeColon != null) {
        TextRange textRange = elementBeforeColon.getTextRange();
        document.deleteString(textRange.getStartOffset(), context.getStartOffset());
    }
}
 
Example 16
Source File: NewExpressionTemplate.java    From HakunaMatataIntelliJPlugin with Apache License 2.0 4 votes vote down vote up
private void removeExpressionFromEditor(@NotNull PsiElement expression, @NotNull Editor editor) {
    Document document = editor.getDocument();
    document.deleteString(expression.getTextRange().getStartOffset(), expression.getTextRange().getEndOffset());
}
 
Example 17
Source File: DotEnvCommenter.java    From idea-php-dotenv-plugin with MIT License 4 votes vote down vote up
@Override
public void uncommentLine(int line, int offset, @NotNull Document document, @NotNull CommenterDataHolder data) {
    document.deleteString(offset, offset + 1);
}
 
Example 18
Source File: DeleteToWordStartAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void deleteToWordStart(Editor editor) {
  boolean camel = editor.getSettings().isCamelWords();
  if (myNegateCamelMode) {
    camel = !camel;
  }
  CharSequence text = editor.getDocument().getCharsSequence();
  CaretModel caretModel = editor.getCaretModel();
  int endOffset = caretModel.getOffset();
  int minOffset = editor.getDocument().getLineStartOffset(caretModel.getLogicalPosition().line);

  myQuotesNumber.clear();
  for (int i : QUOTE_SYMBOLS_ARRAY) {
    myQuotesNumber.put(i, 0);
  }
  countQuotes(myQuotesNumber, text, minOffset, endOffset);

  EditorActionUtil.moveCaretToPreviousWord(editor, false, camel);

  for (int offset = caretModel.getOffset(); offset > minOffset; offset = caretModel.getOffset()) {
    char previous = text.charAt(offset - 1);
    char current = text.charAt(offset);
    if (QUOTE_SYMBOLS.contains(current)) {
      if (Character.isWhitespace(previous)) {
        break;
      }
      else if (offset < endOffset - 1 && !Character.isJavaIdentifierPart(text.charAt(offset + 1))) {
        // Handle a situation like ' "one", "two", [caret] '. We want to delete up to the previous literal end here.
        editor.getCaretModel().moveToOffset(offset + 1);
        break;
      }
      if (myQuotesNumber.get(current) % 2 == 0) {
        // Was 'one "two" [caret]', now 'one "two[caret]"', we want to get 'one [caret]"two"'
        EditorActionUtil.moveCaretToPreviousWord(editor, false, camel);
        continue;
      }
      break;
    }

    if (QUOTE_SYMBOLS.contains(previous)) {
      if (myQuotesNumber.get(previous) % 2 == 0) {
        // Was 'one "two[caret]", now 'one "[caret]two"', we want 'one [caret]"two"'
        editor.getCaretModel().moveToOffset(offset - 1);
      }
    }
    break;
  }

  int startOffset = caretModel.getOffset();
  Document document = editor.getDocument();
  document.deleteString(startOffset, endOffset);
}
 
Example 19
Source File: YamlKeyInsertHandler.java    From intellij-spring-assistant with MIT License 4 votes vote down vote up
private void deleteLookupPlain(InsertionContext context) {
  Document document = context.getDocument();
  document.deleteString(context.getStartOffset(), context.getTailOffset());
  context.commitDocument();
}
 
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);
    }
  }
}