Java Code Examples for com.intellij.openapi.command.CommandProcessor

The following examples show how to use com.intellij.openapi.command.CommandProcessor. 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
Source Project: consulo   Source File: Log4J2Logger.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
  }
}
 
Example 2
Source Project: consulo   Source File: GotoCustomRegionAction.java    License: Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 3
Source Project: consulo   Source File: ProjectViewImpl.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 4
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);
}
 
Example 5
Source Project: consulo   Source File: DocumentsSynchronizer.java    License: Apache License 2.0 6 votes vote down vote up
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;
  }
}
 
Example 6
Source Project: netbeans-mmd-plugin   Source File: PlainTextEditor.java    License: Apache License 2.0 6 votes vote down vote up
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());
    }
  });
}
 
Example 7
Source Project: BashSupport   Source File: BashFormatterTestCase.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 8
Source Project: eslint-plugin   Source File: PropertySuppressableInspectionBase.java    License: MIT License 6 votes vote down vote up
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);
            }
        }
    }
}
 
Example 9
Source Project: consulo   Source File: FormatterTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 10
Source Project: consulo   Source File: DeleteToWordEndAction.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 11
Source Project: idea-gitignore   Source File: GeneratorDialog.java    License: MIT License 6 votes vote down vote up
/**
 * 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);
            })
    );
}
 
Example 12
Source Project: consulo   Source File: ElementCreator.java    License: Apache License 2.0 6 votes vote down vote up
@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];
}
 
Example 13
Source Project: consulo   Source File: VcsVFSListener.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 14
Source Project: consulo   Source File: CleanupInspectionIntention.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 15
Source Project: consulo   Source File: WebProjectViewImpl.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 16
Source Project: consulo   Source File: UndoManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
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];
}
 
Example 17
Source Project: consulo   Source File: EditVariableDialog.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
  });
}
 
Example 18
Source Project: consulo   Source File: LocalHistoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 19
Source Project: needsmoredojo   Source File: RenameRefactoringListener.java    License: Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example 20
Source Project: needsmoredojo   Source File: ClassToUtilConverter.java    License: Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example 21
Source Project: consulo   Source File: PasteReferenceProvider.java    License: 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 22
Source Project: consulo   Source File: PostfixLiveTemplate.java    License: Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 23
@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);
}
 
Example 24
Source Project: consulo   Source File: CloseEditorsActionBase.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 25
Source Project: consulo   Source File: RearrangeCodeProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@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;
      }
    }
  });
}
 
Example 26
Source Project: consulo   Source File: MultiCaretCodeInsightAction.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 27
Source Project: consulo   Source File: MergeVersion.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
  });
}
 
Example 28
Source Project: consulo   Source File: BackspaceAction.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 29
Source Project: consulo   Source File: FormatterBasedIndentAdjuster.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
  }));
}
 
Example 30
Source Project: consulo   Source File: QuickFixAction.java    License: Apache License 2.0 5 votes vote down vote up
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();
  }
}