org.eclipse.jdt.core.formatter.CodeFormatter Java Examples

The following examples show how to use org.eclipse.jdt.core.formatter.CodeFormatter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavaMethodCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Appends everything up to the method name including
 * the opening parenthesis.
 * <p>
 * In case of {@link CompletionProposal#METHOD_REF_WITH_CASTED_RECEIVER}
 * it add cast.
 * </p>
 *
 * @param buffer the string buffer
 * @since 3.4
 */
protected void appendMethodNameReplacement(StringBuffer buffer) {
	if (fProposal.getKind() == CompletionProposal.METHOD_REF_WITH_CASTED_RECEIVER) {
		String coreCompletion= String.valueOf(fProposal.getCompletion());
		String lineDelimiter= TextUtilities.getDefaultLineDelimiter(getTextViewer().getDocument());
		String replacement= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, coreCompletion, 0, lineDelimiter, fInvocationContext.getProject());
		buffer.append(replacement.substring(0, replacement.lastIndexOf('.') + 1));
	}

	if (fProposal.getKind() != CompletionProposal.CONSTRUCTOR_INVOCATION)
		buffer.append(fProposal.getName());

	FormatterPrefs prefs= getFormatterPrefs();
	if (prefs.beforeOpeningParen)
		buffer.append(SPACE);
	buffer.append(LPAREN);
}
 
Example #2
Source File: Util.java    From jbt with Apache License 2.0 6 votes vote down vote up
/**
 * This method formats a source code file (its content is in
 * <code>sourceCode</code>) according to the Eclipse SDK defaults formatting
 * settings, and returns the formatted code.
 * <p>
 * Note that the input source code must be syntactically correct according
 * to the Java 1.7 version. Otherwise, an exception is thrown.
 * 
 * @param sourceCode
 *            the source code to format.
 * @return the formatted source code.
 */
public static String format(String sourceCode) {
	try {
		TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT
				| CodeFormatter.F_INCLUDE_COMMENTS, sourceCode, 0, sourceCode.length(), 0,
				System.getProperty("line.separator"));

		IDocument document = new Document(sourceCode);

		edit.apply(document);

		return document.get();
	} catch (Exception e) {
		throw new RuntimeException("The input source code is not sintactically correct:\n\n" + sourceCode);
	}
}
 
Example #3
Source File: ASTRewriteFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public String[] getPrefixAndSuffix(int indent, ASTNode node, RewriteEventStore events) {
	String nodeString= ASTRewriteFlattener.asString(node, events);
	int nodeStart= this.prefix.length();
	int nodeEnd= nodeStart + nodeString.length() - 1;

	String str= this.prefix + nodeString + this.suffix;

	Position pos1= new Position(this.start, nodeStart + 1 - this.start);
	Position pos2= new Position(nodeEnd, 2);

	TextEdit res= formatString(CodeFormatter.K_STATEMENTS, str, 0, str.length(), indent);
	if (res != null) {
		str= evaluateFormatterEdit(str, res, new Position[] { pos1, pos2 });
	}
	return new String[] {
		str.substring(pos1.offset + 1, pos1.offset + pos1.length - 1),
		str.substring(pos2.offset + 1, pos2.offset + pos2.length - 1)
	};
}
 
Example #4
Source File: Scribe.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void printNextToken(int[] expectedTokenTypes, boolean considerSpaceIfAny){
	printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT);
	try {
		this.currentToken = this.scanner.getNextToken();
		if (Arrays.binarySearch(expectedTokenTypes, this.currentToken) < 0) {
			StringBuffer expectations = new StringBuffer(5);
			for (int i = 0; i < expectedTokenTypes.length; i++){
				if (i > 0) {
					expectations.append(',');
				}
				expectations.append(expectedTokenTypes[i]);
			}
			throw new AbortFormatting("unexpected token type, expecting:["+expectations.toString()+"], actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$
		}
		print(this.scanner.currentPosition - this.scanner.startPosition, considerSpaceIfAny);
	} catch (InvalidInputException e) {
		throw new AbortFormatting(e);
	}
}
 
