Example usage for com.intellij.openapi.command.undo UndoManager getInstance

List of usage examples for com.intellij.openapi.command.undo UndoManager getInstance

Introduction

In this page you can find the example usage for com.intellij.openapi.command.undo UndoManager getInstance.

Prototype

public static UndoManager getInstance(@NotNull Project project) 

Source Link

Usage

From source file:com.android.tools.idea.gradle.AndroidGradleJavaProjectModelModifier.java

License:Apache License

private static void registerUndoAction(@NotNull Project project) {
    UndoManager.getInstance(project).undoableActionPerformed(new BasicUndoableAction() {
        @Override//w ww  .  ja  va 2 s  .c  o m
        public void undo() throws UnexpectedUndoException {
            requestProjectSync(project);
        }

        @Override
        public void redo() throws UnexpectedUndoException {
            requestProjectSync(project);
        }
    });
}

From source file:com.goide.codeInsight.imports.GoReferenceImporterTest.java

License:Apache License

public void testUndo() {
    DaemonCodeAnalyzerSettings.getInstance().setImportHintEnabled(true);
    updateSettings(true);// ww w  . j  a va2  s  . co m
    myFixture.configureByText("a.go", "package main\n\nfunc main() { <caret> }");
    myFixture.type("fmt.");
    myFixture.doHighlighting();
    myFixture.doHighlighting();
    myFixture.checkResult("package main\n\nimport \"fmt\"\n\nfunc main() { fmt. }");
    FileEditor editor = FileEditorManager.getInstance(myFixture.getProject())
            .getSelectedEditor(myFixture.getFile().getVirtualFile());
    UndoManager.getInstance(myFixture.getProject()).undo(editor);
    myFixture.checkResult("package main\n\nfunc main() { <caret> }");
}

From source file:com.intellij.codeInsight.CodeInsightTestCase.java

License:Apache License

protected void undo() {
    UndoManager undoManager = UndoManager.getInstance(myProject);
    TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(getEditor());
    undoManager.undo(textEditor);/* ww w  .  jav  a2  s . co m*/
}

From source file:com.intellij.codeInsight.completion.XmlTagInsertHandler.java

License:Apache License

public static void insertIncompleteTag(char completionChar, final Editor editor, XmlTag tag) {
    XmlElementDescriptor descriptor = tag.getDescriptor();
    final Project project = editor.getProject();
    TemplateManager templateManager = TemplateManager.getInstance(project);
    Template template = templateManager.createTemplate("", "");

    template.setToIndent(true);//from   w  w  w . j  av a 2 s .co  m

    // temp code
    PsiFile containingFile = tag.getContainingFile();
    boolean htmlCode = HtmlUtil.hasHtml(containingFile) || HtmlUtil.supportsXmlTypedHandlers(containingFile);
    template.setToReformat(!htmlCode);

    StringBuilder indirectRequiredAttrs = addRequiredAttributes(descriptor, tag, template, containingFile);
    final boolean chooseAttributeName = addTail(completionChar, descriptor, htmlCode, tag, template,
            indirectRequiredAttrs);

    templateManager.startTemplate(editor, template, new TemplateEditingAdapter() {
        private RangeMarker myAttrValueMarker;

        @Override
        public void waitingForInput(Template template) {
            int offset = editor.getCaretModel().getOffset();
            myAttrValueMarker = editor.getDocument().createRangeMarker(offset + 1, offset + 4);
        }

        @Override
        public void templateFinished(final Template template, boolean brokenOff) {
            final int offset = editor.getCaretModel().getOffset();

            if (chooseAttributeName && offset > 0) {
                char c = editor.getDocument().getCharsSequence().charAt(offset - 1);
                if (c == '/' || (c == ' ' && brokenOff)) {
                    new WriteCommandAction.Simple(project) {
                        @Override
                        protected void run() throws Throwable {
                            editor.getDocument().replaceString(offset, offset + 3, ">");
                        }
                    }.execute();
                }
            }
        }

        @Override
        public void templateCancelled(final Template template) {
            if (myAttrValueMarker == null) {
                return;
            }

            final UndoManager manager = UndoManager.getInstance(project);
            if (manager.isUndoInProgress() || manager.isRedoInProgress()) {
                return;
            }

            if (chooseAttributeName && myAttrValueMarker.isValid()) {
                final int startOffset = myAttrValueMarker.getStartOffset();
                final int endOffset = myAttrValueMarker.getEndOffset();
                new WriteCommandAction.Simple(project) {
                    @Override
                    protected void run() throws Throwable {
                        editor.getDocument().replaceString(startOffset, endOffset, ">");
                    }
                }.execute();
            }
        }
    });
}

