Java Code Examples for com.intellij.psi.PsiDocumentManager#getDocument()

The following examples show how to use com.intellij.psi.PsiDocumentManager#getDocument() . 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
/**
 * 插入插件的表达式
 * apply plugin: 'com.antfortune.freeline'
 *
 * @param project
 * @param psiFile
 * @param pluginId
 */
public static void applyPlugin(Project project, GroovyFile psiFile, String pluginId) {
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
    GrStatement grStatement = factory.createExpressionFromText(String.format("apply plugin: \'%s\'",
            new Object[]{pluginId}), null);
    GrExpression expression = GroovyFileUil.getLastPlugin(psiFile);
    if (expression != null && expression.getParent() != null) {
        psiFile.addAfter(grStatement, expression.getParent());
        // 换行
        psiFile.addAfter(factory.createLineTerminator("\n"), expression.getParent());
    }
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    Document document = documentManager.getDocument(psiFile);
    if (document != null) {
        documentManager.commitDocument(document);
    }
}
 
Example 2
private void formatInternal(PsiFile file, Collection<TextRange> ranges) {
  ApplicationManager.getApplication().assertWriteAccessAllowed();
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
  documentManager.commitAllDocuments();
  CheckUtil.checkWritable(file);

  Document document = documentManager.getDocument(file);

  if (document == null) {
    return;
  }
  // If there are postponed PSI changes (e.g., during a refactoring), just abort.
  // If we apply them now, then the incoming text ranges may no longer be valid.
  if (documentManager.isDocumentBlockedByPsi(document)) {
    return;
  }

  format(file, document, ranges);
}
 
Example 3
private void formatInternal(PsiFile file, Collection<TextRange> ranges) {
  ApplicationManager.getApplication().assertWriteAccessAllowed();
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
  documentManager.commitAllDocuments();
  CheckUtil.checkWritable(file);

  Document document = documentManager.getDocument(file);

  if (document == null) {
    return;
  }
  // If there are postponed PSI changes (e.g., during a refactoring), just abort.
  // If we apply them now, then the incoming text ranges may no longer be valid.
  if (documentManager.isDocumentBlockedByPsi(document)) {
    return;
  }

  format(document, ranges);
}
 
Example 4
Source Project: intellij-haxe   File: HaxePsiBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private void printErrorInfo(int offset, String token, String message) {

    PsiDocumentManager mgr = PsiDocumentManager.getInstance(getProject());
    Document doc = null != mgr ? mgr.getDocument(psiFile) : null;
    int line = null != doc ? doc.getLineNumber(offset) + 1 : StringUtil.offsetToLineNumber(getOriginalText(), offset);

    StringBuilder s = new StringBuilder();
    s.append("Parsing error at ");
    s.append(null != psiFile ? psiFile.getName() : "<text>");
    s.append(", ");
    s.append(line);
    s.append(": '");
    s.append(null != token ? token : "<unknown token>");
    s.append("'.  ");
    s.append(null != message ? message : "<no message>");

    String error = s.toString();
    boolean needToReport;
    synchronized (this) {
      needToReport = reportedErrors.add(error);
    }
    if (needToReport) {
      LOG.debug(error);
    }
  }
 
Example 5
@Override
public void insert(List<String> items) {
    PsiDocumentManager manager = PsiDocumentManager.getInstance(serviceKeyValue.getProject());
    Document document = manager.getDocument(serviceKeyValue.getContainingFile());
    if (document == null) {
        return;
    }

    List<String> arrayList = new ArrayList<>();
    for (String item : items) {
        arrayList.add("'@" + (StringUtils.isNotBlank(item) ? item : "?") + "'");
    }

    YamlHelper.putKeyValue(serviceKeyValue, "arguments", "[" + StringUtils.join(arrayList, ", ") + "]");

    manager.doPostponedOperationsAndUnblockDocument(document);
    manager.commitDocument(document);
}
 
