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

The following examples show how to use com.intellij.psi.PsiDocumentManager#commitDocument() . 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: FluidTypedHandler.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@NotNull
public Result beforeCharTyped(char c, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file, @NotNull FileType fileType) {
    if (!(file.getViewProvider() instanceof FluidFileViewProvider)) {

        return Result.CONTINUE;
    } else if (c != '{') {

        return Result.CONTINUE;
    } else {
        int offset = editor.getCaretModel().getOffset();

        StringBuilder buf = new StringBuilder();
        String space = isWhitespaceRequired(project, c) ? " " : "";
        buf.append(c).append(space);
        if (isClosingSequenceNeeded(editor, offset, c)) {
            buf.append(space).append('}');
        }

        typeInStringAndMoveCaret(editor, buf.toString(), 1 + space.length());
        PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
        documentManager.commitDocument(editor.getDocument());

        return Result.STOP;
    }
}
 
Example 2
Source File: GradleUtil.java    From freeline with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 插入插件的表达式
 * 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 3
Source File: YamlCreateServiceArgumentsCallback.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@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 4
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 5
Source File: CodeInsightUtilCore.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
public static <T extends PsiElement> T forcePsiPostprocessAndRestoreElement(@Nonnull T element,
                                                                            boolean useFileLanguage) {
  final PsiFile psiFile = element.getContainingFile();
  final Document document = psiFile.getViewProvider().getDocument();
  //if (document == null) return element;
  final Language language = useFileLanguage ? psiFile.getLanguage() : PsiUtilCore.getDialect(element);
  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(psiFile.getProject());
  final RangeMarker rangeMarker = document.createRangeMarker(element.getTextRange());
  documentManager.doPostponedOperationsAndUnblockDocument(document);
  documentManager.commitDocument(document);

  T elementInRange = findElementInRange(psiFile, rangeMarker.getStartOffset(), rangeMarker.getEndOffset(),
                                        (Class<? extends T>)element.getClass(),
                                        language, element);
  rangeMarker.dispose();
  return elementInRange;
}
 
Example 6
Source File: CustomizableLanguageCodeStylePanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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 7
Source File: PasteReferenceProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void insert(final String fqn, final PsiElement element, final Editor editor, final QualifiedNameProvider provider) {
  final Project project = editor.getProject();
  if (project == null) return;

  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  documentManager.commitDocument(editor.getDocument());

  final PsiFile file = documentManager.getPsiFile(editor.getDocument());
  if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

  CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
    Document document = editor.getDocument();
    documentManager.doPostponedOperationsAndUnblockDocument(document);
    documentManager.commitDocument(document);
    EditorModificationUtil.deleteSelectedText(editor);
    provider.insertQualifiedName(fqn, element, editor, project);
  }), IdeBundle.message("command.pasting.reference"), null);
}
 
Example 8
Source File: MoveElementLeftRightActionHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@RequiredUIAccess
protected boolean isEnabledForCaret(@Nonnull Editor editor, @Nonnull Caret caret, DataContext dataContext) {
  Project project = editor.getProject();
  if (project == null) return false;
  Document document = editor.getDocument();
  if (!(document instanceof DocumentEx)) return false;
  PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
  psiDocumentManager.commitDocument(document);
  PsiFile file = psiDocumentManager.getPsiFile(document);
  if (file == null || !file.isValid()) return false;
  PsiElement[] elementList = getElementList(file, caret.getSelectionStart(), caret.getSelectionEnd());
  return elementList != null;
}
 
Example 9
Source File: RearrangeCodeAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  final Project project = e.getProject();
  if (project == null) {
    return;
  }

  final Editor editor = e.getData(CommonDataKeys.EDITOR);
  if (editor == null) {
    return;
  }

  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  Document document = editor.getDocument();
  documentManager.commitDocument(document);

  final PsiFile file = documentManager.getPsiFile(document);
  if (file == null) {
    return;
  }

  SelectionModel model = editor.getSelectionModel();
  if (model.hasSelection()) {
    new RearrangeCodeProcessor(file, model).run();
  }
  else {
    new RearrangeCodeProcessor(file).run();
  }
}
 
Example 10
Source File: FormatterBasedIndentAdjuster.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void scheduleIndentAdjustment(@Nonnull Project myProject, @Nonnull Document myDocument, int myOffset) {
  IndentAdjusterRunnable fixer = new IndentAdjusterRunnable(myProject, myDocument, myOffset);
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
  if (isSynchronousAdjustment(myDocument)) {
    documentManager.commitDocument(myDocument);
    fixer.run();
  }
  else {
    documentManager.performLaterWhenAllCommitted(fixer);
  }
}
 
Example 11
Source File: FormatterBasedLineIndentProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public String getLineIndent(@Nonnull Project project, @Nonnull Editor editor, Language language, int offset) {
  Document document = editor.getDocument();
  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  documentManager.commitDocument(document);
  PsiFile file = documentManager.getPsiFile(document);
  if (file == null) return "";
  return CodeStyleManager.getInstance(project).getLineIndent(file, offset, FormattingMode.ADJUST_INDENT_ON_ENTER);
}
 