Example #5
Source File: CompletionProposalCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the Java completion proposal for the JDT Core
 * {@link CompletionProposal#FIELD_REF_WITH_CASTED_RECEIVER} proposal.
 *
 * @param proposal the JDT Core proposal
 * @return the Java completion proposal
 * @since 3.4
 */
private IJavaCompletionProposal createFieldWithCastedReceiverProposal(CompletionProposal proposal) {
	String completion= String.valueOf(proposal.getCompletion());
	completion= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, completion, 0, "\n", fJavaProject); //$NON-NLS-1$
	int start= proposal.getReplaceStart();
	int length= getLength(proposal);
	StyledString label= fLabelProvider.createStyledLabel(proposal);
	Image image= getImage(fLabelProvider.createFieldImageDescriptor(proposal));
	int relevance= computeRelevance(proposal);

	JavaCompletionProposal javaProposal= new JavaFieldWithCastedReceiverCompletionProposal(completion, start, length, image, label, relevance, getContext().isInJavadoc(), getInvocationContext(), proposal);
	if (fJavaProject != null)
		javaProposal.setProposalInfo(new FieldProposalInfo(fJavaProject, proposal));

	javaProposal.setTriggerCharacters(VAR_TRIGGER);

	return javaProposal;
}
 
Example #6
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void format(IDocument doc, CompilationUnitContext context) throws BadLocationException {
	Map<String, String> options;
	IJavaProject project= context.getJavaProject();
	if (project != null)
		options= project.getOptions(true);
	else
		options= JavaCore.getOptions();

	String contents= doc.get();
	int[] kinds= { CodeFormatter.K_EXPRESSION, CodeFormatter.K_STATEMENTS, CodeFormatter.K_UNKNOWN};
	TextEdit edit= null;
	for (int i= 0; i < kinds.length && edit == null; i++) {
		edit= CodeFormatterUtil.format2(kinds[i], contents, fInitialIndentLevel, fLineDelimiter, options);
	}

	if (edit == null)
		throw new BadLocationException(); // fall back to indenting

	edit.apply(doc, TextEdit.UPDATE_REGIONS);
}
 
Example #7
Source File: TypeCreator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private String formatJava(IType type) throws JavaModelException {
  String source = type.getCompilationUnit().getSource();
  CodeFormatter formatter = ToolFactory.createCodeFormatter(type.getJavaProject().getOptions(true));
  TextEdit formatEdit = formatter.format(CodeFormatterFlags.getFlagsForCompilationUnitFormat(), source, 0,
      source.length(), 0, lineDelimiter);
  if (formatEdit == null) {
    CorePluginLog.logError("Could not format source for " + type.getCompilationUnit().getElementName());
    return source;
  }

  Document document = new Document(source);
  try {
    formatEdit.apply(document);
    source = document.get();
  } catch (BadLocationException e) {
    CorePluginLog.logError(e);
  }

  source = Strings.trimLeadingTabsAndSpaces(source);
  return source;
}
 
Example #8
Source File: ProjectResources.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Given a String containing the text of a Java source file, return the same
 * Java source, but reformatted by the Eclipse auto-format code, with the
 * user's current Java preferences.
 */
public static String reformatJavaSourceAsString(String source) {
  TextEdit reformatTextEdit = CodeFormatterUtil.format2(
      CodeFormatter.K_COMPILATION_UNIT, source, 0, (String) null,
      JavaCore.getOptions());
  if (reformatTextEdit != null) {
    Document document = new Document(source);
    try {
      reformatTextEdit.apply(document, TextEdit.NONE);
      source = document.get();
    } catch (BadLocationException ble) {
      CorePluginLog.logError(ble);
    }
  }
  return source;
}
 
