我正在开发IntelliJ Idea 13的插件。我在beforeDocumentSaving
进行了一些更改,并使用了document.setText
:
public class AppendAction implements ApplicationComponent
{
@Override public void initComponent()
{
MessageBus bus = ApplicationManager.getApplication().getMessageBus();
MessageBusConnection connection = bus.connect();
connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerAdapter()
{
@Override public void beforeDocumentSaving(Document document)
{
document.setText(appendSomething(document.getText()));
}
});
}
}
这很好用,我唯一的问题是当这个插件运行时,我想撤消更改时,我会看到以下错误消息:
Cannot Undo
Following files have changes that cannot be undone:
任何Idea
? : - )
答案 0 :(得分:4)
答案是将document.setText
包裹到ApplicationManager.getApplication().runWriteAction
和CommandProcessor.getInstance().runUndoTransparentAction
中。
我在githib上的intellij-community源代码中找到了一个示例TrailingSpacesStripper: https://github.com/JetBrains/intellij-community/blob/master/platform/platform-impl/src/com/intellij/openapi/editor/impl/TrailingSpacesStripper.java
public class AppendAction implements ApplicationComponent
{
@Override public void initComponent()
{
MessageBus bus = ApplicationManager.getApplication().getMessageBus();
MessageBusConnection connection = bus.connect();
connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerAdapter()
{
@Override public void beforeDocumentSaving(final Document document)
{
ApplicationManager.getApplication().runWriteAction(new DocumentRunnable(document, null)
{
@Override public void run()
{
CommandProcessor.getInstance().runUndoTransparentAction(new Runnable()
{
@Override public void run()
{
document.setText(appendSomething(document.getText()));
}
});
}
});
}
});
}
}
答案 1 :(得分:2)
您应该通过CommandProcessor API包装更改。
来自IntelliJ IDEA Architectural Overview:
任何修改文档内容的操作都必须包含在命令
(CommandProcessor.getInstance().executeCommand())
中。 executeCommand()调用可以嵌套,最外面的executeCommand调用添加到撤消堆栈。如果在命令中修改了多个文档,则撤消此命令将默认向用户显示确认对话框。