From source file:com.intellij.codeInsight.daemon.impl.PostHighlightingPass.java

License:Apache License

public static void invokeOnTheFlyImportOptimizer(@NotNull final Runnable runnable, @NotNull final PsiFile file,
        @NotNull final Editor editor) {
    final long stamp = editor.getDocument().getModificationStamp();
    ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override//from w w  w  .  j  av  a 2s  . c o  m
        public void run() {
            if (file.getProject().isDisposed() || editor.isDisposed()
                    || editor.getDocument().getModificationStamp() != stamp) {
                return;
            }
            //no need to optimize imports on the fly during undo/redo
            final UndoManager undoManager = UndoManager.getInstance(editor.getProject());
            if (undoManager.isUndoInProgress() || undoManager.isRedoInProgress()) {
                return;
            }
            PsiDocumentManager.getInstance(file.getProject()).commitAllDocuments();
            String beforeText = file.getText();
            final long oldStamp = editor.getDocument().getModificationStamp();
            CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
                @Override
                public void run() {
                    ApplicationManager.getApplication().runWriteAction(runnable);
                }
            });
            if (oldStamp != editor.getDocument().getModificationStamp()) {
                String afterText = file.getText();
                if (Comparing.strEqual(beforeText, afterText)) {
                    LOG.error(LogMessageEx.createEvent("Import optimizer  hasn't optimized any imports",
                            file.getViewProvider().getVirtualFile().getPath(),
                            AttachmentFactory.createAttachment(file.getViewProvider().getVirtualFile())));
                }
            }
        }
    });
}

From source file:com.intellij.codeInsight.ExternalAnnotationsManagerImpl.java

License:Apache License

private void annotateExternally(@NotNull final VirtualFile root, @NotNull final PsiModifierListOwner listOwner,
        @NotNull final Project project, @NotNull final String packageName,
        @NotNull final String annotationFQName, @NotNull final PsiFile fromFile,
        @Nullable final PsiNameValuePair[] value) {
    List<XmlFile> xmlFiles = findExternalAnnotationsXmlFiles(listOwner);

    final XmlFile existingXml = findXmlFileInRoot(xmlFiles, root);
    if (existingXml != null && !FileModificationService.getInstance().preparePsiElementForWrite(existingXml)) {
        notifyAfterAnnotationChanging(listOwner, annotationFQName, false);
        return;/*  w w  w  .  ja  v  a2 s . com*/
    }

    final Set<PsiFile> annotationFiles = xmlFiles == null ? new THashSet<PsiFile>()
            : new THashSet<PsiFile>(xmlFiles);

    new WriteCommandAction(project) {
        @Override
        protected void run(final Result result) throws Throwable {
            if (existingXml != null) {
                annotateExternally(listOwner, annotationFQName, existingXml, fromFile, value);
            } else {
                XmlFile newXml = createAnnotationsXml(root, packageName);
                if (newXml == null) {
                    notifyAfterAnnotationChanging(listOwner, annotationFQName, false);
                } else {
                    annotationFiles.add(newXml);
                    cacheExternalAnnotations(packageName, fromFile, new SmartList<PsiFile>(annotationFiles));
                    annotateExternally(listOwner, annotationFQName, newXml, fromFile, value);
                }
            }

            UndoManager.getInstance(project).undoableActionPerformed(new BasicUndoableAction() {
                @Override
                public void undo() {
                    dropCache();
                    notifyChangedExternally();
                }

                @Override
                public void redo() {
                    dropCache();
                    notifyChangedExternally();
                }
            });
        }
    }.execute();
}