Example #9
Source File: JavaFormatter.java    From formatter-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public String doFormat(String code, LineEnding ending) throws IOException, BadLocationException {
    TextEdit te;
    try {
        te = this.formatter.format(CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, code, 0,
                code.length(), 0, ending.getChars());
        if (te == null) {
            this.log.debug(
                    "Code cannot be formatted. Possible cause is unmatched source/target/compliance version.");
            return null;
        }
    } catch (IndexOutOfBoundsException e) {
        this.log.debug("Code cannot be formatted for text -->" + code + "<--", e);
        return null;
    }

    IDocument doc = new Document(code);
    te.apply(doc);
    String formattedCode = doc.get();

    if (code.equals(formattedCode)) {
        return null;
    }
    return formattedCode;
}
 
Example #10
Source File: GetterSetterCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @param document
 * @param offset
 * @param importRewrite
 * @param completionSnippetsSupported
 * @param addComments
 * @return
 * @throws CoreException
 * @throws BadLocationException
 */
public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite, boolean completionSnippetsSupported, boolean addComments) throws CoreException, BadLocationException {
	int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic);
	String stub;
	if (fIsGetter) {
		String getterName= GetterSetterUtil.getGetterName(fField, null);
		stub = GetterSetterUtil.getGetterStub(fField, getterName, addComments, flags);
	} else {
		String setterName= GetterSetterUtil.getSetterName(fField, null);
		stub = GetterSetterUtil.getSetterStub(fField, setterName, addComments, flags);
	}

	// use the code formatter
	String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
	String replacement = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, 0, lineDelim, fField.getJavaProject());

	if (replacement.endsWith(lineDelim)) {
		replacement = replacement.substring(0, replacement.length() - lineDelim.length());
	}

	return replacement;
}
 
Example #11
Source File: JavaCodeFormatter.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public String apply(String contents) {
    TextEdit edit = codeFormatter.format(
            CodeFormatter.K_COMPILATION_UNIT
            | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0,
            contents.length(), 0, System.lineSeparator());

    if (edit == null) {
        // TODO log a fatal or warning here. Throwing an exception is causing the actual freemarker error to be lost
        return contents;
    }

    IDocument document = new Document(contents);

    try {
        edit.apply(document);
    } catch (Exception e) {
        throw new RuntimeException(
                "Failed to format the generated source code.", e);
    }

    return document.get();
}
 
Example #12
Source File: JavaCodeFormatter.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public String apply(String contents) {
    TextEdit edit = codeFormatter.format(
            CodeFormatter.K_COMPILATION_UNIT
            | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0,
            contents.length(), 0, Constant.LF);

    if (edit == null) {
        // TODO log a fatal or warning here. Throwing an exception is causing the actual freemarker error to be lost
        return contents;
    }

    IDocument document = new Document(contents);

    try {
        edit.apply(document);
    } catch (Exception e) {
        throw new RuntimeException(
                "Failed to format the generated source code.", e);
    }

    return document.get();
}
 
Example #13
Source File: Scribe.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
Scribe(CodeFormatterVisitor formatter, long sourceLevel, IRegion[] regions, CodeSnippetParsingUtil codeSnippetParsingUtil, boolean includeComments) {
	initializeScanner(sourceLevel, formatter.preferences);
	this.formatter = formatter;
	this.pageWidth = formatter.preferences.page_width;
	this.tabLength = formatter.preferences.tab_size;
	this.indentationLevel= 0; // initialize properly
	this.numberOfIndentations = 0;
	this.useTabsOnlyForLeadingIndents = formatter.preferences.use_tabs_only_for_leading_indentations;
	this.indentEmptyLines = formatter.preferences.indent_empty_lines;
	this.tabChar = formatter.preferences.tab_char;
	if (this.tabChar == DefaultCodeFormatterOptions.MIXED) {
		this.indentationSize = formatter.preferences.indentation_size;
	} else {
		this.indentationSize = this.tabLength;
	}
	this.lineSeparator = formatter.preferences.line_separator;
	this.lineSeparatorAndSpace = this.lineSeparator+' ';
	this.firstLS = this.lineSeparator.charAt(0);
	this.lsLength = this.lineSeparator.length();
	this.indentationLevel = formatter.preferences.initial_indentation_level * this.indentationSize;
	this.regions= regions;
	if (codeSnippetParsingUtil != null) {
		final RecordedParsingInformation information = codeSnippetParsingUtil.recordedParsingInformation;
		if (information != null) {
			this.lineEnds = information.lineEnds;
			this.commentPositions = information.commentPositions;
		}
	}
	if (formatter.preferences.comment_format_line_comment) this.formatComments |= CodeFormatter.K_SINGLE_LINE_COMMENT;
	if (formatter.preferences.comment_format_block_comment) this.formatComments |= CodeFormatter.K_MULTI_LINE_COMMENT;
	if (formatter.preferences.comment_format_javadoc_comment) this.formatComments |= CodeFormatter.K_JAVA_DOC;
	if (includeComments) this.formatComments |= CodeFormatter.F_INCLUDE_COMMENTS;
	reset();
}
 
