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

The following examples show how to use com.intellij.openapi.editor.Document#replaceString() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public 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 2
Source Project: BashSupport   File: BashShebangImpl.java    License: Apache License 2.0 6 votes vote down vote up
public void updateCommand(String command, @Nullable TextRange replacementRange) {
    log.debug("Updating command to " + command);

    PsiFile file = getContainingFile();
    if (file == null) {
        return;
    }

    Document document = file.getViewProvider().getDocument();
    if (document != null) {
        TextRange textRange = replacementRange != null ? replacementRange : commandRange();
        document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), command);
    } else {
        //fallback
        PsiElement newElement = BashPsiElementFactory.createShebang(getProject(), command, hasNewline());
        getNode().replaceChild(getNode().getFirstChildNode(), newElement.getNode());
    }
}
 
Example 3
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
    BashVarDef varDef = (BashVarDef) startElement;

    PsiElement context = varDef.getContext();
    if (context != null) {
        //a definition without value, e.g. "local a" has to be relaced with a= , otherwise it's not a valid var def

        if (!varDef.hasAssignmentValue()) {
            Document document = PsiDocumentManager.getInstance(project).getDocument(varDef.getContainingFile());
            if (document != null) {
                int endOffset = context.getTextOffset() + context.getTextLength();
                document.replaceString(context.getTextOffset(), endOffset, varDef.getName() + "=");

                PsiDocumentManager.getInstance(project).commitDocument(document);
            }
        } else {
            BashPsiUtils.replaceElement(context, varDef);
        }
    }
}
 
Example 4
Source Project: idea-latex   File: WrapEditorAction.java    License: MIT License 6 votes vote down vote up
/**
 * Wraps selection.
 *
 * @param editor Current editor.
 */
private void wrap(@NotNull TextEditor editor) {
    final Document document = editor.getEditor().getDocument();
    final SelectionModel selectionModel = editor.getEditor().getSelectionModel();
    final CaretModel caretModel = editor.getEditor().getCaretModel();

    final int start = selectionModel.getSelectionStart();
    final int end = selectionModel.getSelectionEnd();
    final String text = StringUtil.notNullize(selectionModel.getSelectedText());

    String newText = getLeftText() + text + getRightText();
    int newStart = start + getLeftText().length();
    int newEnd = StringUtil.isEmpty(text) ? newStart : end + getLeftText().length();

    document.replaceString(start, end, newText);
    selectionModel.setSelection(newStart, newEnd);
    caretModel.moveToOffset(newEnd);
}
 
Example 5
Source Project: idea-latex   File: WrapEditorAction.java    License: MIT License 6 votes vote down vote up
/**
 * Unwraps selection.
 *
 * @param editor  Current editor.
 * @param matched Matched PSI element.
 */
private void unwrap(@NotNull final TextEditor editor, @NotNull final PsiElement matched) {
    final Document document = editor.getEditor().getDocument();
    final SelectionModel selectionModel = editor.getEditor().getSelectionModel();
    final CaretModel caretModel = editor.getEditor().getCaretModel();

    final int start = matched.getTextRange().getStartOffset();
    final int end = matched.getTextRange().getEndOffset();
    final String text = StringUtil.notNullize(matched.getText());

    String newText = StringUtil.trimEnd(StringUtil.trimStart(text, getLeftText()), getRightText());
    int newStart = selectionModel.getSelectionStart() - getLeftText().length();
    int newEnd = selectionModel.getSelectionEnd() - getLeftText().length();

    document.replaceString(start, end, newText);

    selectionModel.setSelection(newStart, newEnd);
    caretModel.moveToOffset(newEnd);
}
 
Example 6
Source Project: consulo   File: Change.java    License: 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 7
static OffsetsInFile insertDummyIdentifier(CompletionInitializationContext initContext, CompletionProgressIndicator indicator) {
  OffsetsInFile topLevelOffsets = indicator.getHostOffsets();
  CompletionAssertions.checkEditorValid(initContext.getEditor());
  if (initContext.getDummyIdentifier().isEmpty()) {
    return topLevelOffsets;
  }

  Editor hostEditor = InjectedLanguageUtil.getTopLevelEditor(initContext.getEditor());
  OffsetMap hostMap = topLevelOffsets.getOffsets();

  PsiFile hostCopy = obtainFileCopy(topLevelOffsets.getFile());
  Document copyDocument = Objects.requireNonNull(hostCopy.getViewProvider().getDocument());

  String dummyIdentifier = initContext.getDummyIdentifier();
  int startOffset = hostMap.getOffset(CompletionInitializationContext.START_OFFSET);
  int endOffset = hostMap.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET);

  indicator.registerChildDisposable(() -> new OffsetTranslator(hostEditor.getDocument(), initContext.getFile(), copyDocument, startOffset, endOffset, dummyIdentifier));

  copyDocument.setText(hostEditor.getDocument().getText());

  OffsetMap copyOffsets = topLevelOffsets.getOffsets().copyOffsets(copyDocument);
  indicator.registerChildDisposable(() -> copyOffsets);

  copyDocument.replaceString(startOffset, endOffset, dummyIdentifier);
  return new OffsetsInFile(hostCopy, copyOffsets);
}
 
