org.eclipse.jdt.internal.corext.util.Strings Java Examples

The following examples show how to use org.eclipse.jdt.internal.corext.util.Strings. 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: 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 #2
Source File: DelegateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Performs the actual rewriting and adds an edit to the ASTRewrite set with
 * {@link #setSourceRewrite(CompilationUnitRewrite)}.
 *
 * @throws JavaModelException
 */
public void createEdit() throws JavaModelException {
	try {
		IDocument document= new Document(fDelegateRewrite.getCu().getBuffer().getContents());
		TextEdit edit= fDelegateRewrite.getASTRewrite().rewriteAST(document, fDelegateRewrite.getCu().getJavaProject().getOptions(true));
		edit.apply(document, TextEdit.UPDATE_REGIONS);

		String newSource= Strings.trimIndentation(document.get(fTrackedPosition.getStartPosition(), fTrackedPosition.getLength()),
				fPreferences.tabWidth, fPreferences.indentWidth, false);

		ASTNode placeholder= fOriginalRewrite.getASTRewrite().createStringPlaceholder(newSource, fDeclaration.getNodeType());

		CategorizedTextEditGroup groupDescription= fOriginalRewrite.createCategorizedGroupDescription(getTextEditGroupLabel(), CATEGORY_DELEGATE);
		ListRewrite bodyDeclarationsListRewrite= fOriginalRewrite.getASTRewrite().getListRewrite(fDeclaration.getParent(), getTypeBodyDeclarationsProperty());
		if (fCopy)
			if (fInsertBefore)
				bodyDeclarationsListRewrite.insertBefore(placeholder, fDeclaration, groupDescription);
			else
				bodyDeclarationsListRewrite.insertAfter(placeholder, fDeclaration, groupDescription);
		else
			bodyDeclarationsListRewrite.replace(fDeclaration, placeholder, groupDescription);

	} catch (BadLocationException e) {
		JavaPlugin.log(e);
	}
}
 
Example #3
Source File: PatternMatcher.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public boolean matches(String text) {
	switch (fMatchKind) {
		case SearchPattern.R_PATTERN_MATCH:
			return fStringMatcher.match(text);
		case SearchPattern.R_EXACT_MATCH:
			return fPattern.equalsIgnoreCase(text);
		case SearchPattern.R_CAMELCASE_SAME_PART_COUNT_MATCH:
			return SearchPattern.camelCaseMatch(fPattern, text, true);
		case SearchPattern.R_CAMELCASE_MATCH:
			if (SearchPattern.camelCaseMatch(fPattern, text)) {
				return true;
			}
			// fall back to prefix match if camel case failed (bug 137244)
			return Strings.startsWithIgnoreCase(text, fPattern);
		default:
			return Strings.startsWithIgnoreCase(text, fPattern);
	}
}
 
Example #4
Source File: CodeRefactoringUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static int getIndentationLevel(ASTNode node, ICompilationUnit unit) throws CoreException {
	IPath fullPath= unit.getCorrespondingResource().getFullPath();
	try{
		FileBuffers.getTextFileBufferManager().connect(fullPath, LocationKind.IFILE, new NullProgressMonitor());
		ITextFileBuffer buffer= FileBuffers.getTextFileBufferManager().getTextFileBuffer(fullPath, LocationKind.IFILE);
		try {
			IRegion region= buffer.getDocument().getLineInformationOfOffset(node.getStartPosition());
			return Strings.computeIndentUnits(buffer.getDocument().get(region.getOffset(), region.getLength()), unit.getJavaProject());
		} catch (BadLocationException exception) {
			JavaPlugin.log(exception);
		}
		return 0;
	} finally {
		FileBuffers.getTextFileBufferManager().disconnect(fullPath, LocationKind.IFILE, new NullProgressMonitor());
	}
}
 
Example #5
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the method content of the moved method.
 *
 * @param document
 *            the document representing the source compilation unit
 * @param declaration
 *            the source method declaration
 * @param rewrite
 *            the ast rewrite to use
 * @return the string representing the moved method body
 * @throws BadLocationException
 *             if an offset into the document is invalid
 */
protected String createMethodContent(final IDocument document, final MethodDeclaration declaration, final ASTRewrite rewrite) throws BadLocationException {
	Assert.isNotNull(document);
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	final IRegion range= new Region(declaration.getStartPosition(), declaration.getLength());
	final RangeMarker marker= new RangeMarker(range.getOffset(), range.getLength());
	final IJavaProject project= fMethod.getJavaProject();
	final TextEdit[] edits= rewrite.rewriteAST(document, project.getOptions(true)).removeChildren();
	for (int index= 0; index < edits.length; index++)
		marker.addChild(edits[index]);
	final MultiTextEdit result= new MultiTextEdit();
	result.addChild(marker);
	final TextEditProcessor processor= new TextEditProcessor(document, new MultiTextEdit(0, document.getLength()), TextEdit.UPDATE_REGIONS);
	processor.getRoot().addChild(result);
	processor.performEdits();
	final IRegion region= document.getLineInformation(document.getLineOfOffset(marker.getOffset()));
	return Strings.changeIndent(document.get(marker.getOffset(), marker.getLength()), Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project), project, "", TextUtilities.getDefaultLineDelimiter(document)); //$NON-NLS-1$
}
 
