Correctly indenting new line created with SmartEnterProcessor
I am writing a SmartEnterProcessor for a custom language plugin. My simple rule is to e.g. add a brackets on class declaration and move caret to position where user can write in insides of this class.
My code, when simplified, is like:
public class MySmartEnterProcessor extends SmartEnterProcessor {
@Override
public boolean process(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile psiFile) {
...
int offsetToJump = ...; // Calculates e.g. `class Foo<caret>` offset
editor.getDocument().insertString(offsetToJump, " {\n\n}\n"); // Inserts brackets
editor.getCaretModel().moveToOffset(offsetToJump + 3); // Jump inside of newly created block
reformat(psiElementForDeclaration); // Do we need this?
}}
As the result, I am getting not
class Foo {
|<caret at normal indentation>
}
but:
class Foo {
|<caret at normal indentation>
}
which is not awesome. With current formatter, after `Move Caret to Line End` action(`End` in default keymap or `Ctrl+E` in emacs keymap) idea inserts needed amount of indentation respecting current indentation level. But in this case, our formatter does not make an indentation, because the line where caret moved to is empty.
So the question is:
1)Is it a formatter work?
2)If not, how can I make idea insert a needed amount of indentation before caret in this case?
I have looked at JavaSmartEnter implementation, but it is not too obvious on where it happens.
Please sign in to leave a comment.
Ok, it seems it's better to use inheritance from SmartEnterProcessorWithFixers and add our custom fixers. In this case,
class Foo {being completed to
class Foo {|<caret>
}
works out of the box. It is still a question on how we can do such a transformation without preceding `{`.
Formatter cannot help directly in this case - there's no code on the empty line between braces, so there's no reason for it to introduce indent there. JavaSmartProcessor has complex logic, but in this case, in the end, it ends up calling plain Enter logic (JavaSmartProcessor.doEnter -> PlainEnterProcessor.doEnter), which inserts appropriate indent. You can do a similar thing in your processor, or just enter appropriate spacing directly, along with braces.
Thank you very much, Dmitry.
Indeed, simply using PlainEnterProcessor I was able to get a very nice results and that completely solves my question. Thanks again!