Example #14
Source File: JavadocLineBreakPreparator.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(int kind, TokenManager tokenManager, ASTNode astRoot) {
	if ((kind & CodeFormatter.F_INCLUDE_COMMENTS) != 0) {
		ASTVisitor visitor = new Vistor(tokenManager);
		for (Comment comment : getComments(astRoot)) {
			comment.accept(visitor);
		}
	}
}
 
Example #15
Source File: CodeUtils.java    From minnal with Apache License 2.0 5 votes vote down vote up
public static String format(String code, Map<String, String> options) {
    DefaultCodeFormatterOptions cfOptions = DefaultCodeFormatterOptions.getJavaConventionsSettings();
    cfOptions.tab_char = DefaultCodeFormatterOptions.TAB;
    CodeFormatter cf = new DefaultCodeFormatter(cfOptions, options);
    TextEdit te = cf.format(CodeFormatter.K_UNKNOWN, code, 0, code.length(), 0, null);
    IDocument dc = new Document(code);

    try {
        te.apply(dc);
    } catch (Exception e) {
        throw new MinnalGeneratorException("Failed while formatting the code", e);
    }
    return dc.get();
}
 
Example #16
Source File: FullSourceWorkspaceFormatterTests.java    From dacapobench with Apache License 2.0 5 votes vote down vote up
/**
 * Format files using code formatter default options.
 */
public void testFormatDefault() throws CoreException {
  for (int i = 0; i < FORMAT_FILES.length; i++) {
    if (DACAPO_PRINT)
      System.out.print(".");
    IJavaElement element = JDT_CORE_PROJECT.findType(FORMAT_FILES[i]);
    String source = ((ICompilationUnit) element.getParent()).getSource();
    for (int j = 0; j < 2; j++)
      new DefaultCodeFormatter().format(CodeFormatter.K_COMPILATION_UNIT, source, 0, source.length(), 0, null);
  }
}
 
Example #17
Source File: ASTRewriteFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public String[] getPrefixAndSuffix(int indent, ASTNode node, RewriteEventStore events) {
	String nodeString= ASTRewriteFlattener.asString(node, events);
	String str= this.prefix + nodeString;
	Position pos= new Position(this.start, this.prefix.length() + 1 - this.start);

	TextEdit res= formatString(CodeFormatter.K_STATEMENTS, str, 0, str.length(), indent);
	if (res != null) {
		str= evaluateFormatterEdit(str, res, new Position[] { pos });
	}
	return new String[] { str.substring(pos.offset + 1, pos.offset + pos.length - 1), ""}; //$NON-NLS-1$
}
 
Example #18
Source File: Scribe.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
void setIncludeComments(boolean on) {
	if (on) {
		this.formatComments |= CodeFormatter.F_INCLUDE_COMMENTS;
	} else {
		this.formatComments &= ~CodeFormatter.F_INCLUDE_COMMENTS;
	}
}
 