Example 8
Source Project: BashSupport   File: BackquoteQuickfix.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
    Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    if (document != null) {
        BashBackquote backquote = (BashBackquote) startElement;
        int endOffset = startElement.getTextRange().getEndOffset();
        String command = backquote.getCommandText();

        //fixme replace this with a PSI element created by the Bash psi factory
        document.replaceString(startElement.getTextOffset(), endOffset, "$(" + command + ")");

        PsiDocumentManager.getInstance(project).commitDocument(document);
    }
}
 
Example 9
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
    Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    if (document != null) {
        int endOffset = startElement.getTextOffset() + startElement.getTextLength();

        String replacement = wrapText(startElement.getText());

        document.replaceString(startElement.getTextOffset(), endOffset, replacement);

        PsiDocumentManager.getInstance(project).commitDocument(document);
    }
}
 
Example 10
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
    TextRange r = startElement.getTextRange();
    String replacement = String.valueOf(numericValue);

    Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    if (document != null) {
        document.replaceString(r.getStartOffset(), r.getEndOffset(), replacement);
        PsiDocumentManager.getInstance(project).commitDocument(document);
    }
}
 
Example 11
Source Project: consulo   File: DummyIdentifierPatcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void patchFileCopy(@Nonnull final PsiFile fileCopy, @Nonnull final Document document, @Nonnull final OffsetMap map) {
  if (StringUtil.isEmpty(myDummyIdentifier)) return;
  int startOffset = map.getOffset(CompletionInitializationContext.START_OFFSET);
  int endOffset = map.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET);
  document.replaceString(startOffset, endOffset, myDummyIdentifier);
}
 
Example 12
Source Project: eslint-plugin   File: EqeqeqActionFix.java    License: MIT License 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile psiFile, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement element, @NotNull PsiElement end) throws IncorrectOperationException {
    ASTNode op = JSBinaryExpressionUtil.getOperator(element);
    Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());

    String replace = "";
    if (op.getText().equals("==")) {
        replace = "===";
    } else if (op.getText().equals("!=")) {
        replace = "!==";
    }
    document.replaceString(op.getStartOffset(), op.getStartOffset() + op.getTextLength(), replace);
}
 
Example 13
Source Project: consulo   File: PlainFileManipulator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public PsiPlainTextFile handleContentChange(@Nonnull PsiPlainTextFile file, @Nonnull TextRange range, String newContent)
        throws IncorrectOperationException {
  final Document document = FileDocumentManager.getInstance().getDocument(file.getVirtualFile());
  document.replaceString(range.getStartOffset(), range.getEndOffset(), newContent);
  PsiDocumentManager.getInstance(file.getProject()).commitDocument(document);

  return file;
}
 
Example 14
@Override
protected boolean doCharDeleted(char c, PsiFile file, Editor editor) {
  if (myReplacement == null) {
    return false;
  }

  Document document = editor.getDocument();
  CaretModel caretModel = editor.getCaretModel();
  int endOffset = CharArrayUtil.shiftForward(document.getImmutableCharSequence(), caretModel.getOffset(), " \t");

  document.replaceString(myStartOffset, endOffset, myReplacement);
  caretModel.moveToOffset(myStartOffset + myReplacement.length());

  return true;
}
 
Example 15
private void extractExpectedLineMarkerSet(Document document) {
  String text = document.getText();

  @NonNls String pat = ".*?((<" + LINE_MARKER + ")(?: descr=\"((?:[^\"\\\\]|\\\\\")*)\")?>)(.*)";
  final Pattern p = Pattern.compile(pat, Pattern.DOTALL);
  final Pattern pat2 = Pattern.compile("(.*?)(</" + LINE_MARKER + ">)(.*)", Pattern.DOTALL);

  while (true) {
    Matcher m = p.matcher(text);
    if (!m.matches()) break;
    int startOffset = m.start(1);
    final String descr = m.group(3) != null ? m.group(3) : ANY_TEXT;
    String rest = m.group(4);

    document.replaceString(startOffset, m.end(1), "");

    final Matcher matcher2 = pat2.matcher(rest);
    LOG.assertTrue(matcher2.matches(), "Cannot find closing </" + LINE_MARKER + ">");
    String content = matcher2.group(1);
    int endOffset = startOffset + matcher2.start(3);
    String endTag = matcher2.group(2);

    document.replaceString(startOffset, endOffset, content);
    endOffset -= endTag.length();

    LineMarkerInfo markerInfo = new LineMarkerInfo<PsiElement>(myFile, new TextRange(startOffset, endOffset), null, Pass.LINE_MARKERS,
                                                               new ConstantFunction<PsiElement, String>(descr), null,
                                                               GutterIconRenderer.Alignment.RIGHT);

    lineMarkerInfos.put(document.createRangeMarker(startOffset, endOffset), markerInfo);
    text = document.getText();
  }
}
 