Example 6
Source Project: consulo   File: FileContentUtil.java    License: 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 7
Source Project: consulo   File: CustomTemplateCallback.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
public static PsiElement getContext(@Nonnull PsiFile file, int offset, boolean searchInInjectedFragment) {
  PsiElement element = null;
  if (searchInInjectedFragment && !InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file)) {
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(file.getProject());
    Document document = documentManager.getDocument(file);
    if (document != null && !documentManager.isCommitted(document)) {
      LOGGER.error("Trying to access to injected template context on uncommited document, offset = " + offset, AttachmentFactory.createAttachment(file.getVirtualFile()));
    }
    else {
      element = InjectedLanguageManager.getInstance(file.getProject()).findInjectedElementAt(file, offset);
    }
  }
  if (element == null) {
    element = PsiUtilCore.getElementAtOffset(file, offset);
  }
  return element;
}
 
Example 8
@Override
protected PsiFile doReformat(final Project project, final PsiFile psiFile) {
  final String text = psiFile.getText();
  final PsiDocumentManager manager = PsiDocumentManager.getInstance(project);
  final Document doc = manager.getDocument(psiFile);
  CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
    if (doc != null) {
      doc.replaceString(0, doc.getTextLength(), text);
      manager.commitDocument(doc);
    }
    try {
      CodeStyleManager.getInstance(project).reformat(psiFile);
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }), "", "");
  if (doc != null) {
    manager.commitDocument(doc);
  }
  return psiFile;
}
 
Example 9
@Override
protected void tearDown() throws Exception {
    // clean up the schema discovery caches
    for (PsiFile psiFile : psiFiles) {
        PsiDocumentManager documentManager = PsiDocumentManager.getInstance(psiFile.getProject());
        final Document document = documentManager.getDocument(psiFile);
        assertNotNull(document);
        ApplicationManager.getApplication().runWriteAction(() -> {
            document.setText("");
            documentManager.commitAllDocuments();
        });
    }
    super.tearDown();
}
 
Example 10
Source Project: consulo   File: UsageViewTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testUsageViewHandlesDocumentChange() throws Exception {
  PsiFile psiFile = createFile("X.java", "public class X{ int xxx; } //comment");
  Usage usage = createUsage(psiFile, psiFile.getText().indexOf("xxx"));

  UsageView usageView = UsageViewManager.getInstance(getProject()).createUsageView(UsageTarget.EMPTY_ARRAY, new Usage[]{usage}, new UsageViewPresentation(), null);
  Disposer.register(getTestRootDisposable(), usageView);

  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
  Document document = documentManager.getDocument(psiFile);
  document.insertString(0, "/* sdfsdfsd */");
  documentManager.commitAllDocuments();
  int navigationOffset = ((UsageInfo2UsageAdapter)usage).getUsageInfo().getNavigationOffset();
  assertEquals(psiFile.getText().indexOf("xxx"), navigationOffset);
}
 
Example 11
Source Project: consulo   File: UsageViewTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testTextUsageInfoHandlesDocumentChange() throws Exception {
  PsiFile psiFile = createFile("X.java", "public class X{ int xxx; } //comment");
  Usage usage = new UsageInfo2UsageAdapter(new UsageInfo(psiFile, psiFile.getText().indexOf("xxx"), StringUtil.indexOfSubstringEnd(psiFile.getText(),"xxx")));

  UsageView usageView = UsageViewManager.getInstance(getProject()).createUsageView(UsageTarget.EMPTY_ARRAY, new Usage[]{usage}, new UsageViewPresentation(), null);
  Disposer.register(getTestRootDisposable(), usageView);

  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
  Document document = documentManager.getDocument(psiFile);
  document.insertString(0, "/* sdfsdfsd */");
  documentManager.commitAllDocuments();
  int navigationOffset = ((UsageInfo2UsageAdapter)usage).getUsageInfo().getNavigationOffset();
  assertEquals(psiFile.getText().indexOf("xxx"), navigationOffset);
}
 
