下面列出了com.intellij.psi.util.PsiModificationTracker#com.intellij.openapi.command.CommandProcessor 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void logErrorHeader() {
final String info = ourApplicationInfoProvider.get();
if (info != null) {
myLogger.error(info);
}
myLogger.error("JDK: " + System.getProperties().getProperty("java.version", "unknown"));
myLogger.error("VM: " + System.getProperties().getProperty("java.vm.name", "unknown"));
myLogger.error("Vendor: " + System.getProperties().getProperty("java.vendor", "unknown"));
myLogger.error("OS: " + System.getProperties().getProperty("os.name", "unknown"));
ApplicationEx2 application = (ApplicationEx2)ApplicationManager.getApplication();
if (application != null && application.isComponentsCreated()) {
final String lastPreformedActionId = LastActionTracker.ourLastActionId;
if (lastPreformedActionId != null) {
myLogger.error("Last Action: " + lastPreformedActionId);
}
CommandProcessor commandProcessor = CommandProcessor.getInstance();
final String currentCommandName = commandProcessor.getCurrentCommandName();
if (currentCommandName != null) {
myLogger.error("Current Command: " + currentCommandName);
}
}
}
@RequiredUIAccess
@Override
public void actionPerformed(@Nonnull final AnActionEvent e) {
final Project project = e.getProject();
final Editor editor = e.getData(CommonDataKeys.EDITOR);
if (Boolean.TRUE.equals(e.getData(PlatformDataKeys.IS_MODAL_CONTEXT))) {
return;
}
if (project != null && editor != null) {
if (DumbService.getInstance(project).isDumb()) {
DumbService.getInstance(project).showDumbModeNotification(IdeBundle.message("goto.custom.region.message.dumb.mode"));
return;
}
CommandProcessor processor = CommandProcessor.getInstance();
processor.executeCommand(project, () -> {
Collection<FoldingDescriptor> foldingDescriptors = getCustomFoldingDescriptors(editor, project);
if (foldingDescriptors.size() > 0) {
CustomFoldingRegionsPopup regionsPopup = new CustomFoldingRegionsPopup(foldingDescriptors, editor, project);
regionsPopup.show();
}
else {
notifyCustomRegionsUnavailable(editor, project);
}
}, IdeBundle.message("goto.custom.region.command"), null);
}
}
private void detachLibrary(@Nonnull final LibraryOrderEntry orderEntry, @Nonnull Project project) {
final Module module = orderEntry.getOwnerModule();
String message = IdeBundle.message("detach.library.from.module", orderEntry.getPresentableName(), module.getName());
String title = IdeBundle.message("detach.library");
int ret = Messages.showOkCancelDialog(project, message, title, Messages.getQuestionIcon());
if (ret != Messages.OK) return;
CommandProcessor.getInstance().executeCommand(module.getProject(), () -> {
final Runnable action = () -> {
ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
OrderEntry[] orderEntries = rootManager.getOrderEntries();
ModifiableRootModel model = rootManager.getModifiableModel();
OrderEntry[] modifiableEntries = model.getOrderEntries();
for (int i = 0; i < orderEntries.length; i++) {
OrderEntry entry = orderEntries[i];
if (entry instanceof LibraryOrderEntry && ((LibraryOrderEntry)entry).getLibrary() == orderEntry.getLibrary()) {
model.removeOrderEntry(modifiableEntries[i]);
}
}
model.commit();
};
ApplicationManager.getApplication().runWriteAction(action);
}, title, null);
}
private void insertToEditor(final Project project, final StringElement stringElement) {
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
@Override
public void run() {
getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
if (editor != null) {
int offset = editor.getCaretModel().getOffset();
Document document = editor.getDocument();
String key = stringElement.getName();
if (key != null) {
document.insertString(offset, key);
editor.getCaretModel().moveToOffset(offset + key.length());
}
}
}
});
}
}, "WriteStringKeyCommand", "", UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION);
}
protected void replaceString(@Nonnull final Document document, final int startOffset, final int endOffset, @Nonnull final String newText) {
LOG.assertTrue(!myDuringModification);
try {
myDuringModification = true;
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
@Override
public void run() {
LOG.assertTrue(endOffset <= document.getTextLength());
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
document.replaceString(startOffset, endOffset, newText);
}
});
}
}, DiffBundle.message("save.merge.result.command.name"), document);
}
finally {
myDuringModification = false;
}
}
public void replaceSelection(@Nonnull final String clipboardText) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
final SelectionModel model = Assertions.assertNotNull(getEditor()).getSelectionModel();
final int start = model.getSelectionStart();
final int end = model.getSelectionEnd();
getDocument().replaceString(start, end, "");
getDocument().insertString(start, clipboardText);
}
}, null, null, UndoConfirmationPolicy.DEFAULT, getDocument());
}
});
}
protected void checkFormatting(String expected) throws IOException {
CommandProcessor.getInstance().executeCommand(myFixture.getProject(), new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
final PsiFile file = myFixture.getFile();
TextRange myTextRange = file.getTextRange();
CodeStyleManager.getInstance(file.getProject()).reformatText(file, myTextRange.getStartOffset(), myTextRange.getEndOffset());
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
});
}
}, null, null);
myFixture.checkResult(expected);
}
protected void createSuppression(@NotNull Project project, @NotNull PsiElement element, @NotNull PsiElement container) throws IncorrectOperationException {
if (element.isValid()) {
PsiFile psiFile = element.getContainingFile();
if (psiFile != null) {
psiFile = psiFile.getOriginalFile();
}
if (psiFile != null && psiFile.isValid()) {
final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
if (document != null) {
int lineNo = document.getLineNumber(element.getTextOffset());
final int lineEndOffset = document.getLineEndOffset(lineNo);
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
document.insertString(lineEndOffset, " //eslint-disable-line");
}
}, null, null);
}
}
}
}
@SuppressWarnings({"UNUSED_SYMBOL"})
private void checkPsi(final PsiFile file, String textAfter) {
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
performFormatting(file);
}
});
}
}, "", "");
String fileText = file.getText();
assertEquals(textAfter, fileText);
}
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
CopyPasteManager.getInstance().stopKillRings();
int lineNumber = editor.getCaretModel().getLogicalPosition().line;
if (editor.isColumnMode() && editor.getCaretModel().supportsMultipleCarets()
&& editor.getCaretModel().getOffset() == editor.getDocument().getLineEndOffset(lineNumber)) {
return;
}
boolean camelMode = editor.getSettings().isCamelWords();
if (myNegateCamelMode) {
camelMode = !camelMode;
}
deleteToWordEnd(editor, camelMode);
}
/**
* Updates editor's content depending on the selected {@link TreePath}.
*
* @param path selected tree path
*/
private void updateDescriptionPanel(@NotNull TreePath path) {
final TemplateTreeNode node = (TemplateTreeNode) path.getLastPathComponent();
final Resources.Template template = node.getTemplate();
ApplicationManager.getApplication().runWriteAction(
() -> CommandProcessor.getInstance().runUndoTransparentAction(() -> {
String content = template != null ?
StringUtil.notNullize(template.getContent()).replace('\r', '\0') : "";
previewDocument.replaceString(0, previewDocument.getTextLength(), content);
List<Pair<Integer, Integer>> pairs =
getFilterRanges(profileFilter.getTextEditor().getText(), content);
highlightWords(pairs);
})
);
}
@Nullable
private Exception executeCommand(String commandName, ThrowableRunnable<Exception> invokeCreate) {
final Exception[] exception = new Exception[1];
CommandProcessor.getInstance().executeCommand(myProject, () -> {
LocalHistoryAction action = LocalHistory.getInstance().startAction(commandName);
try {
invokeCreate.run();
}
catch (Exception ex) {
exception[0] = ex;
}
finally {
action.finish();
}
}, commandName, null, UndoConfirmationPolicy.REQUEST_CONFIRMATION);
return exception[0];
}
protected VcsVFSListener(@Nonnull Project project, @Nonnull AbstractVcs vcs) {
myProject = project;
myVcs = vcs;
myChangeListManager = ChangeListManager.getInstance(project);
myDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject);
final MyVirtualFileListener myVFSListener = new MyVirtualFileListener();
final MyCommandAdapter myCommandListener = new MyCommandAdapter();
myVcsManager = ProjectLevelVcsManager.getInstance(project);
myAddOption = myVcsManager.getStandardConfirmation(VcsConfiguration.StandardConfirmation.ADD, vcs);
myRemoveOption = myVcsManager.getStandardConfirmation(VcsConfiguration.StandardConfirmation.REMOVE, vcs);
VirtualFileManager.getInstance().addVirtualFileListener(myVFSListener, this);
CommandProcessor.getInstance().addCommandListener(myCommandListener, this);
myVcsFileListenerContextHelper = VcsFileListenerContextHelper.getInstance(myProject);
}
public static AbstractPerformFixesTask applyFixesNoSort(@Nonnull Project project,
@Nonnull String presentationText,
@Nonnull List<ProblemDescriptor> descriptions,
@Nullable Class quickfixClass) {
final SequentialModalProgressTask progressTask =
new SequentialModalProgressTask(project, presentationText, true);
final boolean isBatch = quickfixClass != null && BatchQuickFix.class.isAssignableFrom(quickfixClass);
final AbstractPerformFixesTask fixesTask = isBatch ?
new PerformBatchFixesTask(project, descriptions.toArray(ProblemDescriptor.EMPTY_ARRAY), progressTask, quickfixClass) :
new PerformFixesTask(project, descriptions.toArray(ProblemDescriptor.EMPTY_ARRAY), progressTask, quickfixClass);
CommandProcessor.getInstance().executeCommand(project, () -> {
CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);
progressTask.setMinIterationTime(200);
progressTask.setTask(fixesTask);
ProgressManager.getInstance().run(progressTask);
}, presentationText, null);
return fixesTask;
}
private void detachLibrary(@Nonnull final LibraryOrderEntry orderEntry, @Nonnull Project project) {
final Module module = orderEntry.getOwnerModule();
String message = IdeBundle.message("detach.library.from.module", orderEntry.getPresentableName(), module.getName());
String title = IdeBundle.message("detach.library");
int ret = Messages.showOkCancelDialog(project, message, title, Messages.getQuestionIcon());
if (ret != Messages.OK) return;
CommandProcessor.getInstance().executeCommand(module.getProject(), () -> {
final Runnable action = () -> {
ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
OrderEntry[] orderEntries = rootManager.getOrderEntries();
ModifiableRootModel model = rootManager.getModifiableModel();
OrderEntry[] modifiableEntries = model.getOrderEntries();
for (int i = 0; i < orderEntries.length; i++) {
OrderEntry entry = orderEntries[i];
if (entry instanceof LibraryOrderEntry && ((LibraryOrderEntry)entry).getLibrary() == orderEntry.getLibrary()) {
model.removeOrderEntry(modifiableEntries[i]);
}
}
model.commit();
};
ApplicationManager.getApplication().runWriteAction(action);
}, title, null);
}
private void undoOrRedo(final FileEditor editor, final boolean isUndo) {
myCurrentOperationState = isUndo ? OperationState.UNDO : OperationState.REDO;
final RuntimeException[] exception = new RuntimeException[1];
Runnable executeUndoOrRedoAction = () -> {
try {
if (myProject != null) {
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
}
CopyPasteManager.getInstance().stopKillRings();
myMerger.undoOrRedo(editor, isUndo);
}
catch (RuntimeException ex) {
exception[0] = ex;
}
finally {
myCurrentOperationState = OperationState.NONE;
}
};
String name = getUndoOrRedoActionNameAndDescription(editor, isUndoInProgress()).second;
CommandProcessor.getInstance()
.executeCommand(myProject, executeUndoOrRedoAction, name, null, myMerger.getUndoConfirmationPolicy());
if (exception[0] != null) throw exception[0];
}
private void updateTemplateTextByVarNameChange(final Variable oldVar, final Variable newVar) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(null, new Runnable() {
@Override
public void run() {
Document document = myEditor.getDocument();
String templateText = document.getText();
templateText = templateText.replaceAll("\\$" + oldVar.getName() + "\\$", "\\$" + newVar.getName() + "\\$");
document.replaceString(0, document.getTextLength(), templateText);
}
}, null, null);
}
});
}
protected void initHistory() {
ChangeListStorage storage;
try {
storage = new ChangeListStorageImpl(getStorageDir());
}
catch (Throwable e) {
LocalHistoryLog.LOG.warn("cannot create storage, in-memory implementation will be used", e);
storage = new InMemoryChangeListStorage();
}
myChangeList = new ChangeList(storage);
myVcs = new LocalHistoryFacade(myChangeList);
myGateway = new IdeaGateway();
myEventDispatcher = new LocalHistoryEventDispatcher(myVcs, myGateway);
CommandProcessor.getInstance().addCommandListener(myEventDispatcher, this);
myConnection = myBus.connect();
myConnection.subscribe(VirtualFileManager.VFS_CHANGES, myEventDispatcher);
VirtualFileManager fm = VirtualFileManager.getInstance();
fm.addVirtualFileManagerListener(myEventDispatcher, this);
}
@Override
public void elementRenamed(@NotNull final PsiElement psiElement)
{
final String moduleName = originalFile.substring(0, originalFile.indexOf('.'));
CommandProcessor.getInstance().executeCommand(psiElement.getProject(), new Runnable() {
@Override
public void run() {
new ModuleImporter(possibleFiles,
moduleName,
(PsiFile) psiElement,
new SourcesLocator().getSourceLibraries(psiElement.getProject()).toArray(new SourceLibrary[0]),
ServiceManager.getService(psiElement.getProject(),
DojoSettings.class).getNamingExceptionList())
.findFilesThatReferenceModule(SourcesLocator.getProjectSourceDirectories(psiElement.getProject(), true), true);
}
},
"Rename Dojo Module",
"Rename Dojo Module");
}
@Override
public void run(Object[] result)
{
DeclareResolver util = new DeclareResolver();
final DeclareStatementItems utilItem = util.getDeclareStatementFromParsedStatement(result);
if(utilItem == null)
{
Notifications.Bus.notify(new Notification("needsmoredojo", "Convert class module to util module", "Valid declare block was not found", NotificationType.WARNING));
return;
}
CommandProcessor.getInstance().executeCommand(utilItem.getDeclareContainingStatement().getProject(), new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
doRefactor(utilItem.getClassName(), utilItem.getDeclareContainingStatement(), utilItem.getExpressionsToMixin(), utilItem.getMethodsToConvert());
}
});
}
},
"Convert class module to util module",
"Convert class module to util module");
}
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);
}
private static void expandTemplate(@Nonnull final PostfixTemplate template,
@Nonnull final Editor editor,
@Nonnull final PsiElement context) {
if (template.startInWriteAction()) {
ApplicationManager.getApplication().runWriteAction(() -> CommandProcessor.getInstance()
.executeCommand(context.getProject(), () -> template.expand(context, editor), "Expand postfix template", POSTFIX_TEMPLATE_ID));
}
else {
template.expand(context, editor);
}
}
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(getProject(), () -> {
final CodeCompletionHandlerBase handler = new CodeCompletionHandlerBase(CompletionType.BASIC) {
@Override
protected void completionFinished(final CompletionProgressIndicator indicator, boolean hasModifiers) {
// find our lookup element
final LookupElement lookupElement = ContainerUtil.find(indicator.getLookup().getItems(), insert::match);
if(lookupElement == null) {
fail("No matching lookup element found");
}
// overwrite behavior and force completion + insertHandler
CommandProcessor.getInstance().executeCommand(indicator.getProject(), new Runnable() {
@Override
public void run() {
//indicator.setMergeCommand(); Currently method has package level access
indicator.getLookup().finishLookup(Lookup.AUTO_INSERT_SELECT_CHAR, lookupElement);
}
}, "Autocompletion", null);
}
};
Editor editor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(getEditor(), getFile());
handler.invokeCompletion(getProject(), editor);
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
}, null, null);
}
@RequiredUIAccess
@Override
public void actionPerformed(final AnActionEvent e) {
final Project project = e.getData(CommonDataKeys.PROJECT);
final CommandProcessor commandProcessor = CommandProcessor.getInstance();
commandProcessor.executeCommand(project, () -> {
List<Pair<EditorComposite, EditorWindow>> filesToClose = getFilesToClose(e);
for (int i = 0; i != filesToClose.size(); ++i) {
final Pair<EditorComposite, EditorWindow> we = filesToClose.get(i);
we.getSecond().closeFile(we.getFirst().getFile());
}
}, IdeBundle.message("command.close.all.unmodified.editors"), null);
}
@Nonnull
@Override
protected FutureTask<Boolean> prepareTask(@Nonnull final PsiFile file, final boolean processChangedTextOnly) {
return new FutureTask<Boolean>(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
try {
Collection<TextRange> ranges = getRangesToFormat(file, processChangedTextOnly);
Document document = PsiDocumentManager.getInstance(myProject).getDocument(file);
if (document != null && Rearranger.EXTENSION.forLanguage(file.getLanguage()) != null) {
PsiDocumentManager.getInstance(myProject).doPostponedOperationsAndUnblockDocument(document);
PsiDocumentManager.getInstance(myProject).commitDocument(document);
Runnable command = prepareRearrangeCommand(file, ranges);
try {
CommandProcessor.getInstance().executeCommand(myProject, command, COMMAND_NAME, null);
}
finally {
PsiDocumentManager.getInstance(myProject).commitDocument(document);
}
}
return true;
}
catch (FilesTooBigForDiffException e) {
handleFileTooBigException(LOG, e, file);
return false;
}
}
});
}
public void actionPerformedImpl(final Project project, final Editor hostEditor) {
CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
MultiCaretCodeInsightActionHandler handler = getHandler();
try {
iterateOverCarets(project, hostEditor, handler);
}
finally {
handler.postInvoke();
}
}), getCommandName(), DocCommandGroupId.noneGroupId(hostEditor.getDocument()));
hostEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
@Override
public void applyText(final String text, final Project project) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
@Override
public void run() {
doApplyText(text, project);
}
}, "Merge changes", null);
}
});
}
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
MacUIUtil.hideCursor();
CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
if (editor instanceof EditorWindow) {
// manipulate actual document/editor instead of injected
// since the latter have trouble finding the right location of caret movement in the case of multi-shred injected fragments
editor = ((EditorWindow)editor).getDelegate();
}
doBackSpaceAtCaret(editor);
}
@Override
public void run() {
int lineStart = myDocument.getLineStartOffset(myLine);
CommandProcessor.getInstance().runUndoTransparentAction(() -> ApplicationManager.getApplication().runWriteAction(() -> {
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject);
if (codeStyleManager instanceof FormattingModeAwareIndentAdjuster) {
((FormattingModeAwareIndentAdjuster)codeStyleManager).adjustLineIndent(myDocument, lineStart, FormattingMode.ADJUST_INDENT_ON_ENTER);
}
}));
}
public void doApplyFix(@Nonnull final RefEntity[] refElements, @Nonnull InspectionResultsView view) {
final RefManagerImpl refManager = (RefManagerImpl)view.getGlobalInspectionContext().getRefManager();
final boolean initial = refManager.isInProcess();
refManager.inspectionReadActionFinished();
try {
final boolean[] refreshNeeded = {false};
if (refElements.length > 0) {
final Project project = refElements[0].getRefManager().getProject();
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
refreshNeeded[0] = applyFix(refElements);
}
});
}
}, getTemplatePresentation().getText(), null);
}
if (refreshNeeded[0]) {
refreshViews(view.getProject(), refElements, myToolWrapper);
}
}
finally { //to make offline view lazy
if (initial) refManager.inspectionReadActionStarted();
}
}