Java Code Examples for org.eclipse.jface.text.Position#setLength()

The following examples show how to use org.eclipse.jface.text.Position#setLength() . 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: IndentFoldingStrategy.java    From typescript.java with MIT License 6 votes vote down vote up
/**
 * This is the default behavior for updating a dirtied IndexedRegion. This
 * function can be overridden if slightly different functionality is
 * required in a specific instance of this class.
 * 
 * @param existingAnnotationsIter
 *            the existing annotations that need to be updated based on the
 *            given dirtied IndexRegion
 * @param dirtyRegion
 *            the IndexedRegion that caused the annotations need for
 *            updating
 * @param modifications
 *            the list of annotations to be modified
 * @param deletions
 *            the list of annotations to be deleted
 */
protected void updateAnnotations(Annotation existingAnnotation, Position newPos, Map additions, List modifications,
		List deletions) {
	if (existingAnnotation instanceof FoldingAnnotation) {
		FoldingAnnotation foldingAnnotation = (FoldingAnnotation) existingAnnotation;
		// Position newPos = null; //calcNewFoldPosition(null);

		// if a new position can be calculated then update the position of
		// the annotation,
		// else the annotation needs to be deleted
		if (newPos != null && newPos.length > 0 && projectionAnnotationModel != null) {
			Position oldPos = projectionAnnotationModel.getPosition(foldingAnnotation);
			// only update the position if we have to
			if (!newPos.equals(oldPos)) {
				oldPos.setOffset(newPos.offset);
				oldPos.setLength(newPos.length);
				modifications.add(foldingAnnotation);
			}
		} else {
			deletions.add(foldingAnnotation);
		}
	}
}
 
