Running code formatting programmatically


I am currently building a plug-in which will, in response to some specific user actions and in specific circumstances, insert code snippets into an open source file (ie, the currently selected file in the open project). I am now at the point where things actually work, with one snag: I would like to format the inserted code snippet using the user's style/format (rather than "hardcode" a series of tabs etc in the template itself). 

Have been searching around for an example of how to to do this, but that has proven more elusive :-) than usual. Would appreciate any pointers on the matter - I can find references to FormattingModel etc, but at a complete loss on how to do something like 

- Acquire FormattingModel for current open file (ie, the one that I have just inserted the snippet into), I can't use a specific formatter even if I knew how because my plug-in will insert language-specific code snippets (ie, if you're using Java, a java code snippet will be inserted, if Kotlin, then a Kotlin one, etc), and the formatting rules might be language-dependent/specific

- Requesting the formatting operation to be performed

- Committing the changes to the open file

Any help/pointers gratefully received.

Comment actions Permalink

I have a program .Net  that generates Java source files from FreeMarker template
files. The generated files do not have optimal or consistent code
formatting in order to make the FreeMarker template files easier to read.
I would like the program to
format (ie pretty print) these generated files to improve their layout.
would need to be automated. At the moment the program has no dependencies
Eclipse libraries but I can add whatever dependencies I need.

I notice there is a class called CodeFormatter in the Eclipse API. How do
create or obtain an instance of this class in order to format the
java code? Also what dependencies would I need in order to use it? I don't
really want to pull in SWT dependencies etc as my program does not have a

Many thanks in advance for any help that you can offer.

Comment actions Permalink

Given the PsiFile, you can use:

ReformatCodeProcessor(psiFile, true).run()

Here, "true" means only process the text that has changed. Use "false" if you want to reformat the entire file.

Comment actions Permalink

Thanks a lot for that , as it set me on the right path. It's now working using the following code (I am reproducing the template insertion bit as well as it might be of use for other people):


WriteCommandAction.runWriteCommandAction(project, () ->
document.insertString(getEditor().getCaretModel().getPrimaryCaret().getOffset(), template);

new ReformatCodeProcessor(psiFile, false).run();

} );

Please note that without the commit, the changes never seem to actually make it, even if the commands run without problem. 

Thanks again, much appreciated. 



Please sign in to leave a comment.