Example 16
Source Project: consulo   File: SelectionReverter.java    License: Apache License 2.0 5 votes vote down vote up
protected void doRevert() throws IOException, FilesTooBigForDiffException {
  Block b = myCalculator.getSelectionFor(myLeftRevision, new Progress() {
    public void processed(int percentage) {
      // should be already processed.
    }
  });

  Document d = myGateway.getDocument(myRightEntry.getPath());

  int from = d.getLineStartOffset(myFromLine);
  int to = d.getLineEndOffset(myToLine);

  d.replaceString(from, to, b.getBlockContent());
}
 
Example 17
private static void adjustIndentationInRange(@Nonnull PsiFile file, @Nonnull Document document, @Nonnull TextRange[] indents, final int indentAdjustment) {
  final CharSequence charsSequence = document.getCharsSequence();
  for (final TextRange indent : indents) {
    final String oldIndentStr = charsSequence.subSequence(indent.getStartOffset() + 1, indent.getEndOffset()).toString();
    final int oldIndent = IndentHelperImpl.getIndent(file, oldIndentStr, true);
    final String newIndentStr = IndentHelperImpl.fillIndent(CodeStyle.getIndentOptions(file), Math.max(oldIndent + indentAdjustment, 0));
    document.replaceString(indent.getStartOffset() + 1, indent.getEndOffset(), newIndentStr);
  }
}
 
Example 18
private void doReplace(Document document, String textToInsert) {
    document.replaceString(matchResultReplace.start(), matchResultReplace.end(), textToInsert);
}
 
Example 19
Source Project: intellij-haxe   File: UsefulPsiTreeUtil.java    License: Apache License 2.0 4 votes vote down vote up
static public void replaceElementWithText(PsiElement element, String text) {
  Document document = PsiDocumentManager.getInstance(element.getProject()).getDocument(element.getContainingFile());
  TextRange range = element.getTextRange();
  document.replaceString(range.getStartOffset(), range.getEndOffset(), text);
}
 
Example 20
/**
 * @param   event    ActionSystem event
 */
void write(final AnActionEvent event) {
    Editor editor = event.getData(PlatformDataKeys.EDITOR);

    if (editor != null) {
        final Document document = editor.getDocument();

        CaretModel caretModel = editor.getCaretModel();

        for (Caret caret : caretModel.getAllCarets()) {
            boolean hasSelection = caret.hasSelection();
            String selectedText  = caret.getSelectedText();

            String trailingCharacter    = TextualHelper.getTrailingPunctuationMark(selectedText);
            String leadingCharacters    = TextualHelper.getLeadingPreservation(selectedText);

            int amountLines     = 1;
            // applies only when replacing a single-lined selection, can be rounded up
            Integer amountWords = null;

            // Generated dummy text will replace the current selected text
            if (hasSelection && selectedText != null ) {
                int selectionLength = selectedText.length();
                if (selectionLength > 0) {
                    amountLines = TextualHelper.countLines(selectedText);
                    if (amountLines == 1) {
                        amountWords = TextualHelper.getWordCount(selectedText);
                    }
                }
            }

            // Generate and insert / replace selection with dummy text
            String dummyText  = generateText(amountLines, amountWords, leadingCharacters, trailingCharacter, selectedText).toString();

            Integer dummyTextLength = dummyText.length();
            Integer offsetStart;

            if (hasSelection) {
                // Move caret to end of selection
                offsetStart = caret.getSelectionStart();
                int offsetEnd = caret.getSelectionEnd();

                document.replaceString(offsetStart, offsetEnd, dummyText);
                caret.setSelection(offsetStart, offsetStart + dummyTextLength);
            } else {
                // Move caret to end of inserted text
                offsetStart  = caretModel.getOffset();
                dummyText   = dummyText.trim();
                document.insertString(offsetStart, dummyText);
            }
        }

    }
}