From source file:com.intellij.codeInsight.intention.impl.QuickEditHandler.java

License:Apache License

@Override
public void documentChanged(DocumentEvent e) {
    UndoManager undoManager = UndoManager.getInstance(myProject);
    boolean undoOrRedo = undoManager.isUndoInProgress() || undoManager.isRedoInProgress();
    if (undoOrRedo) {
        // allow undo/redo up until 'creation stamp' back in time
        // and check it after action is completed
        if (e.getDocument() == myOrigDocument) {
            //noinspection SSBasedInspection
            SwingUtilities.invokeLater(new Runnable() {
                @Override/*from   w w w  . j  a v  a 2s  .co m*/
                public void run() {
                    if (myOrigCreationStamp > myOrigDocument.getModificationStamp()) {
                        closeEditor();
                    }
                }
            });
        }
    } else if (e.getDocument() == myNewDocument) {
        commitToOriginal();
    } else if (e.getDocument() == myOrigDocument) {
        if (myCommittingToOriginal || myAltFullRange != null && myAltFullRange.isValid())
            return;
        closeEditor();
    }
}

From source file:com.intellij.codeInsight.template.impl.TemplateState.java

License:Apache License

public void start(@NotNull TemplateImpl template, @Nullable final PairProcessor<String, String> processor,
        @Nullable Map<String, String> predefinedVarValues) {
    LOG.assertTrue(!myStarted, "Already started");
    myStarted = true;//  w  w  w  .  j av a  2  s . c  o  m
    myTemplate = template;
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    myProcessor = processor;

    DocumentReference[] refs = myDocument == null ? null
            : new DocumentReference[] { DocumentReferenceManager.getInstance().create(myDocument) };
    UndoManager.getInstance(myProject).undoableActionPerformed(new BasicUndoableAction(refs) {
        @Override
        public void undo() {
            if (myDocument != null) {
                fireTemplateCancelled();
                LookupManager.getInstance(myProject).hideActiveLookup();
                int oldVar = myCurrentVariableNumber;
                setCurrentVariableNumber(-1);
                currentVariableChanged(oldVar);
            }
        }

        @Override
        public void redo() {
            //TODO:
            // throw new UnexpectedUndoException("Not implemented");
        }
    });
    myTemplateIndented = false;
    myCurrentVariableNumber = -1;
    mySegments = new TemplateSegments(myEditor);
    myPrevTemplate = myTemplate;

    //myArgument = argument;
    myPredefinedVariableValues = predefinedVarValues;

    if (template.isInline()) {
        int caretOffset = myEditor.getCaretModel().getOffset();
        myTemplateRange = myDocument.createRangeMarker(caretOffset,
                caretOffset + template.getTemplateText().length());
    } else {
        PsiFile file = getPsiFile();
        preprocessTemplate(file, myEditor.getCaretModel().getOffset(), myTemplate.getTemplateText());
        int caretOffset = myEditor.getCaretModel().getOffset();
        myTemplateRange = myDocument.createRangeMarker(caretOffset, caretOffset);
    }
    myTemplateRange.setGreedyToLeft(true);
    myTemplateRange.setGreedyToRight(true);

    processAllExpressions(template);
}

From source file:com.intellij.ide.actions.UndoRedoAction.java

License:Apache License

private static UndoManager getUndoManager(FileEditor editor, DataContext dataContext) {
    Project project = getProject(editor, dataContext);
    return project != null ? UndoManager.getInstance(project) : UndoManager.getGlobalInstance();
}

From source file:com.intellij.psi.formatter.FormatterTestCase.java

License:Open Source License

@Override
protected void tearDown() throws Exception {
    if (myFile != null) {
        ((UndoManagerImpl) UndoManager.getInstance(getProject()))
                .clearUndoRedoQueueInTests(myFile.getVirtualFile());
        FileEditorManager.getInstance(getProject()).closeFile(myFile.getVirtualFile());
    }/*  w  w w  . j av  a 2s.  co m*/
    myEditor = null;
    myFile = null;
    super.tearDown();
}