Example 2
Source File: NLSSearchResultRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Finds the key defined by the given match. The assumption is that the key is the only argument
 * and it is a string literal i.e. quoted ("...") or a string constant i.e. 'static final
 * String' defined in the same class.
 * 
 * @param keyPositionResult reference parameter: will be filled with the position of the found
 *            key
 * @param enclosingElement enclosing java element
 * @return a string denoting the key, {@link #NO_KEY} if no key can be found and
 *         <code>null</code> otherwise
 * @throws CoreException if a problem occurs while accessing the <code>enclosingElement</code>
 */
private String findKey(Position keyPositionResult, IJavaElement enclosingElement) throws CoreException {
	ICompilationUnit unit= (ICompilationUnit)enclosingElement.getAncestor(IJavaElement.COMPILATION_UNIT);
	if (unit == null)
		return null;

	String source= unit.getSource();
	if (source == null)
		return null;

	IJavaProject javaProject= unit.getJavaProject();
	IScanner scanner= null;
	if (javaProject != null) {
		String complianceLevel= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
		String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
		scanner= ToolFactory.createScanner(false, false, false, sourceLevel, complianceLevel);
	} else {
		scanner= ToolFactory.createScanner(false, false, false, false);
	}
	scanner.setSource(source.toCharArray());
	scanner.resetTo(keyPositionResult.getOffset() + keyPositionResult.getLength(), source.length());

	try {
		if (scanner.getNextToken() != ITerminalSymbols.TokenNameDOT)
			return null;

		if (scanner.getNextToken() != ITerminalSymbols.TokenNameIdentifier)
			return null;

		String src= new String(scanner.getCurrentTokenSource());
		int tokenStart= scanner.getCurrentTokenStartPosition();
		int tokenEnd= scanner.getCurrentTokenEndPosition();

		if (scanner.getNextToken() == ITerminalSymbols.TokenNameLPAREN) {
			// Old school
			// next must be key string. Ignore methods which do not take a single String parameter (Bug 295040).
			int nextToken= scanner.getNextToken();
			if (nextToken != ITerminalSymbols.TokenNameStringLiteral && nextToken != ITerminalSymbols.TokenNameIdentifier)
				return null;

			tokenStart= scanner.getCurrentTokenStartPosition();
			tokenEnd= scanner.getCurrentTokenEndPosition();
			int token;
			while ((token= scanner.getNextToken()) == ITerminalSymbols.TokenNameDOT) {
				if ((nextToken= scanner.getNextToken()) != ITerminalSymbols.TokenNameIdentifier) {
						return null;
				}
				tokenStart= scanner.getCurrentTokenStartPosition();
				tokenEnd= scanner.getCurrentTokenEndPosition();
			}
			if (token != ITerminalSymbols.TokenNameRPAREN)
				return null;
			
			if (nextToken == ITerminalSymbols.TokenNameStringLiteral) {
				keyPositionResult.setOffset(tokenStart + 1);
				keyPositionResult.setLength(tokenEnd - tokenStart - 1);
				return source.substring(tokenStart + 1, tokenEnd);
			} else if (nextToken == ITerminalSymbols.TokenNameIdentifier) {
				keyPositionResult.setOffset(tokenStart);
				keyPositionResult.setLength(tokenEnd - tokenStart + 1);
				IType parentClass= (IType)enclosingElement.getAncestor(IJavaElement.TYPE);
				IField[] fields= parentClass.getFields();
				String identifier= source.substring(tokenStart, tokenEnd + 1);
				for (int i= 0; i < fields.length; i++) {
					if (fields[i].getElementName().equals(identifier)) {
						if (!Signature.getSignatureSimpleName(fields[i].getTypeSignature()).equals("String")) //$NON-NLS-1$
							return null;
						Object obj= fields[i].getConstant();
						return obj instanceof String ? ((String)obj).substring(1, ((String)obj).length() - 1) : NO_KEY;
					}
				}
			}
			return NO_KEY;
		} else {
			IJavaElement[] keys= unit.codeSelect(tokenStart, tokenEnd - tokenStart + 1);

			// an interface can't be a key
			if (keys.length == 1 && keys[0].getElementType() == IJavaElement.TYPE && ((IType) keys[0]).isInterface())
				return null;

			keyPositionResult.setOffset(tokenStart);
			keyPositionResult.setLength(tokenEnd - tokenStart + 1);
			return src;
		}
	} catch (InvalidInputException e) {
		throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
	}
}
 
Example 3
Source File: DefaultJavaFoldingStructureProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void update(FoldingStructureComputationContext ctx) {
if (ctx == null)
	return;

Map<JavaProjectionAnnotation, Position> additions= new HashMap<JavaProjectionAnnotation, Position>();
List<JavaProjectionAnnotation> deletions= new ArrayList<JavaProjectionAnnotation>();
List<JavaProjectionAnnotation> updates= new ArrayList<JavaProjectionAnnotation>();

computeFoldingStructure(ctx);
Map<JavaProjectionAnnotation, Position> newStructure= ctx.fMap;
Map<IJavaElement, List<Tuple>> oldStructure= computeCurrentStructure(ctx);

Iterator<JavaProjectionAnnotation> e= newStructure.keySet().iterator();
while (e.hasNext()) {
	JavaProjectionAnnotation newAnnotation= e.next();
	Position newPosition= newStructure.get(newAnnotation);

	IJavaElement element= newAnnotation.getElement();
	/*
	 * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=130472 and
	 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=127445 In the presence of syntax
	 * errors, anonymous types may have a source range offset of 0. When such a situation is
	 * encountered, we ignore the proposed folding range: if no corresponding folding range
	 * exists, it is silently ignored; if there *is* a matching folding range, we ignore the
	 * position update and keep the old range, in order to keep the folding structure
	 * stable.
	 */
	boolean isMalformedAnonymousType= newPosition.getOffset() == 0 && element.getElementType() == IJavaElement.TYPE && isInnerType((IType) element);
	List<Tuple> annotations= oldStructure.get(element);
	if (annotations == null) {
		if (!isMalformedAnonymousType)
			additions.put(newAnnotation, newPosition);
	} else {
		Iterator<Tuple> x= annotations.iterator();
		boolean matched= false;
		while (x.hasNext()) {
			Tuple tuple= x.next();
			JavaProjectionAnnotation existingAnnotation= tuple.annotation;
			Position existingPosition= tuple.position;
			if (newAnnotation.isComment() == existingAnnotation.isComment()) {
				boolean updateCollapsedState= ctx.allowCollapsing() && existingAnnotation.isCollapsed() != newAnnotation.isCollapsed();
				if (!isMalformedAnonymousType && existingPosition != null && (!newPosition.equals(existingPosition) || updateCollapsedState)) {
					existingPosition.setOffset(newPosition.getOffset());
					existingPosition.setLength(newPosition.getLength());
					if (updateCollapsedState)
						if (newAnnotation.isCollapsed())
							existingAnnotation.markCollapsed();
						else
							existingAnnotation.markExpanded();
					updates.add(existingAnnotation);
				}
				matched= true;
				x.remove();
				break;
			}
		}
		if (!matched)
			additions.put(newAnnotation, newPosition);

		if (annotations.isEmpty())
			oldStructure.remove(element);
	}
}

Iterator<List<Tuple>> iter= oldStructure.values().iterator();
while (iter.hasNext()) {
	List<Tuple> list= iter.next();
	int size= list.size();
	for (int i= 0; i < size; i++)
		deletions.add(list.get(i).annotation);
}

match(deletions, additions, updates, ctx);

Annotation[] deletedArray= deletions.toArray(new Annotation[deletions.size()]);
Annotation[] changedArray= updates.toArray(new Annotation[updates.size()]);
ctx.getModel().modifyAnnotations(deletedArray, additions, changedArray);

ctx.fScanner.setSource(null);
  }
 
Example 4
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Overrides the default implementation to handle {@link IJavaAnnotation}.
 * </p>
 *
 * @param offset the region offset
 * @param length the region length
 * @param forward <code>true</code> for forwards, <code>false</code> for backward
 * @param annotationPosition the position of the found annotation
 * @return the found annotation
 * @since 3.2
 */
@Override
protected Annotation findAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {

	Annotation nextAnnotation= null;
	Position nextAnnotationPosition= null;
	Annotation containingAnnotation= null;
	Position containingAnnotationPosition= null;
	boolean currentAnnotation= false;

	IDocument document= getDocumentProvider().getDocument(getEditorInput());
	int endOfDocument= document.getLength();
	int distance= Integer.MAX_VALUE;

	IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
	if (model == null)
		return null;

	Iterator<Annotation> e= new JavaAnnotationIterator(model.getAnnotationIterator(), true);
	while (e.hasNext()) {
		Annotation a= e.next();
		if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget(a))
			continue;

		Position p= model.getPosition(a);
		if (p == null)
			continue;

		if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
			if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) {
				containingAnnotation= a;
				containingAnnotationPosition= p;
				currentAnnotation= p.length == length;
			}
		} else {
			int currentDistance= 0;

			if (forward) {
				currentDistance= p.getOffset() - offset;
				if (currentDistance < 0)
					currentDistance= endOfDocument + currentDistance;

				if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
					distance= currentDistance;
					nextAnnotation= a;
					nextAnnotationPosition= p;
				}
			} else {
				currentDistance= offset + length - (p.getOffset() + p.length);
				if (currentDistance < 0)
					currentDistance= endOfDocument + currentDistance;

				if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
					distance= currentDistance;
					nextAnnotation= a;
					nextAnnotationPosition= p;
				}
			}
		}
	}
	if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
		annotationPosition.setOffset(containingAnnotationPosition.getOffset());
		annotationPosition.setLength(containingAnnotationPosition.getLength());
		return containingAnnotation;
	}
	if (nextAnnotationPosition != null) {
		annotationPosition.setOffset(nextAnnotationPosition.getOffset());
		annotationPosition.setLength(nextAnnotationPosition.getLength());
	}

	return nextAnnotation;
}
 
