Insert String into Editor from within a ToolWindow

Hi all,

How can I insert a string into the editor from within a ToolWindow?
I played a lot with code snippets I found on the web, but none worked.

Does anyone has a simple example for me?

Thanks in advance!

0

Into which editor? Also, what exactly did you try and what doesn't work? In general, an editor doesn't care whether the code that's inserting text into it was invoked from a toolwindow or from some other part of the UI.

You may find this document useful: http://confluence.jetbrains.com/display/IDEADEV/IntelliJ+IDEA+Architectural+Overview

0
Avatar
Permanently deleted user

Hi Dmitry,

yeah I have read  http://confluence.jetbrains.com/display/IDEADEV/IntelliJ+IDEA+Architectural+Overview. But I am quite new to Swing and GUI development and I perhaps understand 50% of the documentation.

I want to insert the String into the current Editor at the current cursor position.

The only code that nearly works and I still have is the following:

FileEditorManager manager = FileEditorManager.getInstance(project);
final Editor editor = manager.getSelectedTextEditor();
assert editor != null;
final int cursorOffset = editor.getCaretModel().getOffset();
final Document document = editor.getDocument();

ApplicationManager.getApplication().runWriteAction(new Runnable() {
     @Override
     public void run() {
          document.insertString(cursorOffset, snippetCode);
     }
});


But if this code is executed I get the follwing error:

 [  17297]  ERROR - llij.ide.plugins.PluginManager - Must not change document outside command or undo-transparent action. See com.intellij.openapi.command.WriteCommandAction or com.intellij.openapi.command.CommandProcessor 
com.intellij.util.IncorrectOperationException: Must not change document outside command or undo-transparent action. See com.intellij.openapi.command.WriteCommandAction or com.intellij.openapi.command.CommandProcessor
...
0

Please try reading the error message produced by this operation and following the instructions contained in it.

0
Avatar
Permanently deleted user

I got it now:

FileEditorManager manager = FileEditorManager.getInstance(project);
final Editor editor = manager.getSelectedTextEditor();
assert editor != null;
final int cursorOffset = editor.getCaretModel().getOffset();
final Document document = editor.getDocument();

new WriteCommandAction(project){
     @Override
     protected void run(@NotNull Result result) throws Throwable {
          document.insertString(cursorOffset, snippetCode);
     }
}.execute();
0

请先登录再写评论。