Example #19
Source File: Scribe.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void printQualifiedReference(int sourceEnd, boolean expectParenthesis) {
	int currentTokenStartPosition = this.scanner.currentPosition;
	try {
		do {
			printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT);
			switch(this.currentToken = this.scanner.getNextToken()) {
				case TerminalTokens.TokenNameEOF :
					return;
				case TerminalTokens.TokenNameWHITESPACE :
					addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition());
					currentTokenStartPosition = this.scanner.currentPosition;
					break;
				case TerminalTokens.TokenNameCOMMENT_BLOCK :
				case TerminalTokens.TokenNameCOMMENT_JAVADOC :
					printBlockComment(false);
					currentTokenStartPosition = this.scanner.currentPosition;
					break;
				case TerminalTokens.TokenNameCOMMENT_LINE :
					printLineComment();
					currentTokenStartPosition = this.scanner.currentPosition;
					break;
				case TerminalTokens.TokenNameIdentifier :
				case TerminalTokens.TokenNameDOT :
					print(this.scanner.currentPosition - this.scanner.startPosition, false);
					currentTokenStartPosition = this.scanner.currentPosition;
					break;
				case TerminalTokens.TokenNameRPAREN:
					if (expectParenthesis) {
						currentTokenStartPosition = this.scanner.startPosition;
					}
					// $FALL-THROUGH$ - fall through default case...
				default:
					this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1);
					return;
			}
		} while (this.scanner.currentPosition <= sourceEnd);
	} catch(InvalidInputException e) {
		throw new AbortFormatting(e);
	}
}
 
Example #20
Source File: Scribe.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void printNextToken(int expectedTokenType, boolean considerSpaceIfAny, int emptyLineRules) {
	// Set brace flag, it's useful for the scribe while preserving line breaks
	printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT, emptyLineRules);
	try {
		this.currentToken = this.scanner.getNextToken();
		if (expectedTokenType != this.currentToken) {
			throw new AbortFormatting("unexpected token type, expecting:"+expectedTokenType+", actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$
		}
		print(this.scanner.currentPosition - this.scanner.startPosition, considerSpaceIfAny);
	} catch (InvalidInputException e) {
		throw new AbortFormatting(e);
	}
}
 
Example #21
Source File: Scribe.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
void printComment(int kind, String source, int start, int end, int level) {

		// Set scanner
		resetScanner(source.toCharArray());
		this.scanner.resetTo(start, end);
		// Put back 3.4RC2 code => comment following line  as it has an impact on Linux tests
		// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=234336
		// TODO (frederic) Need more investigations and a better fix in
		// isAdaptableRegion(int) and adaptRegions()
		// this.scannerEndPosition = end;

		// Set indentation level
	    this.numberOfIndentations = level;
	    this.indentationLevel = level * this.indentationSize;
	    this.column = this.indentationLevel + 1;

	    // Print corresponding comment
	    switch (kind) {
	    	case CodeFormatter.K_SINGLE_LINE_COMMENT:
			    printComment(kind, NO_TRAILING_COMMENT);
	    		break;
	    	case CodeFormatter.K_MULTI_LINE_COMMENT:
			    printComment(kind, NO_TRAILING_COMMENT);
	    		break;
	    	case CodeFormatter.K_JAVA_DOC:
	    		printJavadocComment(start, end);
	    		break;
	    }
    }
 
Example #22
Source File: FormatterHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private int getFormattingKind(ICompilationUnit cu, boolean includeComments) {
	int kind = includeComments ? CodeFormatter.F_INCLUDE_COMMENTS : 0;
	if (cu.getResource() != null && cu.getResource().getName().equals(IModule.MODULE_INFO_JAVA)) {
		kind |= CodeFormatter.K_MODULE_INFO;
	} else {
		kind |= CodeFormatter.K_COMPILATION_UNIT;
	}
	return kind;
}
 
