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

The following examples show how to use com.intellij.openapi.editor.Document#setText() . 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: CsvValidationInspection.java    From intellij-csv-validator with Apache License 2.0 6 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    try {
        PsiElement element = descriptor.getPsiElement();
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        List<Integer> quotePositions = new ArrayList<>();

        int quotePosition = CsvIntentionHelper.getOpeningQuotePosition(element);
        if (quotePosition != -1) {
            quotePositions.add(quotePosition);
        }
        PsiElement endSeparatorElement = CsvIntentionHelper.findQuotePositionsUntilSeparator(element, quotePositions, true);
        if (endSeparatorElement == null) {
            quotePositions.add(document.getTextLength());
        } else {
            quotePositions.add(endSeparatorElement.getTextOffset());
        }
        String text = CsvIntentionHelper.addQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 2
Source File: CsvIntentionHelper.java    From intellij-csv-validator with Apache License 2.0 6 votes vote down vote up
public static void unquoteAll(@NotNull Project project, @NotNull PsiFile psiFile) {
    try {
        Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
        List<Integer> quotePositions = new ArrayList<>();
        Collection<PsiElement> fields = getAllFields(psiFile);
        for (PsiElement field : fields) {
            if (getChildren(field).stream().anyMatch(element -> CsvHelper.getElementType(element) == CsvTypes.ESCAPED_TEXT)) {
                continue;
            }
            if (CsvHelper.getElementType(field.getFirstChild()) == CsvTypes.QUOTE) {
                quotePositions.add(field.getFirstChild().getTextOffset());
            }
            if (CsvHelper.getElementType(field.getLastChild()) == CsvTypes.QUOTE) {
                quotePositions.add(field.getLastChild().getTextOffset());
            }
        }
        String text = removeQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 3
Source File: CsvIntentionHelper.java    From intellij-csv-validator with Apache License 2.0 6 votes vote down vote up
public static void quoteValue(@NotNull Project project, @NotNull final PsiElement element) {
    try {
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        List<Integer> quotePositions = new ArrayList<>();

        int quotePosition = getOpeningQuotePosition(element.getFirstChild(), element.getLastChild());
        if (quotePosition != -1) {
            quotePositions.add(quotePosition);
        }
        PsiElement endSeparatorElement = findQuotePositionsUntilSeparator(element, quotePositions);
        if (endSeparatorElement == null) {
            quotePositions.add(document.getTextLength());
        } else {
            quotePositions.add(endSeparatorElement.getTextOffset());
        }
        String text = addQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 4
Source File: CsvIntentionHelper.java    From intellij-csv-validator with Apache License 2.0 6 votes vote down vote up
public static void unquoteValue(@NotNull Project project, @NotNull final PsiElement element) {
    try {
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        List<Integer> quotePositions = new ArrayList<>();

        if (CsvHelper.getElementType(element.getFirstChild()) == CsvTypes.QUOTE) {
            quotePositions.add(element.getFirstChild().getTextOffset());
        }
        if (CsvHelper.getElementType(element.getLastChild()) == CsvTypes.QUOTE) {
            quotePositions.add(element.getLastChild().getTextOffset());
        }
        String text = removeQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 5
Source File: FileContentUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void setFileText(@javax.annotation.Nullable Project project, final VirtualFile virtualFile, final String text) throws IOException {
  if (project == null) {
    project = ProjectUtil.guessProjectForFile(virtualFile);
  }
  if (project != null) {
    final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    final Document document = psiFile == null? null : psiDocumentManager.getDocument(psiFile);
    if (document != null) {
      document.setText(text != null ? text : "");
      psiDocumentManager.commitDocument(document);
      FileDocumentManager.getInstance().saveDocument(document);
      return;
    }
  }
  VfsUtil.saveText(virtualFile, text != null ? text : "");
  virtualFile.refresh(false, false);
}
 
Example 6
Source File: ApplyTextFilePatch.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void applyCreate(Project project, final VirtualFile newFile, CommitContext commitContext) throws IOException {
  final Document document = FileDocumentManager.getInstance().getDocument(newFile);
  if (document == null) {
    throw new IOException("Failed to set contents for new file " + newFile.getPath());
  }
  final String charsetName = CharsetEP.getCharset(newFile.getPath(), commitContext);
  if (charsetName != null) {
    try {
      final Charset charset = Charset.forName(charsetName);
      newFile.setCharset(charset);
    } catch (IllegalArgumentException e) {
      //
    }
  }
  document.setText(myPatch.getNewFileText());
  FileDocumentManager.getInstance().saveDocument(document);
}
 
Example 7
Source File: CreateFileFix.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void openFile(@Nonnull Project project, PsiDirectory directory, PsiFile newFile, String text) {
  final FileEditorManager editorManager = FileEditorManager.getInstance(directory.getProject());
  final FileEditor[] fileEditors = editorManager.openFile(newFile.getVirtualFile(), true);

  if (text != null) {
    for (FileEditor fileEditor : fileEditors) {
      if (fileEditor instanceof TextEditor) { // JSP is not safe to edit via Psi
        final Document document = ((TextEditor)fileEditor).getEditor().getDocument();
        document.setText(text);

        if (ApplicationManager.getApplication().isUnitTestMode()) {
          FileDocumentManager.getInstance().saveDocument(document);
        }
        PsiDocumentManager.getInstance(project).commitDocument(document);
        break;
      }
    }
  }
}
 
Example 8
Source File: CsvValidationInspection.java    From intellij-csv-validator with Apache License 2.0 5 votes vote down vote up
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    try {
        PsiElement element = descriptor.getPsiElement();
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        CsvValueSeparator separator = CsvHelper.getValueSeparator(element.getContainingFile());
        String text = document.getText();
        document.setText(text.substring(0, element.getTextOffset()) + separator.getCharacter() + text.substring(element.getTextOffset()));
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 9
Source File: CsvValidationInspection.java    From intellij-csv-validator with Apache License 2.0 5 votes vote down vote up
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    try {
        PsiElement element = descriptor.getPsiElement();
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        document.setText(document.getText() + "\"");
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 10
Source File: CsvIntentionHelper.java    From intellij-csv-validator with Apache License 2.0 5 votes vote down vote up
public static void quoteAll(@NotNull Project project, @NotNull PsiFile psiFile) {
    try {
        Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
        List<Integer> quotePositions = new ArrayList<>();
        Collection<PsiElement> fields = getAllFields(psiFile);
        PsiElement separator;
        for (PsiElement field : fields) {
            if (field.getFirstChild() == null || CsvHelper.getElementType(field.getFirstChild()) != CsvTypes.QUOTE) {
                separator = CsvHelper.getPreviousSeparator(field);
                if (separator == null) {
                    quotePositions.add(field.getParent().getTextOffset());
                } else {
                    quotePositions.add(separator.getTextOffset() + separator.getTextLength());
                }
            }
            if (field.getLastChild() == null || CsvHelper.getElementType(field.getLastChild()) != CsvTypes.QUOTE) {
                separator = CsvHelper.getNextSeparator(field);
                if (separator == null) {
                    quotePositions.add(field.getParent().getTextOffset() + field.getParent().getTextLength());
                } else {
                    quotePositions.add(separator.getTextOffset());
                }
            }
        }
        String text = addQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 11
Source File: CsvShiftColumnIntentionAction.java    From intellij-csv-validator with Apache License 2.0 5 votes vote down vote up
protected static void changeLeftAndRightColumnOrder(@NotNull Project project,
                                                    CsvFile csvFile,
                                                    CsvColumnInfo<PsiElement> leftColumnInfo,
                                                    CsvColumnInfo<PsiElement> rightColumnInfo) {
    Document document = PsiDocumentManager.getInstance(project).getDocument(csvFile);
    document.setText(
            changeLeftAndRightColumnOrder(document.getText(), CsvHelper.getValueSeparator(csvFile), leftColumnInfo, rightColumnInfo)
    );
}
 
Example 12
Source File: ParametersPanel.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 5 votes vote down vote up
private void setInitialContent(Document document) {
    if (document != null && document.getText().isEmpty()) {
        final Runnable setTextRunner = () -> document.setText("{}");
        ApplicationManager.getApplication()
                .invokeLater(() -> ApplicationManager.getApplication().runWriteAction(setTextRunner));
    }
}
 
Example 13
Source File: UndoHandler.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
private void performUndoableAction(List<String> filesChangedList) {
    for (String fileName : filesChangedList)
        try {
            VirtualFile virtualFile = getInstance().findFileByIoFile(new File(fileName));
            if (virtualFile != null) {
                Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
                getInstance().refreshAndFindFileByIoFile(new File(fileName));
                if (document != null)
                    document.setText(StringUtils.join(FileUtils.readLines(new File(fileName), EncodingManager.getInstance().getEncoding(virtualFile, true).toString()).toArray(), "\n"));
            }
        } catch (Exception ignored) {
            LOG.debug(ignored);
        }
}
 
Example 14
Source File: ApplyTextFilePatch.java    From consulo with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
protected Result applyChange(final Project project, final VirtualFile fileToPatch, final FilePath pathBeforeRename, final Getter<CharSequence> baseContents) throws IOException {
  byte[] fileContents = fileToPatch.contentsToByteArray();
  CharSequence text = LoadTextUtil.getTextByBinaryPresentation(fileContents, fileToPatch);
  final GenericPatchApplier applier = new GenericPatchApplier(text, myPatch.getHunks());
  if (applier.execute()) {
    final Document document = FileDocumentManager.getInstance().getDocument(fileToPatch);
    if (document == null) {
      throw new IOException("Failed to set contents for updated file " + fileToPatch.getPath());
    }
    document.setText(applier.getAfter());
    FileDocumentManager.getInstance().saveDocument(document);
    return new Result(applier.getStatus()) {
      @Override
      public ApplyPatchForBaseRevisionTexts getMergeData() {
        return null;
      }
    };
  }
  applier.trySolveSomehow();
  return new Result(ApplyPatchStatus.FAILURE) {
    @Override
    public ApplyPatchForBaseRevisionTexts getMergeData() {
      return ApplyPatchForBaseRevisionTexts.create(project, fileToPatch, pathBeforeRename, myPatch, baseContents);
    }
  };
}
 
Example 15
Source File: CompletionInitializationUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
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);
}