Example #6
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the source of the given node from the location where it was parsed.
 * @param node the node to get the source from
 * @param extendedRange if set, the extended ranges of the nodes should ne used
 * @param removeIndent if set, the indentation is removed.
 * @return return the source for the given node or null if accessing the source failed.
 */
public static String getNodeSource(ASTNode node, boolean extendedRange, boolean removeIndent) {
	ASTNode root= node.getRoot();
	if (root instanceof CompilationUnit) {
		CompilationUnit astRoot= (CompilationUnit) root;
		ITypeRoot typeRoot= astRoot.getTypeRoot();
		try {
			if (typeRoot != null && typeRoot.getBuffer() != null) {
				IBuffer buffer= typeRoot.getBuffer();
				int offset= extendedRange ? astRoot.getExtendedStartPosition(node) : node.getStartPosition();
				int length= extendedRange ? astRoot.getExtendedLength(node) : node.getLength();
				String str= buffer.getText(offset, length);
				if (removeIndent) {
					IJavaProject project= typeRoot.getJavaProject();
					int indent= StubUtility.getIndentUsed(buffer, node.getStartPosition(), project);
					str= Strings.changeIndent(str, indent, project, new String(), typeRoot.findRecommendedLineSeparator());
				}
				return str;
			}
		} catch (JavaModelException e) {
			// ignore
		}
	}
	return null;
}
 
Example #7
Source File: BindingLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the label for a Java element with the flags as defined by {@link JavaElementLabels}.
 * @param binding The binding to render.
 * @param flags The text flags as defined in {@link JavaElementLabels}
 * @return the label of the binding
 */
public static String getBindingLabel(IBinding binding, long flags) {
	StringBuffer buffer= new StringBuffer(60);
	if (binding instanceof ITypeBinding) {
		getTypeLabel(((ITypeBinding) binding), flags, buffer);
	} else if (binding instanceof IMethodBinding) {
		getMethodLabel(((IMethodBinding) binding), flags, buffer);
	} else if (binding instanceof IVariableBinding) {
		final IVariableBinding variable= (IVariableBinding) binding;
		if (variable.isField())
			getFieldLabel(variable, flags, buffer);
		else
			getLocalVariableLabel(variable, flags, buffer);
	}
	return Strings.markLTR(buffer.toString());
}
 
Example #8
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static String getMethodBodyContent(boolean isConstructor, IJavaProject project, String destTypeName, String methodName, String bodyStatement, String lineDelimiter) throws CoreException {
	String templateName= isConstructor ? CodeTemplateContextType.CONSTRUCTORSTUB_ID : CodeTemplateContextType.METHODSTUB_ID;
	Template template= getCodeTemplate(templateName, project);
	if (template == null) {
		return bodyStatement;
	}
	CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter);
	context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
	context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName);
	context.setVariable(CodeTemplateContextType.BODY_STATEMENT, bodyStatement);
	String str= evaluateTemplate(context, template, new String[] { CodeTemplateContextType.BODY_STATEMENT });
	if (str == null && !Strings.containsOnlyWhitespaces(bodyStatement)) {
		return bodyStatement;
	}
	return str;
}
 