Example #23
Source File: JavaFormatter.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("try")
public static String formatEclipseStyle(final Properties prop, final String content) {
  try (TelemetryUtils.ScopedSpan scope =
      TelemetryUtils.startScopedSpan("JavaFormatter.formatEclipseStyle")) {
    TelemetryUtils.ScopedSpan.addAnnotation(
        TelemetryUtils.annotationBuilder().put("size", content.length()).build("args"));

    final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(prop);
    final IDocument document = new Document(content);
    final TextEdit textEdit =
        codeFormatter.format(
            CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS,
            content,
            0,
            content.length(),
            0,
            null);
    if (nonNull(textEdit)) {
      textEdit.apply(document);
      return ensureCorrectNewLines(document.get());
    } else {
      return content;
    }
  } catch (Throwable e) {
    return content;
  }
}
 
Example #24
Source File: AnonymousTypeCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public String updateReplacementString(IDocument document, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {
	// Construct empty body for performance concern
	// See https://github.com/microsoft/language-server-protocol/issues/1032#issuecomment-648748013
	String newBody = fSnippetSupport ? "{\n\t${0}\n}" : "{\n\n}";

	StringBuilder buf = new StringBuilder("new A()"); //$NON-NLS-1$
	buf.append(newBody);
	// use the code formatter
	String lineDelim = TextUtilities.getDefaultLineDelimiter(document);
	final IJavaProject project = fCompilationUnit.getJavaProject();
	IRegion lineInfo = document.getLineInformationOfOffset(fReplacementOffset);
	Map<String, String> options = project != null ? project.getOptions(true) : JavaCore.getOptions();
	String replacementString = CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, buf.toString(), 0, lineDelim, options);
	int lineEndOffset = lineInfo.getOffset() + lineInfo.getLength();
	int p = offset;
	if (p < document.getLength()) {
		char ch = document.getChar(p);
		while (p < lineEndOffset) {
			if (ch == '(' || ch == ')' || ch == ';' || ch == ',') {
				break;
			}
			ch = document.getChar(++p);
		}
		if (ch != ';' && ch != ',' && ch != ')') {
			replacementString = replacementString + ';';
		}
	}
	int beginIndex = replacementString.indexOf('(');
	replacementString = replacementString.substring(beginIndex);
	return replacementString;
}
 
Example #25
Source File: JavaCodeFormatterImpl.java    From jenerate with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String formatCode(IType objectClass, String source) throws JavaModelException, BadLocationException {
    String lineDelim = getLineDelimiterUsed(objectClass);
    int indent = getUsedIndentation(objectClass) + 1;
    TextEdit textEdit = ToolFactory.createCodeFormatter(null).format(CodeFormatter.K_CLASS_BODY_DECLARATIONS,
            source, 0, source.length(), indent, lineDelim);
    if (textEdit == null) {
        return source;
    }
    Document document = new Document(source);
    textEdit.apply(document);
    return document.get();
}
 
Example #26
Source File: GoogleJavaFormatter.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
/** Runs the Google Java formatter on the given source, with only the given ranges specified. */
private TextEdit formatInternal(int kind, String source, IRegion[] regions, int initialIndent) {
  try {
    boolean includeComments =
        (kind & CodeFormatter.F_INCLUDE_COMMENTS) == CodeFormatter.F_INCLUDE_COMMENTS;
    kind &= ~CodeFormatter.F_INCLUDE_COMMENTS;
    SnippetKind snippetKind;
    switch (kind) {
      case ASTParser.K_EXPRESSION:
        snippetKind = SnippetKind.EXPRESSION;
        break;
      case ASTParser.K_STATEMENTS:
        snippetKind = SnippetKind.STATEMENTS;
        break;
      case ASTParser.K_CLASS_BODY_DECLARATIONS:
        snippetKind = SnippetKind.CLASS_BODY_DECLARATIONS;
        break;
      case ASTParser.K_COMPILATION_UNIT:
        snippetKind = SnippetKind.COMPILATION_UNIT;
        break;
      default:
        throw new IllegalArgumentException(String.format("Unknown snippet kind: %d", kind));
    }
    List<Replacement> replacements =
        new SnippetFormatter()
            .format(
                snippetKind, source, rangesFromRegions(regions), initialIndent, includeComments);
    if (idempotent(source, regions, replacements)) {
      // Do not create edits if there's no diff.
      return null;
    }
    // Convert replacements to text edits.
    return editFromReplacements(replacements);
  } catch (IllegalArgumentException | FormatterException exception) {
    // Do not format on errors.
    return null;
  }
}
 
