List of usage examples for org.eclipse.jdt.internal.formatter DefaultCodeFormatter DefaultCodeFormatter
public DefaultCodeFormatter(Map<String, String> options)
From source file:com.google.googlejavaformat.java.EclipseJavadocFormatter.java
License:Apache License
private static String formatJavadocInternal(String input, int indent, JavaFormatterOptions options) { ImmutableMap.Builder<String, String> optionBuilder = ImmutableMap.<String, String>builder(); optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT, "true"); optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, Integer.toString(options.indentationMultiplier())); optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, Integer.toString(options.maxLineLength() - indent)); optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, Integer.toString(options.maxLineLength())); optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_PARAMETER_DESCRIPTION, DefaultCodeFormatterConstants.FALSE); optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INSERT_NEW_LINE_FOR_PARAMETER, JavaCore.DO_NOT_INSERT);//from w w w . ja va2s.co m optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_JAVADOC_COMMENT, DefaultCodeFormatterConstants.FALSE); optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_JOIN_LINES_IN_COMMENTS, DefaultCodeFormatterConstants.TRUE); optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_JOIN_WRAPPED_LINES, DefaultCodeFormatterConstants.TRUE); // Disable indenting root tags for now since it indents more than 4 spaces optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_ROOT_TAGS, DefaultCodeFormatterConstants.FALSE); optionBuilder.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_SOURCE, DefaultCodeFormatterConstants.FALSE); optionBuilder.put(JavaCore.COMPILER_COMPLIANCE, "1.8"); optionBuilder.put(JavaCore.COMPILER_SOURCE, "1.8"); optionBuilder.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.8"); DefaultCodeFormatter codeFormatter = new DefaultCodeFormatter( new DefaultCodeFormatterOptions(optionBuilder.build())); TextEdit edit = codeFormatter.format(CodeFormatter.K_JAVA_DOC, input, /*offset*/ 0, input.length(), // eclipse doesn't indent comments reliably, so always request no indent and fix it // up later in JavaCommentsHelper /*indent*/ 0, /*lineSeparator*/ null); if (edit == null) { throw new RuntimeException("error formatting javadoc"); } Document document = new Document(input); try { edit.apply(document); } catch (BadLocationException e) { throw new RuntimeException("error formatting javadoc", e); } return document.get(); }
From source file:com.google.gwt.eclipse.core.editors.java.JsniAutoEditStrategy.java
License:Open Source License
private String getIndentToken() { return new DefaultCodeFormatter((Map<String, String>) prefs).createIndentationString(1); }
From source file:com.google.gwt.eclipse.core.editors.java.JsniFormattingUtil.java
License:Open Source License
public static TextEdit format(IDocument document, TypedPosition partition, Map<String, String> javaFormattingPrefs, Map<String, String> javaScriptFormattingPrefs, String original) {//from w w w . ja v a 2 s . c om try { // Extract the JSNI block out of the document int offset = partition.getOffset(); int length = partition.getLength(); // Determine the line delimiter, indent string, and tab/indent widths String lineDelimiter = TextUtilities.getDefaultLineDelimiter(document); int tabWidth = IndentManipulation.getTabWidth(javaFormattingPrefs); int indentWidth = IndentManipulation.getIndentWidth(javaFormattingPrefs); // Get indentation level of the first line of the JSNI block (this should // be the line containing the JSNI method declaration) int methodDeclarationOffset = getMethodDeclarationOffset(document, offset); int jsniLine1 = document.getLineOfOffset(methodDeclarationOffset); int methodIndentLevel = getLineIndentLevel(document, jsniLine1, tabWidth, indentWidth); DefaultCodeFormatter defaultCodeFormatter = new DefaultCodeFormatter(javaFormattingPrefs); String indentLine = defaultCodeFormatter.createIndentationString(methodIndentLevel); // Extract the JSNI body out of the block and split it up by line String jsniSource = document.get(offset, length); String body = JsniParser.extractMethodBody(jsniSource); String formattedJs; // JSNI Java references mess up the JS formatter, so replace them // with place holder values JsniJavaRefReplacementResult replacementResults = replaceJsniJavaRefs(body); body = replacementResults.getJsni(); TextEdit formatEdit = CodeFormatterUtil.format2(CodeFormatter.K_STATEMENTS, body, methodIndentLevel + 1, lineDelimiter, javaScriptFormattingPrefs); if (formatEdit != null) { body = restoreJsniJavaRefs(replacementResults); Document d = new Document(body); formatEdit.apply(d); formattedJs = d.get(); if (!formattedJs.startsWith(lineDelimiter)) { formattedJs = lineDelimiter + formattedJs; } if (!formattedJs.endsWith(lineDelimiter)) { formattedJs = formattedJs + lineDelimiter; } formattedJs = formattedJs + indentLine; formattedJs = "/*-{" + formattedJs + "}-*/"; } else { if (original == null) { return null; } formattedJs = original; // formatting failed, use the original string } return new ReplaceEdit(offset, length, formattedJs); } catch (Exception e) { GWTPluginLog.logError(e); return null; } }
From source file:krasa.formatter.JsniFormattingUtil.java
License:Open Source License
public static TextEdit format(IDocument document, TypedPosition partition, Map<String, String> javaFormattingPrefs, Map<String, String> javaScriptFormattingPrefs, String original) {// w w w . ja v a 2 s. c o m try { // Extract the JSNI block out of the document int offset = partition.getOffset(); int length = partition.getLength(); // Determine the line delimiter, indent string, and tab/indent widths String lineDelimiter = Settings.LINE_SEPARATOR; int tabWidth = IndentManipulation.getTabWidth(javaFormattingPrefs); int indentWidth = IndentManipulation.getIndentWidth(javaFormattingPrefs); // Get indentation level of the first line of the JSNI block (this should // be the line containing the JSNI method declaration) int methodDeclarationOffset = getMethodDeclarationOffset(document, offset); int jsniLine1 = document.getLineOfOffset(methodDeclarationOffset); int methodIndentLevel = getLineIndentLevel(document, jsniLine1, tabWidth, indentWidth); DefaultCodeFormatter defaultCodeFormatter = new DefaultCodeFormatter(javaFormattingPrefs); String indentLine = defaultCodeFormatter.createIndentationString(methodIndentLevel); // Extract the JSNI body out of the block and split it up by line String jsniSource = document.get(offset, length); String body = JsniParser.extractMethodBody(jsniSource); String formattedJs; // JSNI Java references mess up the JS formatter, so replace them // with place holder values JsniJavaRefReplacementResult replacementResults = replaceJsniJavaRefs(body); body = replacementResults.getJsni(); CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(javaScriptFormattingPrefs); TextEdit formatEdit = codeFormatter.format(CodeFormatter.K_STATEMENTS, body, 0, body.length(), methodIndentLevel + 1, lineDelimiter); if (formatEdit != null) { body = restoreJsniJavaRefs(replacementResults); Document d = new Document(body); formatEdit.apply(d); formattedJs = d.get(); if (!formattedJs.startsWith(lineDelimiter)) { formattedJs = lineDelimiter + formattedJs; } if (!formattedJs.endsWith(lineDelimiter)) { formattedJs = formattedJs + lineDelimiter; } formattedJs = formattedJs + indentLine; formattedJs = "/*-{" + formattedJs + "}-*/"; } else { if (original == null) { return null; } formattedJs = original; // formatting failed, use the original string } return new ReplaceEdit(offset, length, formattedJs); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:net.sf.fast.ibatis.build.AbstractCodeBuilder.java
License:Apache License
@SuppressWarnings("unchecked") private String generateCode(ICompilationUnit cu, FastIbatisConfig fc) { if (cu == null || Utils.isMethodExist(cu, fc.getMethodName())) return null; ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(cu);//from w w w . j a va 2 s .co m // parser.setResolveBindings(false); CompilationUnit astRoot = (CompilationUnit) parser.createAST(null); AST ast = astRoot.getAST();// AST.newAST(AST.JLS3); TypeDeclaration type = ((TypeDeclaration) astRoot.types().get(0)); MethodDeclaration methodDeclaration = createMethodDeclaration(ast, type, fc); if (type.isInterface()) { } else { Block block = createBlock(ast, fc); methodDeclaration.setBody(block); } Javadoc jc = Utils.getJavadoc(ast, fc.getMethodComment()); if (jc != null) methodDeclaration.setJavadoc(jc); type.bodyDeclarations().add(methodDeclaration); String str = astRoot.toString(); IDocument document = new SimpleDocument(str); //writeContent(fileName,newSource); Map options = cu.getJavaProject().getOptions(true); CodeFormatter formatter = new DefaultCodeFormatter(options); int indentationLevel = 0;//StringUtils.inferIndentationLevel(" ", getTabSize()); TextEdit textEdit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, str, 0, str.length(), indentationLevel, "\n"); try { textEdit.apply(document, TextEdit.NONE); String result = document.get(); return result; } catch (Exception e) { } return null; }
From source file:org.eclim.plugin.jdt.command.format.FormatCommand.java
License:Open Source License
/** * {@inheritDoc}// w w w. j av a 2 s .c om * @see org.eclim.command.Command#execute(CommandLine) */ public String execute(CommandLine commandLine) throws Exception { String project = commandLine.getValue(Options.PROJECT_OPTION); String file = commandLine.getValue(Options.FILE_OPTION); int bByteOffset = commandLine.getIntValue(Options.BOFFSET_OPTION); int eByteOffset = commandLine.getIntValue(Options.EOFFSET_OPTION); ICompilationUnit src = JavaUtils.getCompilationUnit(project, file); IJavaProject myProject = JavaUtils.getJavaProject(project); DefaultCodeFormatter formatter = new DefaultCodeFormatter(myProject.getOptions(false)); int kind = CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS; String source = src.getBuffer().getContents(); String vimEncoding = "UTF-8"; byte[] byteSource = source.getBytes(vimEncoding); ByteArrayOutputStream outStream = null; outStream = new ByteArrayOutputStream(); outStream.write(byteSource, 0, bByteOffset); String sourcePrefix = outStream.toString(vimEncoding); outStream = new ByteArrayOutputStream(); outStream.write(byteSource, bByteOffset, eByteOffset - bByteOffset); String sourceRoot = outStream.toString(vimEncoding); int bCharOffset = sourcePrefix.length(); int eCharOffset = bCharOffset + sourceRoot.length(); int charLength = eCharOffset - bCharOffset; String lineDelimiter = StubUtility.getLineDelimiterUsed(src); TextEdit edits = formatter.format(kind, source, bCharOffset, charLength, 0, lineDelimiter); if (edits == null) { return "no edits returned on attempt to format the source."; } Document document = new Document(src.getBuffer().getContents()); edits.apply(document); src.getBuffer().setContents(document.get()); src.save(null, false); return StringUtils.EMPTY; }
From source file:org.eclim.plugin.jdt.util.JavaUtils.java
License:Open Source License
/** * Format a region in the supplied source file. * * @param src The ICompilationUnit./*from www . j a v a 2s. c om*/ * @param kind The kind of code snippet to format. * @param offset The starting offset of the region to format. * @param length The length of the region to format. */ public static void format(ICompilationUnit src, int kind, int offset, int length) throws Exception { IBuffer buffer = src.getBuffer(); String contents = buffer.getContents(); String delimiter = StubUtility.getLineDelimiterUsed(src); DefaultCodeFormatter formatter = new DefaultCodeFormatter(src.getJavaProject().getOptions(true)); // when the eclipse indent settings differ from vim (tabs vs spaces) then // the inserted method's indent may be a bit off. this is a workaround to // force reformatting of the code from the start of the line to the start of // the next set of code following the new method. Doesn't quite fix indent // formatting of methods in nested classes. while (offset > 0 && !IndentManipulation.isLineDelimiterChar(buffer.getChar(offset - 1))) { offset--; length++; } while ((offset + length) < contents.length() && IndentManipulation.isLineDelimiterChar(buffer.getChar(offset + length))) { length++; } TextEdit edits = formatter.format(kind, contents, offset, length, 0, delimiter); if (edits != null) { int oldLength = contents.length(); Document document = new Document(contents); edits.apply(document); String formatted = document.get(); // jdt formatter can introduce trailing whitespace (javadoc comments), so // we'll remove all trailing whitespace from the formatted section (unless // the user has configured eclim not to do so). length += formatted.length() - oldLength; if (offset < (offset + length)) { String stripTrailingWhitespace = Preferences.getInstance().getValue( src.getJavaProject().getProject(), "org.eclim.java.format.strip_trialing_whitespace"); if ("true".equals(stripTrailingWhitespace)) { String pre = formatted.substring(0, offset); StringBuffer section = new StringBuffer(formatted.substring(offset, offset + length)); StringBuffer post = new StringBuffer(formatted.substring(offset + length)); // account for section not ending at a line delimiter while (!section.toString().endsWith(delimiter) && post.length() > 0) { section.append(post.charAt(0)); post.deleteCharAt(0); } Matcher matcher = TRAILING_WHITESPACE.matcher(section); String stripped = matcher.replaceAll(StringUtils.EMPTY); src.getBuffer().setContents(pre + stripped + post); } else { src.getBuffer().setContents(formatted); } } else { src.getBuffer().setContents(formatted); } if (src.isWorkingCopy()) { src.commitWorkingCopy(true, null); } src.save(null, false); } }
From source file:org.eclipse.che.jdt.core.ToolFactory.java
License:Open Source License
/** * Create an instance of the built-in code formatter. * <p>The given options should at least provide the source level ({@link org.eclipse.jdt.core.JavaCore#COMPILER_SOURCE}), * the compiler compliance level ({@link org.eclipse.jdt.core.JavaCore#COMPILER_COMPLIANCE}) and the target platform * ({@link org.eclipse.jdt.core.JavaCore#COMPILER_CODEGEN_TARGET_PLATFORM}). * Without these options, it is not possible for the code formatter to know what kind of source it needs to format. * </p>/* w ww .j a va 2 s .c o m*/ * <p>The given mode determines what options should be enabled when formatting the code. It can have the following * values: {@link #M_FORMAT_NEW}, {@link #M_FORMAT_EXISTING}, but other values may be added in the future. * </p> * * @param options the options map to use for formatting with the default code formatter. Recognized options * are documented on <code>JavaCore#getDefaultOptions()</code>. If set to <code>null</code>, then use * the current settings from <code>JavaCore#getOptions</code>. * @param mode the given mode to modify the given options. * * @return an instance of the built-in code formatter * @see org.eclipse.jdt.core.formatter.CodeFormatter * @see org.eclipse.jdt.core.JavaCore#getOptions() * @since 3.3 */ public static CodeFormatter createCodeFormatter(Map options, int mode) { if (options == null) options = org.eclipse.jdt.core.JavaCore.getOptions(); Map currentOptions = new HashMap(options); if (mode == M_FORMAT_NEW) { // disable the option for not formatting comments starting on first column currentOptions.put( DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT_STARTING_ON_FIRST_COLUMN, DefaultCodeFormatterConstants.TRUE); // disable the option for not indenting comments starting on first column currentOptions.put(DefaultCodeFormatterConstants.FORMATTER_NEVER_INDENT_BLOCK_COMMENTS_ON_FIRST_COLUMN, DefaultCodeFormatterConstants.FALSE); currentOptions.put(DefaultCodeFormatterConstants.FORMATTER_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN, DefaultCodeFormatterConstants.FALSE); } return new DefaultCodeFormatter(currentOptions); }