How to format selected java code in sublime text .txt file

codejavasublime-text-2

Is there any extension or technique for formatting java code in sublime text?

For example,

I have this code:

    static void test() 
{
        Pair<Integer, Integer>[] intPairArr = new Pair<Integer, Integer>[10]; // error
         addElements(intPairArr);
        Pair<Integer, Integer> pair = intPairArr[1];
           Integer i = pair.getFirst();
        pair.setSecond(i);
        }

I want this formatted code:

static void test() {
    Pair<Integer, Integer>[] intPairArr = new Pair<Integer, Integer>[10]; // error
    addElements(intPairArr);
    Pair<Integer, Integer> pair = intPairArr[1];
    Integer i = pair.getFirst();
    pair.setSecond(i);
}

I don't want to use an IDE for formatting code in a sublime text .txt file. Basically I want to select a snippet Java code in .txt file and format it properly.

  1. I tried CodeFormatter plugin for Sublime Text.I get the following
    error:

    Formatter for this type(plain text) not found
    
  2. I tried Edit > Line > Reindent but this technique is waste of time.

  3. I tried Sublime​AStyle​Formatter plugin for Sublime
    Text, as well.When I select my code and press Ctrl+K
    for formatting my current selection, it doesn't work.

How can I format selected java code in a sublime text .txt file?

Best Answer

I'd suggest that you use CoolFormatter. According to the description, it is:

A Sublime Text plugin for Source Code Formatter. CoolFormat Source Code Formatter is a code formatter for C\C++\C#\CSS \HTML\Java\JavaScript\JSON\Objective-C\PHP\SQL\XML files.

I think your code is in Java, so this would work

The keybindings are:

  • Format entire file: Ctrl+Shift+Alt+Q
  • Format selected text: Ctrl+Shift+Alt+s
Related Question