Moving the caret after replacing a PsiElement
To start getting my head around plugins, I created an intention that fires when pressing alt-enter on an if or a right curly brace that belongs to an if. It will suggest adding an else to this if. I got everything working, except for one thing: I can't get the caret in the right position. Here's the sourcecode for the invoke method of the intention:
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement psiElement) throws IncorrectOperationException {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
@NonNls String text = "if( a ){\n}else{\n\n}";
PsiIfStatement newIfStatement = (PsiIfStatement) factory.createStatementFromText(text, psiElement);
PsiIfStatement ifStatement = PsiTreeUtil.getParentOfType(psiElement, PsiIfStatement.class);
newIfStatement.getCondition().replace(ifStatement.getCondition().copy());
newIfStatement.getThenBranch().replace(ifStatement.getThenBranch().copy());
newIfStatement = (PsiIfStatement) codeStyleManager.reformat(newIfStatement);
ifStatement.replace(newIfStatement);
editor.getCaretModel().moveToOffset(???);
}
I want the caret on the position shown in the next example:
if ( a ) {
//existing then-branch here
}
else {
| <--caret here
}
So far when playing around with get*Offset methods, they are all relative, and the caret gets moved around the top of the editor. How do I get the caret inside the else block?
请先登录再写评论。
For future readers: I know what I did wrong:the method replace() returns the newly replaced/inserted PsiElement which has the new positions. You have to use the getTextOffset() from that one.
Hi Warner,
In case you want to move the caret to right indent, i.e. if you want to have code like below
instead of this one
you can use CodeStyleManager.adjustLineIndent() for that.
Denis
Thanks for the additional comment. It now works perfectly! :) Keep those tips incoming, it's highly appreciated!!