Example #27
Source File: GetterSetterCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {

	CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(fField.getJavaProject());
	boolean addComments= settings.createComments;
	int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic);

	String stub;
	if (fIsGetter) {
		String getterName= GetterSetterUtil.getGetterName(fField, null);
		stub= GetterSetterUtil.getGetterStub(fField, getterName, addComments, flags);
	} else {
		String setterName= GetterSetterUtil.getSetterName(fField, null);
		stub= GetterSetterUtil.getSetterStub(fField, setterName, addComments, flags);
	}

	// use the code formatter
	String lineDelim= TextUtilities.getDefaultLineDelimiter(document);

	IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
	int lineStart= region.getOffset();
	int indent= Strings.computeIndentUnits(document.get(lineStart, getReplacementOffset() - lineStart), settings.tabWidth, settings.indentWidth);

	String replacement= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, indent, lineDelim, fField.getJavaProject());

	if (replacement.endsWith(lineDelim)) {
		replacement= replacement.substring(0, replacement.length() - lineDelim.length());
	}

	setReplacementString(Strings.trimLeadingTabsAndSpaces(replacement));
	return true;
}
 
Example #28
Source File: CodeLineBreakPreparator.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(int kind, TokenManager tokenManager, ASTNode astRoot) {
	if ((kind & CodeFormatter.K_COMPILATION_UNIT) != 0) {
		ASTVisitor visitor = new Vistor(tokenManager);
		astRoot.accept(visitor);
	}
}
 
Example #29
Source File: Scribe.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
void printComment(int emptyLinesRules) {
	printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT, emptyLinesRules);
}
 
Example #30
Source File: NewPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void createPackageInfoJava(IProgressMonitor monitor) throws CoreException {
	String lineDelimiter= StubUtility.getLineDelimiterUsed(fCreatedPackageFragment.getJavaProject());
	StringBuilder content = new StringBuilder();
	String fileComment= getFileComment(lineDelimiter);
	String typeComment= getTypeComment(lineDelimiter);
	
	if (fileComment != null) {
		content.append(fileComment);
		content.append(lineDelimiter);
	}

	if (typeComment != null) {
		content.append(typeComment);
		content.append(lineDelimiter);
	} else if (fileComment != null) {
		// insert an empty file comment to avoid that the file comment becomes the type comment
		content.append("/**");  //$NON-NLS-1$
		content.append(lineDelimiter);
		content.append(" *"); //$NON-NLS-1$
		content.append(lineDelimiter);
		content.append(" */"); //$NON-NLS-1$
		content.append(lineDelimiter);
	}

	content.append("package "); //$NON-NLS-1$
	content.append(fCreatedPackageFragment.getElementName());
	content.append(";"); //$NON-NLS-1$

	ICompilationUnit compilationUnit= fCreatedPackageFragment.createCompilationUnit(PACKAGE_INFO_JAVA_FILENAME, content.toString(), true, monitor);

	JavaModelUtil.reconcile(compilationUnit);

	compilationUnit.becomeWorkingCopy(monitor);
	try {
		IBuffer buffer= compilationUnit.getBuffer();
		ISourceRange sourceRange= compilationUnit.getSourceRange();
		String originalContent= buffer.getText(sourceRange.getOffset(), sourceRange.getLength());

		String formattedContent= CodeFormatterUtil.format(CodeFormatter.K_COMPILATION_UNIT, originalContent, 0, lineDelimiter, fCreatedPackageFragment.getJavaProject());
		formattedContent= Strings.trimLeadingTabsAndSpaces(formattedContent);
		buffer.replace(sourceRange.getOffset(), sourceRange.getLength(), formattedContent);
		compilationUnit.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
	} finally {
		compilationUnit.discardWorkingCopy();
	}
}