How to safely replace text in the editor? replaceString or CommandProcessor?

Hi Guys,

Apologies for being the newbie on the block, I've just started wrestling with the
OpenAPI for my spell check plugin; my first attempt used:

document.replaceString(offset + start, offset + end, event.getReplaceWord());

To replace the misspelt word in the editor, but I noticed it IDEA was throwing
all kinds of asserts behind the scences.. so after digging around some plugin
sources I came up with this alternative procedure to do the same:

CommandProcessor.getInstance().executeCommand(new MyCommand(editor, offset+start,
event.getReplaceWord()), null, null);

private class MyCommand implements Runnable {
Editor editor;
String replacementText;
int offset;

public MyCommand(Editor editor, int offset, String replacementText) {
this.editor = editor;
this.offset = offset;
this.replacementText = replacementText;
}

public void run() {
ApplicationManager.getApplication().runWriteAction(new MyWriteAction());
}

private class MyWriteAction implements Runnable {
public void run() {
CaretModel caretModel = editor.getCaretModel();
if (caretModel != null) {
caretModel.moveToOffset(offset);
EditorModificationUtil.deleteSelectedText(editor);
EditorModificationUtil.insertStringAtCaret(editor,
replacementText, true, false);
}
}
}
}

I'm not feeling comfortable with the latter, the Runnable interfaces make
me feel these are happening asychronously; which isn't desirable for the
intercative, select -> replace, select _> replace operation of the plugin..
Do I have to use the executeCommand / writeAction model or are the
document.replaceString(), insertString()... methods safe to use?
(they actually seemed to work fine) and the associated asserts were
caused by some other detail (caret position / selection?).

Anyone offer any advice? I'm targetting IDEA 3.0 BTW.

Thanks,

Richard

2 comments
Comment actions Permalink

If you extend EditorAction, you don't need to wrap your document edits with CommandProcessor.getInstance().executeCommand(new MyCommand());

0
Comment actions Permalink

Another way (as Alex said) is to extend EditorAction and supply an EditorWriteActionHandler instance in the constructor (if it's a write action). It will do the same thing for you.

All write actions must go through application.runWriteAction(). See the javadoc for the method.

If you change a document (insertString(), etc) you have to use a write action, otherwise you can use a read action.


Timur

0

Please sign in to leave a comment.