I am using org.eclipse.wst.jsdt.feature
plugin.
The usage of formatting JavaScript code programmatically is the same as the way to do with Java code.
as following:
Map<?, ?> setting = DefaultCodeFormatterConstants.getEclipseDefaultSettings();
CodeFormatter formatter = ToolFactory.createCodeFormatter(setting);
TextEdit edit = formatter.format(CodeFormatter.K_JAVASCRIPT_UNIT, js,
0, js.length(), 0, StringUtil.NEW_LINE);
if (edit == null)
return js;
IDocument doc = new Document(js);
try {
edit.apply(doc);
} catch (Exception e) {
e.printStackTrace();
return js;
}
return doc.get();
The thing you need mention is, you need import following package from org.eclipse.wst.jsdt
.
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.wst.jsdt.core.ToolFactory;
import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;