Java Code Examples for org.eclipse.jdt.internal.corext.util.CodeFormatterUtil#format()

The following examples show how to use org.eclipse.jdt.internal.corext.util.CodeFormatterUtil#format() . 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: 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 2
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 3
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 4
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 5
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 6
Source File: SnippetPreview.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void doFormatPreview() {
       if (fSnippets.isEmpty()) {
           fPreviewDocument.set(""); //$NON-NLS-1$
           return;
       }

       //This delimiter looks best for invisible characters
       final String delimiter= "\n"; //$NON-NLS-1$

       final StringBuffer buffer= new StringBuffer();
       for (final Iterator<PreviewSnippet> iter= fSnippets.iterator(); iter.hasNext();) {
           final PreviewSnippet snippet= iter.next();
           String formattedSource;
           try {
               formattedSource= CodeFormatterUtil.format(snippet.kind, snippet.source, 0, delimiter, fWorkingValues);
           } catch (Exception e) {
               final IStatus status= new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR,
                   FormatterMessages.JavaPreview_formatter_exception, e);
               JavaPlugin.log(status);
               continue;
           }
           buffer.append(delimiter);
           buffer.append(formattedSource);
           buffer.append(delimiter);
           buffer.append(delimiter);
       }
       fPreviewDocument.set(buffer.toString());
   }
 
Example 7
Source File: AccessorClassCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private String createAccessorCUSource(IProgressMonitor pm) throws CoreException {
	IProject project= getFileHandle(fAccessorPath).getProject();
	String lineDelimiter= StubUtility.getLineDelimiterPreference(project);
	return CodeFormatterUtil.format(CodeFormatter.K_COMPILATION_UNIT, getUnformattedSource(pm), 0, lineDelimiter, fCu.getJavaProject());
}
 
Example 8
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();
	}
}
 
Example 9
Source File: MethodDeclarationCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {

	CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(fType.getJavaProject());
	boolean addComments= settings.createComments;

	String[] empty= new String[0];
	String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
	String declTypeName= fType.getTypeQualifiedName('.');
	boolean isInterface= fType.isInterface();

	StringBuffer buf= new StringBuffer();
	if (addComments) {
		String comment= CodeGeneration.getMethodComment(fType.getCompilationUnit(), declTypeName, fMethodName, empty, empty, fReturnTypeSig, empty, null, lineDelim);
		if (comment != null) {
			buf.append(comment);
			buf.append(lineDelim);
		}
	}
	if (fReturnTypeSig != null) {
		if (!isInterface) {
			buf.append("private "); //$NON-NLS-1$
		}
	} else {
		if (fType.isEnum())
			buf.append("private "); //$NON-NLS-1$
		else
			buf.append("public "); //$NON-NLS-1$
	}

	if (fReturnTypeSig != null) {
		buf.append(Signature.toString(fReturnTypeSig));
	}
	buf.append(' ');
	buf.append(fMethodName);
	if (isInterface) {
		buf.append("();"); //$NON-NLS-1$
		buf.append(lineDelim);
	} else {
		buf.append("() {"); //$NON-NLS-1$
		buf.append(lineDelim);

		String body= CodeGeneration.getMethodBodyContent(fType.getCompilationUnit(), declTypeName, fMethodName, fReturnTypeSig == null, "", lineDelim); //$NON-NLS-1$
		if (body != null) {
			buf.append(body);
			buf.append(lineDelim);
		}
		buf.append("}"); //$NON-NLS-1$
		buf.append(lineDelim);
	}
	String stub=  buf.toString();

	// use the code formatter
	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, fType.getJavaProject());

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

	setReplacementString(Strings.trimLeadingTabsAndSpaces(replacement));
	return true;
}
 
Example 10
Source File: AnonymousTypeCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {
	fImportRewrite= impRewrite;
	String newBody= createNewBody(impRewrite);
	if (newBody == null)
		return false;

	CompletionProposal coreProposal= ((MemberProposalInfo)getProposalInfo()).fProposal;
	boolean isAnonymousConstructorInvoc= coreProposal.getKind() == CompletionProposal.ANONYMOUS_CLASS_CONSTRUCTOR_INVOCATION;

	boolean replacementStringEndsWithParentheses= isAnonymousConstructorInvoc || getReplacementString().endsWith(")"); //$NON-NLS-1$

	// construct replacement text: an expression to be formatted
	StringBuffer buf= new StringBuffer("new A("); //$NON-NLS-1$
	if (!replacementStringEndsWithParentheses || isAnonymousConstructorInvoc)
		buf.append(')');
	buf.append(newBody);

	// use the code formatter
	String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
	final IJavaProject project= fCompilationUnit.getJavaProject();
	IRegion lineInfo= document.getLineInformationOfOffset(getReplacementOffset());
	int indent= Strings.computeIndentUnits(document.get(lineInfo.getOffset(), lineInfo.getLength()), project);

	Map<String, String> options= project != null ? project.getOptions(true) : JavaCore.getOptions();
	options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES, DefaultCodeFormatterConstants.TRUE);
	String replacementString= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, buf.toString(), 0, lineDelim, options);

	int lineEndOffset= lineInfo.getOffset() + lineInfo.getLength();

	int p= offset;
	char ch= document.getChar(p);
	while (p < lineEndOffset) {
		if (ch == '(' || ch == ')' || ch == ';' || ch == ',')
			break;
		ch= document.getChar(++p);
	}

	if (ch != ';' && ch != ',' && ch != ')')
		replacementString= replacementString + ';';

	replacementString= Strings.changeIndent(replacementString, 0, project, CodeFormatterUtil.createIndentString(indent, project), lineDelim);
	
	int beginIndex= replacementString.indexOf('(');
	if (!isAnonymousConstructorInvoc)
		beginIndex++;
	replacementString= replacementString.substring(beginIndex);

	int pos= offset;
	if (isAnonymousConstructorInvoc && (insertCompletion() ^ isInsertModeToggled())) {
		// Keep existing code
		int endPos= pos;
		ch= document.getChar(endPos);
		while (endPos < lineEndOffset && ch != '(' && ch != ')' && ch != ';' && ch != ',' && !Character.isWhitespace(ch))
			ch= document.getChar(++endPos);

		int keepLength= endPos - pos;
		if (keepLength > 0) {
			String keepStr= document.get(pos, keepLength);
			replacementString= replacementString + keepStr;
			setCursorPosition(replacementString.length() - keepLength);
		}
	} else
		setCursorPosition(replacementString.length());
	
	setReplacementString(replacementString);

	if (pos < document.getLength() && document.getChar(pos) == ')') {
		int currentLength= getReplacementLength();
		if (replacementStringEndsWithParentheses)
			setReplacementLength(currentLength + pos - offset);
		else
			setReplacementLength(currentLength + pos - offset + 1);
	}
	return false;
}