Example 12
Source Project: consulo   File: HTMLTextPainter.java    License: Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
  public HTMLTextPainter(PsiFile psiFile, Project project, String dirName, boolean printLineNumbers) {
    myProject = project;
    myPsiFile = psiFile;
    myPrintLineNumbers = printLineNumbers;
    myHighlighter = HighlighterFactory.createHighlighter(project, psiFile.getVirtualFile());

//    String fileType = FileTypeManager.getInstance().getType(psiFile.getVirtualFile().getName());
//    myForceFonts =
//      FileTypeManager.TYPE_HTML.equals(fileType) ||
//      FileTypeManager.TYPE_XML.equals(fileType) ||
//      FileTypeManager.TYPE_JSP.equals(fileType);

    myText = psiFile.getText();
    myHighlighter.setText(myText);
    mySegmentEnd = myText.length();
    myFileName = psiFile.getVirtualFile().getPresentableUrl();
    myHTMLFileName = dirName + File.separator + ExportToHTMLManager.getHTMLFileName(psiFile);

    PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    Document document = psiDocumentManager.getDocument(psiFile);

    List<LineMarkerInfo> methodSeparators = new ArrayList<LineMarkerInfo>();
    if (document != null) {
      final List<LineMarkerInfo> separators = FileSeparatorUtil.getFileSeparators(psiFile, document);
      methodSeparators.addAll(separators);
    }

    myMethodSeparators = methodSeparators.toArray(new LineMarkerInfo[methodSeparators.size()]);
    myCurrentMethodSeparator = 0;
  }
 
Example 13
Source Project: consulo   File: DuplocatorHashCallback.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"HardCodedStringLiteral"})
private static void writeFragments(final List<? extends PsiFragment> psiFragments, Element duplicateElement, Project project, final boolean shouldWriteOffsets) {
  final PathMacroManager macroManager = PathMacroManager.getInstance(project);
  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);

  for (PsiFragment fragment : psiFragments) {
    final PsiFile psiFile = fragment.getFile();
    final VirtualFile virtualFile = psiFile != null ? psiFile.getVirtualFile() : null;
    if (virtualFile != null) {
      Element fragmentElement = new Element("fragment");
      fragmentElement.setAttribute("file", macroManager.collapsePath(virtualFile.getUrl()));
      if (shouldWriteOffsets) {
        final Document document = documentManager.getDocument(psiFile);
        LOG.assertTrue(document != null);
        int startOffset = fragment.getStartOffset();
        final int line = document.getLineNumber(startOffset);
        fragmentElement.setAttribute("line", String.valueOf(line));
        final int lineStartOffset = document.getLineStartOffset(line);
        if (StringUtil.isEmptyOrSpaces(document.getText().substring(lineStartOffset, startOffset))) {
          startOffset = lineStartOffset;
        }
        fragmentElement.setAttribute("start", String.valueOf(startOffset));
        fragmentElement.setAttribute("end", String.valueOf(fragment.getEndOffset()));
        if (fragment.containsMultipleFragments()) {
          final int[][] offsets = fragment.getOffsets();
          for (int[] offset : offsets) {
            Element offsetElement = new Element("offset");
            offsetElement.setAttribute("start", String.valueOf(offset[0]));
            offsetElement.setAttribute("end", String.valueOf(offset[1]));
            fragmentElement.addContent(offsetElement);
          }
        }
      }
      duplicateElement.addContent(fragmentElement);
    }
  }
}
 
Example 14
@Override
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    final Document currentDocument = psiDocumentManager.getDocument(file);
    if (currentDocument == null) {
        return;
    }

    psiDocumentManager.commitDocument(currentDocument);

    if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) {
        return;
    }

    if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
        return;
    }

    final List<PsiFieldMember> existingFields = collectFields(file, editor);
    if (existingFields != null) {
        final List<PsiFieldMember> selectedFields = selectFieldsAndOptions(existingFields, project);

        if (selectedFields == null || selectedFields.isEmpty()) {
            return;
        }

        InnerBuilderGenerator.generate(project, editor, file, selectedFields);
    }
}
 
