Indent methods hierarchically

Hi,

I'm trying to indent my methods hierarquically. For example, this code:

public void methodA() {
   methodB();
}


private void methodB() {
}

Has to be formmated to this (methodB indented one level):

public void myMethod() {
   methodB();
}




   private void methodB() {
   }



I'm using the code below and it is working fine for the first line of the method:

int line = editor.offsetToLogicalPosition(method.getTextOffset()).line;
LogicalPosition position = new LogicalPosition(line, 0);
editor.getCaretModel().moveToLogicalPosition(position);
EditorModificationUtil.insertStringAtCaret(editor, "\t\t", false, false);


I tried this for the rest of the lines but it didn't work:

int start = method.getTextRange().getStartOffset();
int end = method.getTextRange().getEndOffset();

for (int i = start; i < end; i++) {
   editor.getCaretModel().moveToOffset(i);
   EditorModificationUtil.insertStringAtCaret(editor, "\t\t", false, false);
}



Any ideas?

Thanks,
Andre
4 comments
Comment actions Permalink

Andre,
Your code tries to insert \t\t after every character of the method, not after every line.

Note that trying to fight against IntelliJ IDEA's formatter is generally a bad idea. It doesn't support hierarchical indentation, and while you can format the code in this way once, the formatting is likely to be destroyed by subsequent editing or refactoring operations performed by the user.

0
Comment actions Permalink

Hi Dmitry,

Thank you for your reply.

I understand that generally is not a good idea but this is only a proof of concept :-)

Is there a way to insert the code before each line of the method? could you please throw some light on that?

Thank you again,
Andre

0
Comment actions Permalink

Use Document.getLineStartOffset().

0
Comment actions Permalink

Thank you very much Dmitry, I will try it.

Andre

0

Please sign in to leave a comment.