## Using the code formatter

The JDT API allows other plug-ins to use the default code formatter to format source code. The two methods to consider are:

- ToolFactory.createCodeFormatter(Map)
- ToolFactory.createCodeFormatter(Map, int)

Note: The CodeFormatter class is not intended to be subclassed by clients.

### Getting a code formatter instance

The factory methods on ToolFactory can be invoked to create a new instance of the default code formatter. Before invoking one of those, you need to define a map that contains the code formatter options. In order to create such a map, you can use the methods defined in the class DefaultCodeFormatterConstants like DefaultCodeFormatterConstants.getEclipseDefaultSettings()

NOTE: These predefined maps contain only the code formatter specific options. In order to invoke the code formatter, you also need to specify what kind of source the code formatter will format. In order to do so, specify the three options:

- JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM
- JavaCore.COMPILER_SOURCE
- JavaCore.COMPILER_COMPLIANCE

The possible values of these options are given by the constants:

- JavaCore.VERSION_1_1
- JavaCore.VERSION_1_2
- JavaCore.VERSION_1_3
- JavaCore.VERSION_1_4
- JavaCore.VERSION_1_5
- JavaCore.VERSION_1_6
- JavaCore.VERSION_1_7

If you want to modify the default maps, it is recommended that you use the methods defined on DefaultCodeFormatterConstants to create the values of the corresponding options. This is especially true for the options relative to code wrapping.

### Invoking the code formatter

Use the newly created code formatter to format code snippets. The default code formatter allows you to format different kind of code snippets.
These kinds are specified in the documentation of the format method. The returned value of this method is a text edit. This text edit then needs to be applied to an IDocument instance in order to get the formatted result.

#### Example

    	// take default Eclipse formatting options
    	Map options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();

    	// initialize the compiler settings to be able to format 1.5 code
    	options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5);
    	options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_5);
    	options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5);

    	// change the option to wrap each enum constant on a new line
    	options.put(
    		DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS,
    		DefaultCodeFormatterConstants.createAlignmentValue(
    		true,
    		DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE,
    		DefaultCodeFormatterConstants.INDENT_ON_COLUMN));

    	// instantiate the default code formatter with the given options
    	final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);

    	// retrieve the source to format
    	String source = null;
    	try {
    		source = ...; // retrieve the source
    	} catch (IOException e) {
    		System.err.println("Could not retrieve the source"); //$NON-NLS-1$
    		e.printStackTrace();
    		return;
    	}
    	final TextEdit edit = codeFormatter.format(
    		CodeFormatter.K_COMPILATION_UNIT, // format a compilation unit
    		source, // source to format
    		0, // starting position
    		source.length(), // length
    		0, // initial indentation
    		System.getProperty("line.separator") // line separator
    	);

    	IDocument document = new Document(source);
    	try {
    		edit.apply(document);
    	} catch (MalformedTreeException e) {
    		e.printStackTrace();
    	} catch (BadLocationException e) {
    		e.printStackTrace();
    	}

    	// display the formatted string on the System out
    	System.out.println(document.get());

On this example,

    public enum X { A,B,C,D,E,F}

the result would be:

    public enum X {
    	A,
    	B,
    	C,
    	D,
    	E,
    	F
    }

### Formatting a set of regions

The default code formatter allows to format a set of regions of a given source file.
This can be achieved by calling the format(int, String, IRegion[], int, String) method of the code formatter, with a given source kind and an array of regions.

- Each of the region to format must be within source range and should not overlap with another region.
- The array of regions to format must contain at least one region. Regions should be sorted by their offsets, smaller offset first.

### Comment Formatter API

The default code formatter API offers the possibility to format comments during the processing of the code snippet.
This can be achieved by combining the appropriate flag F_INCLUDE_COMMENTS with K_COMPILATION_UNIT and K_UNKNOWN flags.
This flag is effective only if the corresponding formatting option was enabled when calling format(int, String, int, int, int, String) or format(int, String, IRegion[], int, String) methods:

- FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT which controls the formatting of javadoc comments
- FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT which controls the formatting of multiple lines comments
- FORMATTER_COMMENT_FORMAT_LINE_COMMENT which controls the formatting of single line comments

### Comment formatter options

Various formatting options are available in order to format comments:

- General options to enable or disable the formatting of specific comments (javadoc, multi or single line comments), set maximum line width for comments.
- javadoc comments options to enable the formatting of code snippets or HTML sections inside javadoc comments, indent tag descriptions, etc.
- block comments option to keep or remove blanks lines within such comment

For detailed information about these settings, refer to the DefaultCodeFormatterConstants

### Formatting comments with the stand-alone formatter

The default code formatter can be used to format comments (javadoc, multi or single line). In this case, the source passed to the format method should only contain a specific kind of comments, and corresponding kind K_JAVA_DOC, K_MULTI_LINE_COMMENT or K_SINGLE_LINE_COMMENT should be used.

- #### Formatting javadoc comments

  The following unformatted javadoc:

        /**
       * This is just a simple example to show how javadoc comments can     be formatted .
       * @param str The input string
         * @return      The resulting   string
         */

  should be formatted as follows:

      /**
       * This is just a simple example to show how javadoc comments can be formatted .
       *
       * @param str
       *            The input string
       * @return The resulting string
       */

  using command:

      	(...)
      	final TextEdit edit = codeFormatter.format(
      		CodeFormatter.K_JAVA_DOC, // specify the kind: javadoc
      		source, // source to format (as per the above example)
      		0, // starting position
      		source.length(), // length
      		0, // initial indentation
      		System.getProperty("line.separator") // line separator
      	);
      	(...)

- #### Formatting multi-line comments

  The following unformatted multi-line comment:

      /*
        * This is just an example of multi- line comment intended to demonstrate the default code formatter ability to format multi-line comments .
        *
        *   These possibilities include: Formatting of javadoc     comments,
        *     formatting of multi-line comments
       */

  should be formatted as follows:

      /*
       * This is just an example of multi- line comment intended to demonstrate
       * the default code formatter ability to format multi-line comments .
       *
       * These possibilities include: Formatting of javadoc comments, formatting
       * of multi-line comments
       */

  using command:

      	(...)
      	final TextEdit edit = codeFormatter.format(
      		CodeFormatter.K_MULTI_LINE_COMMENT, // specify the kind: multi-line comments
      		source, // source to format (as per the above example)
      		0, // starting position
      		source.length(), // length
      		0, // initial indentation
      		System.getProperty("line.separator") // line separator
      	);
      	(...)

- #### Formatting single line comments

  The following unformatted single line comments:

      // This is a long comment that should be split in multiple line comments in case the line comment formatting is enabled

  should be formatted as follows:

      // This is a long comment that should be split in multiple line comments in
      // case the line comment formatting is enabled

  using command:

      	(...)
      	final TextEdit edit = codeFormatter.format(
      		CodeFormatter.K_SINGLE_LINE_COMMENT,  // specify the kind: single-line comments
      		source, // source to format (as per the above example)
      		0, // starting position
      		source.length(), // length
      		0, // initial indentation
      		System.getProperty("line.separator") // line separator
      	);
      	(...)