Example #9
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String fixEmptyVariables(TemplateBuffer buffer, String[] variables) throws MalformedTreeException, BadLocationException {
	IDocument doc= new Document(buffer.getString());
	int nLines= doc.getNumberOfLines();
	MultiTextEdit edit= new MultiTextEdit();
	HashSet<Integer> removedLines= new HashSet<Integer>();
	for (int i= 0; i < variables.length; i++) {
		TemplateVariable position= findVariable(buffer, variables[i]); // look if Javadoc tags have to be added
		if (position == null || position.getLength() > 0) {
			continue;
		}
		int[] offsets= position.getOffsets();
		for (int k= 0; k < offsets.length; k++) {
			int line= doc.getLineOfOffset(offsets[k]);
			IRegion lineInfo= doc.getLineInformation(line);
			int offset= lineInfo.getOffset();
			String str= doc.get(offset, lineInfo.getLength());
			if (Strings.containsOnlyWhitespaces(str) && nLines > line + 1 && removedLines.add(new Integer(line))) {
				int nextStart= doc.getLineOffset(line + 1);
				edit.addChild(new DeleteEdit(offset, nextStart - offset));
			}
		}
	}
	edit.apply(doc, 0);
	return doc.get();
}
 
Example #10
Source File: CompletionProposalLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates and returns a parameter list of the given method or type proposal suitable for
 * display. The list does not include parentheses. The lower bound of parameter types is
 * returned.
 * <p>
 * Examples:
 * 
 * <pre>
 *   &quot;void method(int i, String s)&quot; -&gt; &quot;int i, String s&quot;
 *   &quot;? extends Number method(java.lang.String s, ? super Number n)&quot; -&gt; &quot;String s, Number n&quot;
 * </pre>
 * 
 * </p>
 * 
 * @param proposal the proposal to create the parameter list for
 * @return the list of comma-separated parameters suitable for display
 */
public String createParameterList(CompletionProposal proposal) {
	String paramList;
	int kind= proposal.getKind();
	switch (kind) {
		case CompletionProposal.METHOD_REF:
		case CompletionProposal.CONSTRUCTOR_INVOCATION:
			paramList= appendUnboundedParameterList(new StyledString(), proposal).getString();
			return Strings.markJavaElementLabelLTR(paramList);
		case CompletionProposal.TYPE_REF:
		case CompletionProposal.JAVADOC_TYPE_REF:
			paramList= appendTypeParameterList(new StyledString(), proposal).getString();
			return Strings.markJavaElementLabelLTR(paramList);
		case CompletionProposal.ANONYMOUS_CLASS_DECLARATION:
		case CompletionProposal.ANONYMOUS_CLASS_CONSTRUCTOR_INVOCATION:
			paramList= appendUnboundedParameterList(new StyledString(), proposal).getString();
			return Strings.markJavaElementLabelLTR(paramList);
		default:
			Assert.isLegal(false);
			return null; // dummy
	}
}
 
Example #11
Source File: CompletionProposalLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
StyledString createAnonymousTypeLabel(CompletionProposal proposal) {
	char[] declaringTypeSignature= proposal.getDeclarationSignature();
	declaringTypeSignature= Signature.getTypeErasure(declaringTypeSignature);

	StyledString buffer= new StyledString();
	buffer.append(Signature.getSignatureSimpleName(declaringTypeSignature));
	buffer.append('(');
	appendUnboundedParameterList(buffer, proposal);
	buffer.append(')');
	buffer.append("  "); //$NON-NLS-1$
	buffer.append(JavaTextMessages.ResultCollector_anonymous_type);

	if (proposal.getRequiredProposals() != null) {
		char[] signatureQualifier= Signature.getSignatureQualifier(declaringTypeSignature);
		if (signatureQualifier.length > 0) {
			buffer.append(JavaElementLabels.CONCAT_STRING, StyledString.QUALIFIER_STYLER);
			buffer.append(signatureQualifier, StyledString.QUALIFIER_STYLER);
		}
	}

	return Strings.markJavaElementLabelLTR(buffer);
}
 