Example 12
Source File: InnerBuilderHandler.java    From innerbuilder with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: GenerateParserAction.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void actionPerformed(final AnActionEvent e) {
	Project project = e.getData(PlatformDataKeys.PROJECT);
	if ( project==null ) {
		LOG.error("actionPerformed no project for "+e);
		return; // whoa!
	}
	VirtualFile grammarFile = MyActionUtils.getGrammarFileFromEvent(e);
	LOG.info("actionPerformed "+(grammarFile==null ? "NONE" : grammarFile));
	if ( grammarFile==null ) return;
	String title = "ANTLR Code Generation";
	boolean canBeCancelled = true;

	// commit changes to PSI and file system
	PsiDocumentManager psiMgr = PsiDocumentManager.getInstance(project);
	FileDocumentManager docMgr = FileDocumentManager.getInstance();
	Document doc = docMgr.getDocument(grammarFile);
	if ( doc==null ) return;

	boolean unsaved = !psiMgr.isCommitted(doc) || docMgr.isDocumentUnsaved(doc);
	if ( unsaved ) {
		// save event triggers ANTLR run if autogen on
		psiMgr.commitDocument(doc);
		docMgr.saveDocument(doc);
	}

	boolean forceGeneration = true; // from action, they really mean it
	RunANTLROnGrammarFile gen =
		new RunANTLROnGrammarFile(grammarFile,
								  project,
								  title,
								  canBeCancelled,
								  forceGeneration);

	boolean autogen = ANTLRv4GrammarPropertiesStore.getGrammarProperties(project, grammarFile).shouldAutoGenerateParser();
	if ( !unsaved || !autogen ) {
		// if everything already saved (not stale) then run ANTLR
		// if had to be saved and autogen NOT on, then run ANTLR
		// Otherwise, the save file event will have or will run ANTLR.
		ProgressManager.getInstance().run(gen); //, "Generating", canBeCancelled, e.getData(PlatformDataKeys.PROJECT));

		// refresh from disk to see new files
		Set<File> generatedFiles = new HashSet<>();
		generatedFiles.add(new File(gen.getOutputDirName()));
		LocalFileSystem.getInstance().refreshIoFiles(generatedFiles, true, true, null);
		// pop up a notification
		Notification notification =
			new Notification(RunANTLROnGrammarFile.groupDisplayId,
							 "parser for " + grammarFile.getName() + " generated",
							 "to " + gen.getOutputDirName(),
							 NotificationType.INFORMATION);
		Notifications.Bus.notify(notification, project);
	}
}
 
Example 14
Source File: TypedHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static void indentBrace(@Nonnull final Project project, @Nonnull final Editor editor, final char braceChar) {
  final int offset = editor.getCaretModel().getOffset() - 1;
  final Document document = editor.getDocument();
  CharSequence chars = document.getCharsSequence();
  if (offset < 0 || chars.charAt(offset) != braceChar) return;

  int spaceStart = CharArrayUtil.shiftBackward(chars, offset - 1, " \t");
  if (spaceStart < 0 || chars.charAt(spaceStart) == '\n' || chars.charAt(spaceStart) == '\r') {
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    documentManager.commitDocument(document);

    final PsiFile file = documentManager.getPsiFile(document);
    if (file == null || !file.isWritable()) return;
    PsiElement element = file.findElementAt(offset);
    if (element == null) return;

    EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter();
    HighlighterIterator iterator = highlighter.createIterator(offset);

    final FileType fileType = file.getFileType();
    BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator);
    boolean rBraceToken = braceMatcher.isRBraceToken(iterator, chars, fileType);
    final boolean isBrace = braceMatcher.isLBraceToken(iterator, chars, fileType) || rBraceToken;
    int lBraceOffset = -1;

    if (CodeInsightSettings.getInstance().REFORMAT_BLOCK_ON_RBRACE && rBraceToken && braceMatcher.isStructuralBrace(iterator, chars, fileType) && offset > 0) {
      lBraceOffset = BraceMatchingUtil
              .findLeftLParen(highlighter.createIterator(offset - 1), braceMatcher.getOppositeBraceTokenType(iterator.getTokenType()), editor.getDocument().getCharsSequence(), fileType);
    }
    if (element.getNode() != null && isBrace) {
      DefaultRawTypedHandler handler = ((TypedActionImpl)TypedAction.getInstance()).getDefaultRawTypedHandler();
      handler.beginUndoablePostProcessing();

      final int finalLBraceOffset = lBraceOffset;
      ApplicationManager.getApplication().runWriteAction(() -> {
        try {
          int newOffset;
          if (finalLBraceOffset != -1) {
            RangeMarker marker = document.createRangeMarker(offset, offset + 1);
            CodeStyleManager.getInstance(project).reformatRange(file, finalLBraceOffset, offset, true);
            newOffset = marker.getStartOffset();
            marker.dispose();
          }
          else {
            newOffset = CodeStyleManager.getInstance(project).adjustLineIndent(file, offset);
          }

          editor.getCaretModel().moveToOffset(newOffset + 1);
          editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
          editor.getSelectionModel().removeSelection();
        }
        catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      });
    }
  }
}