Example 5
Source File: ParameterGuessingProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the completion string. Offsets and Lengths are set to the offsets and lengths of the
 * parameters.
 * 
 * @return the completion string
 * @throws JavaModelException if parameter guessing failed
 */
private String computeGuessingCompletion() throws JavaModelException {

	StringBuffer buffer= new StringBuffer();
	appendMethodNameReplacement(buffer);

	FormatterPrefs prefs= getFormatterPrefs();

	setCursorPosition(buffer.length());

	if (prefs.afterOpeningParen)
		buffer.append(SPACE);

	char[][] parameterNames= fProposal.findParameterNames(null);

	fChoices= guessParameters(parameterNames);
	int count= fChoices.length;
	int replacementOffset= getReplacementOffset();

	for (int i= 0; i < count; i++) {
		if (i != 0) {
			if (prefs.beforeComma)
				buffer.append(SPACE);
			buffer.append(COMMA);
			if (prefs.afterComma)
				buffer.append(SPACE);
		}

		ICompletionProposal proposal= fChoices[i][0];
		String argument= proposal.getDisplayString();

		Position position= fPositions[i];
		position.setOffset(replacementOffset + buffer.length());
		position.setLength(argument.length());

		if (proposal instanceof JavaCompletionProposal) // handle the "unknown" case where we only insert a proposal.
			((JavaCompletionProposal) proposal).setReplacementOffset(replacementOffset + buffer.length());
		buffer.append(argument);
	}

	if (prefs.beforeClosingParen)
		buffer.append(SPACE);

	buffer.append(RPAREN);

	if (canAutomaticallyAppendSemicolon())
		buffer.append(SEMICOLON);

	return buffer.toString();
}