Example 15
@NotNull
private static Icon getTestStateIcon(@NotNull PsiElement element, @NotNull Icon defaultIcon) {
  // SMTTestProxy maps test run data to a URI derived from a location hint produced by `package:test`.
  // If we can find corresponding data, we can provide state-aware icons. If not, we default to
  // a standard Run state.

  PsiFile containingFile;
  try {
    containingFile = element.getContainingFile();
  }
  catch (PsiInvalidElementAccessException e) {
    containingFile = null;
  }

  final Project project = element.getProject();
  final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);

  final Document document = containingFile == null ? null : psiDocumentManager.getDocument(containingFile);
  if (document != null) {
    final int textOffset = element.getTextOffset();
    final int lineNumber = document.getLineNumber(textOffset);

    // e.g., dart_location:///Users/pq/IdeaProjects/untitled1298891289891/test/unit_test.dart,3,2,["my first unit test"]
    final String path = FileUtil.toSystemIndependentName(containingFile.getVirtualFile().getPath());
    final String testLocationPrefix = "dart_location://" + path + "," + lineNumber;

    final TestStateStorage storage = TestStateStorage.getInstance(project);
    if (storage != null) {
      final Map<String, TestStateStorage.Record> tests = storage.getRecentTests(SCANNED_TEST_RESULT_LIMIT, getSinceDate());
      if (tests != null) {
        // TODO(pq): investigate performance implications.
        for (Map.Entry<String, TestStateStorage.Record> entry : tests.entrySet()) {
          if (entry.getKey().startsWith(testLocationPrefix)) {
            final TestStateStorage.Record state = entry.getValue();
            final TestStateInfo.Magnitude magnitude = TestIconMapper.getMagnitude(state.magnitude);
            if (magnitude != null) {
              switch (magnitude) {
                case IGNORED_INDEX:
                  return AllIcons.RunConfigurations.TestState.Yellow2;
                case ERROR_INDEX:
                case FAILED_INDEX:
                  return AllIcons.RunConfigurations.TestState.Red2;
                case PASSED_INDEX:
                case COMPLETE_INDEX:
                  return AllIcons.RunConfigurations.TestState.Green2;
                default:
              }
            }
          }
        }
      }
    }
  }

  return defaultIcon;
}
 
Example 16
@NotNull
private static Icon getTestStateIcon(@NotNull PsiElement element, @NotNull Icon defaultIcon) {
  // SMTTestProxy maps test run data to a URI derived from a location hint produced by `package:test`.
  // If we can find corresponding data, we can provide state-aware icons. If not, we default to
  // a standard Run state.

  PsiFile containingFile;
  try {
    containingFile = element.getContainingFile();
  }
  catch (PsiInvalidElementAccessException e) {
    containingFile = null;
  }

  final Project project = element.getProject();
  final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);

  final Document document = containingFile == null ? null : psiDocumentManager.getDocument(containingFile);
  if (document != null) {
    final int textOffset = element.getTextOffset();
    final int lineNumber = document.getLineNumber(textOffset);

    // e.g., dart_location:///Users/pq/IdeaProjects/untitled1298891289891/test/unit_test.dart,3,2,["my first unit test"]
    final String path = FileUtil.toSystemIndependentName(containingFile.getVirtualFile().getPath());
    final String testLocationPrefix = "dart_location://" + path + "," + lineNumber;

    final TestStateStorage storage = TestStateStorage.getInstance(project);
    if (storage != null) {
      final Map<String, TestStateStorage.Record> tests = storage.getRecentTests(SCANNED_TEST_RESULT_LIMIT, getSinceDate());
      if (tests != null) {
        // TODO(pq): investigate performance implications.
        for (Map.Entry<String, TestStateStorage.Record> entry : tests.entrySet()) {
          if (entry.getKey().startsWith(testLocationPrefix)) {
            final TestStateStorage.Record state = entry.getValue();
            final TestStateInfo.Magnitude magnitude = TestIconMapper.getMagnitude(state.magnitude);
            if (magnitude != null) {
              switch (magnitude) {
                case IGNORED_INDEX:
                  return AllIcons.RunConfigurations.TestState.Yellow2;
                case ERROR_INDEX:
                case FAILED_INDEX:
                  return AllIcons.RunConfigurations.TestState.Red2;
                case PASSED_INDEX:
                case COMPLETE_INDEX:
                  return AllIcons.RunConfigurations.TestState.Green2;
                default:
              }
            }
          }
        }
      }
    }
  }

  return defaultIcon;
}
 
Example 17
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 18
Source Project: consulo   File: SmartEnterProcessor.java    License: Apache License 2.0 4 votes vote down vote up
protected RangeMarker createRangeMarker(final PsiElement elt) {
  final PsiFile psiFile = elt.getContainingFile();
  final PsiDocumentManager instance = PsiDocumentManager.getInstance(elt.getProject());
  final Document document = instance.getDocument(psiFile);
  return document.createRangeMarker(elt.getTextRange());
}
 
Example 19
private static boolean isDocumentCommitted(@Nonnull PsiFile file) {
  PsiDocumentManager manager = PsiDocumentManager.getInstance(file.getProject());
  Document document = manager.getDocument(file);
  return document != null && manager.isCommitted(document);
}