Example #12
Source File: JavaElementLabels.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the styled label of the given object. The object must be of type {@link IJavaElement} or adapt to {@link IWorkbenchAdapter}.
 * If the element type is not known, the empty string is returned.
 * The returned label is BiDi-processed with {@link TextProcessor#process(String, String)}.
 *
 * @param obj object to get the label for
 * @param flags the rendering flags
 * @return the label or the empty string if the object type is not supported
 *
 * @since 3.4
 */
public static StyledString getStyledTextLabel(Object obj, long flags) {
	if (obj instanceof IJavaElement) {
		return getStyledElementLabel((IJavaElement) obj, flags);

	} else if (obj instanceof IResource) {
		return getStyledResourceLabel((IResource) obj);

	} else if (obj instanceof ClassPathContainer) {
		ClassPathContainer container= (ClassPathContainer) obj;
		return getStyledContainerEntryLabel(container.getClasspathEntry().getPath(), container.getJavaProject());

	} else if (obj instanceof IStorage) {
		return getStyledStorageLabel((IStorage) obj);

	} else if (obj instanceof IAdaptable) {
		IWorkbenchAdapter wbadapter= (IWorkbenchAdapter) ((IAdaptable)obj).getAdapter(IWorkbenchAdapter.class);
		if (wbadapter != null) {
			return Strings.markLTR(new StyledString(wbadapter.getLabel(obj)));
		}
	}
	return new StyledString();
}
 
Example #13
Source File: JavadocTagsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void addEdits(IDocument document, TextEdit rootEdit) throws CoreException {
	try {
		String lineDelimiter= TextUtilities.getDefaultLineDelimiter(document);
		final IJavaProject project= getCompilationUnit().getJavaProject();
		IRegion region= document.getLineInformationOfOffset(fInsertPosition);

		String lineContent= document.get(region.getOffset(), region.getLength());
		String indentString= Strings.getIndentString(lineContent, project);
		String str= Strings.changeIndent(fComment, 0, project, indentString, lineDelimiter);
		InsertEdit edit= new InsertEdit(fInsertPosition, str);
		rootEdit.addChild(edit);
		if (fComment.charAt(fComment.length() - 1) != '\n') {
			rootEdit.addChild(new InsertEdit(fInsertPosition, lineDelimiter));
			rootEdit.addChild(new InsertEdit(fInsertPosition, indentString));
		}
	} catch (BadLocationException e) {
		throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
	}
}
 
Example #14
Source File: JavaDocAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Removes start and end of a comment and corrects indentation and line
 * delimiters.
 *
 * @param comment the computed comment
 * @param indentation the base indentation
 * @param project the Java project for the formatter settings, or <code>null</code> for global preferences
 * @param lineDelimiter the line delimiter
 * @return a trimmed version of <code>comment</code>
 */
private String prepareTemplateComment(String comment, String indentation, IJavaProject project, String lineDelimiter) {
	//	trim comment start and end if any
	if (comment.endsWith("*/")) //$NON-NLS-1$
		comment= comment.substring(0, comment.length() - 2);
	comment= comment.trim();
	if (comment.startsWith("/*")) { //$NON-NLS-1$
		if (comment.length() > 2 && comment.charAt(2) == '*') {
			comment= comment.substring(3); // remove '/**'
		} else {
			comment= comment.substring(2); // remove '/*'
		}
	}
	// trim leading spaces, but not new lines
	int nonSpace= 0;
	int len= comment.length();
	while (nonSpace < len && Character.getType(comment.charAt(nonSpace)) == Character.SPACE_SEPARATOR)
			nonSpace++;
	comment= comment.substring(nonSpace);

	return Strings.changeIndent(comment, 0, project, indentation, lineDelimiter);
}
 
Example #15
Source File: LazyGenericTypeProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private String computeContextString(LazyGenericTypeProposal proposal) {
	try {
		TypeArgumentProposal[] proposals= proposal.computeTypeArgumentProposals();
		if (proposals.length == 0)
			return null;

		StringBuffer buf= new StringBuffer();
		for (int i= 0; i < proposals.length; i++) {
			buf.append(proposals[i].getDisplayName());
			if (i < proposals.length - 1)
				buf.append(", "); //$NON-NLS-1$
		}
		return Strings.markJavaElementLabelLTR(buf.toString());

	} catch (JavaModelException e) {
		return null;
	}
}
 
Example #16
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the indentation level at the position of code completion.
 *
 * @return the indentation level at the position of the code completion
 */
private int getIndentation() {
	int start= getStart();
	IDocument document= getDocument();
	try {
		IRegion region= document.getLineInformationOfOffset(start);
		String lineContent= document.get(region.getOffset(), region.getLength());
		IJavaProject project= getJavaProject();
		return Strings.computeIndentUnits(lineContent, project);
	} catch (BadLocationException e) {
		return 0;
	}
}
 
Example #17
Source File: JavaDocContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the indentation level at the position of code completion.
 *
 * @return the indentation level at the position of the code completion
 */
private int getIndentation() {
	int start= getStart();
	IDocument document= getDocument();
	try {
		IRegion region= document.getLineInformationOfOffset(start);
		String lineContent= document.get(region.getOffset(), region.getLength());
		IJavaProject project= getJavaProject();
		return Strings.computeIndentUnits(lineContent, project);
	} catch (BadLocationException e) {
		return 0;
	}
}
 
Example #18
Source File: CompletionProposalLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
StyledString createLabelWithTypeAndDeclaration(CompletionProposal proposal) {
	char[] name= proposal.getCompletion();
	if (!isThisPrefix(name))
		name= proposal.getName();

	StyledString buf= new StyledString();
	buf.append(name);
	char[] typeName= Signature.getSignatureSimpleName(proposal.getSignature());
	if (typeName.length > 0) {
		buf.append(VAR_TYPE_SEPARATOR);
		buf.append(typeName);
	}
	char[] declaration= proposal.getDeclarationSignature();
	if (declaration != null) {
		declaration= Signature.getSignatureSimpleName(declaration);
		if (declaration.length > 0) {
			buf.append(QUALIFIER_SEPARATOR, StyledString.QUALIFIER_STYLER);
			if (proposal.getRequiredProposals() != null) {
				String declaringType= extractDeclaringTypeFQN(proposal);
				String qualifier= Signature.getQualifier(declaringType);
				if (qualifier.length() > 0) {
					buf.append(qualifier, StyledString.QUALIFIER_STYLER);
					buf.append('.', StyledString.QUALIFIER_STYLER);
				}
			}
			buf.append(declaration, StyledString.QUALIFIER_STYLER);
		}
	}

	return Strings.markJavaElementLabelLTR(buf);
}
 
Example #19
Source File: JavaElementLinks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the label for a Java element with the flags as defined by {@link JavaElementLabels}.
 * Referenced element names in the label are rendered as header links.
 * If <code>linkAllNames</code> is <code>false</code>, don't link the name of the given element
 *
 * @param element the element to render
 * @param flags the rendering flags
 * @param linkAllNames if <code>true</code>, link all names; if <code>false</code>, link all names except original element's name
 * @return the label of the Java element
 * @since 3.6
 */
public static String getElementLabel(IJavaElement element, long flags, boolean linkAllNames) {
	StringBuffer buf= new StringBuffer();

	if (!Strings.USE_TEXT_PROCESSOR) {
		new JavaElementLinkedLabelComposer(linkAllNames ? null : element, buf).appendElementLabel(element, flags);
		return Strings.markJavaElementLabelLTR(buf.toString());
	} else {
		String label= JavaElementLabels.getElementLabel(element, flags);
		return label.replaceAll("<", "&lt;").replaceAll(">", "&gt;"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
	}
}
 
Example #20
Source File: FilteredTypesSelectionDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int compareName(String leftString, String rightString) {
	int result= leftString.compareToIgnoreCase(rightString);
	if (result != 0 || rightString.length() == 0) {
		return result;
	} else if (Strings.isLowerCase(leftString.charAt(0)) && !Strings.isLowerCase(rightString.charAt(0))) {
		return +1;
	} else if (Strings.isLowerCase(rightString.charAt(0)) && !Strings.isLowerCase(leftString.charAt(0))) {
		return -1;
	} else {
		return leftString.compareTo(rightString);
	}
}
 
Example #21
Source File: JavaElementLabels.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the label of the given object. The object must be of type {@link IJavaElement} or adapt to {@link IWorkbenchAdapter}.
 * If the element type is not known, the empty string is returned.
 * The returned label is BiDi-processed with {@link TextProcessor#process(String, String)}.
 *
 * @param obj object to get the label for
 * @param flags the rendering flags
 * @return the label or the empty string if the object type is not supported
 */
public static String getTextLabel(Object obj, long flags) {
	if (obj instanceof IJavaElement) {
		return getElementLabel((IJavaElement) obj, flags);

	} else if (obj instanceof IResource) {
		return BasicElementLabels.getResourceName((IResource) obj);

	} else if (obj instanceof ClassPathContainer) {
		ClassPathContainer container= (ClassPathContainer) obj;
		IPath containerPath= container.getClasspathEntry().getPath();
		try {
			return getContainerEntryLabel(containerPath, container.getJavaProject());
		} catch (JavaModelException e) {
			return BasicElementLabels.getPathLabel(containerPath, false);
		}

	} else if (obj instanceof IStorage) {
		return BasicElementLabels.getResourceName(((IStorage) obj).getName());

	} else if (obj instanceof IAdaptable) {
		IWorkbenchAdapter wbadapter= (IWorkbenchAdapter) ((IAdaptable)obj).getAdapter(IWorkbenchAdapter.class);
		if (wbadapter != null) {
			return Strings.markLTR(wbadapter.getLabel(obj));
		}
	}
	return ""; //$NON-NLS-1$
}
 
Example #22
Source File: NameConventionConfigurationBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public NameConventionEntry getResult() {
	NameConventionEntry res= new NameConventionEntry();
	res.prefix= Strings.removeTrailingCharacters(fPrefixField.getText(), ',');
	res.suffix= Strings.removeTrailingCharacters(fSuffixField.getText(), ',');
	res.prefixkey= fEntry.prefixkey;
	res.suffixkey= fEntry.suffixkey;
	res.kind= 	fEntry.kind;
	return res;
}
 
Example #23
Source File: JavaHistoryActionImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
static String trimTextBlock(String content, String delimiter, IJavaProject currentProject) {
	if (content != null) {
		String[] lines= Strings.convertIntoLines(content);
		if (lines != null) {
			Strings.trimIndentation(lines, currentProject);
			return Strings.concatenate(lines, delimiter);
		}
	}
	return null;
}
 
Example #24
Source File: JavaElementLabels.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the label of a classpath container.
 * The returned label is BiDi-processed with {@link TextProcessor#process(String, String)}.
 *
 * @param containerPath the path of the container
 * @param project the project the container is resolved in
 * @return the label of the classpath container
 * @throws JavaModelException when resolving of the container failed
 */
public static String getContainerEntryLabel(IPath containerPath, IJavaProject project) throws JavaModelException {
	IClasspathContainer container= JavaCore.getClasspathContainer(containerPath, project);
	if (container != null) {
		return Strings.markLTR(container.getDescription());
	}
	ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(containerPath.segment(0));
	if (initializer != null) {
		return Strings.markLTR(initializer.getDescription(containerPath, project));
	}
	return BasicElementLabels.getPathLabel(containerPath, false);
}
 
Example #25
Source File: JavaElementLabels.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the styled label of a classpath container.
 * The returned label is BiDi-processed with {@link TextProcessor#process(String, String)}.
 *
 * @param containerPath the path of the container
 * @param project the project the container is resolved in
 * @return the label of the classpath container
 *
 * @since 3.4
 */
public static StyledString getStyledContainerEntryLabel(IPath containerPath, IJavaProject project) {
	try {
		IClasspathContainer container= JavaCore.getClasspathContainer(containerPath, project);
		String description= null;
		if (container != null) {
			description= container.getDescription();
		}
		if (description == null) {
			ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(containerPath.segment(0));
			if (initializer != null) {
				description= initializer.getDescription(containerPath, project);
			}
		}
		if (description != null) {
			StyledString str= new StyledString(description);
			if (containerPath.segmentCount() > 0 && JavaRuntime.JRE_CONTAINER.equals(containerPath.segment(0))) {
				int index= description.indexOf('[');
				if (index != -1) {
					str.setStyle(index, description.length() - index, DECORATIONS_STYLE);
				}
			}
			return Strings.markLTR(str);
		}
	} catch (JavaModelException e) {
		// ignore
	}
	return new StyledString(BasicElementLabels.getPathLabel(containerPath, false));
}
 
Example #26
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 #27
Source File: GetterSetterCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void evaluateProposals(IType type, String prefix, int offset, int length, int relevance, Set<String> suggestedMethods, Collection<IJavaCompletionProposal> result) throws CoreException {
	if (prefix.length() == 0) {
		relevance--;
	}

	IField[] fields= type.getFields();
	IMethod[] methods= type.getMethods();
	for (int i= 0; i < fields.length; i++) {
		IField curr= fields[i];
		if (!JdtFlags.isEnum(curr)) {
			String getterName= GetterSetterUtil.getGetterName(curr, null);
			if (Strings.startsWithIgnoreCase(getterName, prefix) && !hasMethod(methods, getterName)) {
				suggestedMethods.add(getterName);
				int getterRelevance= relevance;
				if (JdtFlags.isStatic(curr) && JdtFlags.isFinal(curr))
					getterRelevance= relevance - 1;
				result.add(new GetterSetterCompletionProposal(curr, offset, length, true, getterRelevance));
			}

			if (!JdtFlags.isFinal(curr)) {
				String setterName= GetterSetterUtil.getSetterName(curr, null);
				if (Strings.startsWithIgnoreCase(setterName, prefix) && !hasMethod(methods, setterName)) {
					suggestedMethods.add(setterName);
					result.add(new GetterSetterCompletionProposal(curr, offset, length, false, relevance));
				}
			}
		}
	}
}
 
Example #28
Source File: JavaSourceHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the trimmed source lines.
 *
 * @param source the source string, could be <code>null</code>
 * @param javaElement the java element
 * @return the trimmed source lines or <code>null</code>
 */
private String[] getTrimmedSource(String source, IJavaElement javaElement) {
	if (source == null)
		return null;
	source= removeLeadingComments(source);
	String[] sourceLines= Strings.convertIntoLines(source);
	Strings.trimIndentation(sourceLines, javaElement.getJavaProject());
	return sourceLines;
}
 
Example #29
Source File: JavaSourceHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Deprecated
public String getHoverInfo(ITextViewer textViewer, IRegion region) {
	IJavaElement[] result= getJavaElementsAt(textViewer, region);

	fUpwardShiftInLines= 0;
	fBracketHoverStatus= null;

	if (result == null || result.length == 0) {
		return getBracketHoverInfo(textViewer, region);
	}

	if (result.length > 1)
		return null;

	IJavaElement curr= result[0];
	if ((curr instanceof IMember || curr instanceof ILocalVariable || curr instanceof ITypeParameter) && curr instanceof ISourceReference) {
		try {
			String source= ((ISourceReference) curr).getSource();

			String[] sourceLines= getTrimmedSource(source, curr);
			if (sourceLines == null)
				return null;

			String delim= StubUtility.getLineDelimiterUsed(curr);
			source= Strings.concatenate(sourceLines, delim);

			return source;
		} catch (JavaModelException ex) {
			//do nothing
		}
	}
	return null;
}
 
Example #30
Source File: CompletionProposalLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
StyledString createSimpleLabelWithType(CompletionProposal proposal) {
	StyledString buf= new StyledString();
	buf.append(proposal.getCompletion());
	char[] typeName= Signature.getSignatureSimpleName(proposal.getSignature());
	if (typeName.length > 0) {
		buf.append(VAR_TYPE_SEPARATOR);
		buf.append(typeName);
	}
	return Strings.markJavaElementLabelLTR(buf);
}