我正在使用JDT自动缩进我的代码。这缩进了Java代码,但它没有缩进JSP代码......当我尝试用JDT缩进JSP代码时,我得到NullPointerException。
请建议使用JAVA CODE缩进JSP文件。
以下代码用于缩进:
import java.util.Map;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
public class Indenter {
CodeFormatter codeFormatter;
public Indenter() {
// take default Eclipse formatting options
Map<String, String> options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();
// initialize the compiler settings to be able to format 1.5 code
options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7);
options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);
// 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
codeFormatter = ToolFactory.createCodeFormatter(options);
}
public String indent(String source, String language){
if("JAVA".equalsIgnoreCase(language)){
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);
return document.get();
} catch (BadLocationException | MalformedTreeException e) {
e.printStackTrace();
}
}
return source;
}
}