Java Code Examples for org.eclipse.jface.text.TextUtilities#getPartition()

The following examples show how to use org.eclipse.jface.text.TextUtilities#getPartition() . 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: AbstractPartitionDoubleClickSelector.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected IRegion findExtendedDoubleClickSelection(IDocument document, int offset) {
	IRegion match= super.findExtendedDoubleClickSelection(document, offset);
	if (match != null)
		return match;

	try {
		ITypedRegion region= TextUtilities.getPartition(document, fPartitioning, offset, true);
		if (offset == region.getOffset() + 1 || offset == region.getOffset() + region.getLength() - 1) {
			return getSelectedRegion(document, region);
		}
	} catch (BadLocationException e) {
		return null;
	}
	return null;
}
 
Example 2
Source File: RemoveBlockCommentHandler.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
private ITypedRegion searchCommentStart(IDocument doc, int pos, int addLines) throws BadLocationException {
    int lnum = doc.getLineOfOffset(pos);
    lnum += addLines;
    if (lnum < doc.getNumberOfLines()) {
        IRegion reg = doc.getLineInformation(lnum);
        String line = doc.get(reg.getOffset(), reg.getLength());
        for (int i = addLines > 0 ? 0 : pos - reg.getOffset(); i < line.length(); ++i) {
            if (line.charAt(i) == '(' && 
                i+1 < line.length() && 
                line.charAt(i+1) == '*')
            {
                ITypedRegion partition = TextUtilities.getPartition(doc, IModulaPartitions.M2_PARTITIONING, 
                        reg.getOffset() + i, false);
                if (partition.getType().equals(IModulaPartitions.M2_CONTENT_TYPE_BLOCK_COMMENT)) {
                    return partition;
                }
            }
        }
    }
    return null;
}
 
Example 3
Source File: JSDocAutoIndentStrategy.java    From typescript.java with MIT License 6 votes vote down vote up
private String createMethodTags(IDocument document, DocumentCommand command, String indentation,
		String lineDelimiter, IFunction method) throws CoreException, BadLocationException {
	IRegion partition = TextUtilities.getPartition(document, fPartitioning, command.offset, false);
	IFunction inheritedMethod = getInheritedMethod(method);
	String comment = CodeGeneration.getMethodComment(method, inheritedMethod, lineDelimiter);
	if (comment != null) {
		comment = comment.trim();
		boolean javadocComment = comment.startsWith("/**"); //$NON-NLS-1$
		if (!isFirstComment(document, command, method, javadocComment))
			return null;
		boolean isJavaDoc = partition.getLength() >= 3 && document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$
		if (javadocComment == isJavaDoc) {
			return prepareTemplateComment(comment, indentation, method.getJavaScriptProject(), lineDelimiter);
		}
	}
	return null;
}
 
Example 4
Source File: JavaChangeHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the partition type of the document displayed in <code>viewer</code> at <code>startLine</code>.

 * @param viewer the viewer
 * @param startLine the line in the viewer
 * @return the partition type at the start of <code>startLine</code>, or <code>IDocument.DEFAULT_CONTENT_TYPE</code> if none can be detected
 */
private String getPartition(ISourceViewer viewer, int startLine) {
	if (viewer == null)
		return null;
	IDocument doc= viewer.getDocument();
	if (doc == null)
		return null;
	if (startLine <= 0)
		return IDocument.DEFAULT_CONTENT_TYPE;
	try {
		ITypedRegion region= TextUtilities.getPartition(doc, fPartitioning, doc.getLineOffset(startLine) - 1, true);
		return region.getType();
	} catch (BadLocationException e) {
	}
	return IDocument.DEFAULT_CONTENT_TYPE;
}
 
Example 5
Source File: JavaDocAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private String createMethodTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IMethod method)
	throws CoreException, BadLocationException
{
	IRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset, false);
	IMethod inheritedMethod= getInheritedMethod(method);
	String comment= CodeGeneration.getMethodComment(method, inheritedMethod, lineDelimiter);
	if (comment != null) {
		comment= comment.trim();
		boolean javadocComment= comment.startsWith("/**"); //$NON-NLS-1$
		if (!isFirstComment(document, command, method, javadocComment))
			return null;
		boolean isJavaDoc= partition.getLength() >= 3 && document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$
		if (javadocComment == isJavaDoc) {
			return prepareTemplateComment(comment, indentation, method.getJavaProject(), lineDelimiter);
		}
	}
	return null;
}
 
Example 6
Source File: JsniParser.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public static ITypedRegion getEnclosingJsniRegion(ITextSelection selection,
    IDocument document) {
  try {
    ITypedRegion region = TextUtilities.getPartition(document,
        GWTPartitions.GWT_PARTITIONING, selection.getOffset(), false);

    if (region.getType().equals(GWTPartitions.JSNI_METHOD)) {
      int regionEnd = region.getOffset() + region.getLength();
      int selectionEnd = selection.getOffset() + selection.getLength();

      // JSNI region should entirely contain the selection
      if (region.getOffset() <= selection.getOffset()
          && regionEnd >= selectionEnd) {
        return region;
      }
    }
  } catch (BadLocationException e) {
    GWTPluginLog.logError(e);
  }

  return null;
}
 
Example 7
Source File: PartitionDoubleClickSelector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected IRegion findExtendedDoubleClickSelection(IDocument document, int offset) {
	IRegion match= super.findExtendedDoubleClickSelection(document, offset);
	if (match != null)
		return match;

	try {
		ITypedRegion region= TextUtilities.getPartition(document, fPartitioning, offset, true);
		if (offset == region.getOffset() + fHitDelta || offset == region.getOffset() + region.getLength() - fHitDelta) {
			if (fLeftBorder == 0 && fRightBorder == 0)
				return region;
			if (fRightBorder == -1) {
				String delimiter= document.getLineDelimiter(document.getLineOfOffset(region.getOffset() + region.getLength() - 1));
				if (delimiter == null)
					fRightBorder= 0;
				else
					fRightBorder= delimiter.length();
			}
			return new Region(region.getOffset() + fLeftBorder, region.getLength() - fLeftBorder - fRightBorder);
		}
	} catch (BadLocationException e) {
		return null;
	}
	return null;
}
 
Example 8
Source File: PairedBracketsMatcher.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
protected ITypedRegion getPartition(IDocument document, int pos) {
        if (fCachedListenedDocument == null) {
            fCachedListenedDocument = document;
            fCachedListenedDocument.addDocumentListener(fDocumentListener);
        }
        if (fCachedPartition != null) {
            int offs = fCachedPartition.getOffset();
            if (offs <= pos && pos < offs + fCachedPartition.getLength()) {

//                /////---- dbg:
//                try {
//                    ITypedRegion pp = TextUtilities.getPartition(document, fPartitioning, pos, false);
//                    if (!pp.getType().equals(fCachedPartition.getType())) {
//                        System.out.println("****** Partition " + pp.getType() + 
//                                           "(" + pp.getOffset() + 
//                                           " / " + pp.getLength() + 
//                                           ") is cached as '" + fCachedPartition.getType() + 
//                                           "(" + fCachedPartition.getOffset() + 
//                                           " / " + fCachedPartition.getLength() + ")");
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                /////----
                
                return fCachedPartition;
            }
        }
        try {
            fCachedPartition= TextUtilities.getPartition(document, fPartitioning, pos, false);
        } catch (BadLocationException e) {
            fCachedPartition= null;
        }
        return fCachedPartition;
    }
 
Example 9
Source File: HackDefaultCharacterPairMatcher.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns partition information about the region containing the
 * specified position.
 * 
 * @param pos a position within this document.
 * @return positioning information about the region containing the
 *   position
 */
private ITypedRegion getPartition(int pos) {
	if (fCachedPartition == null || !contains(fCachedPartition, pos)) {
		Assert.isTrue(pos >= 0 && pos <= fDocument.getLength());
		try {
			fCachedPartition= TextUtilities.getPartition(fDocument, fPartitioning, pos, false);
		} catch (BadLocationException e) {
			fCachedPartition= null;
		}
	}
	return fCachedPartition;
}
 
Example 10
Source File: JavaDocAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Guesses if the command operates within a newly created Javadoc comment or not.
 * If in doubt, it will assume that the Javadoc is new.
 *
 * @param document the document
 * @param commandOffset the command offset
 * @return <code>true</code> if the comment should be closed, <code>false</code> if not
 */
private boolean isNewComment(IDocument document, int commandOffset) {

	try {
		int lineIndex= document.getLineOfOffset(commandOffset) + 1;
		if (lineIndex >= document.getNumberOfLines())
			return true;

		IRegion line= document.getLineInformation(lineIndex);
		ITypedRegion partition= TextUtilities.getPartition(document, fPartitioning, commandOffset, false);
		int partitionEnd= partition.getOffset() + partition.getLength();
		if (line.getOffset() >= partitionEnd)
			return false;

		if (document.getLength() == partitionEnd)
			return true; // partition goes to end of document - probably a new comment

		String comment= document.get(partition.getOffset(), partition.getLength());
		if (comment.indexOf("/*", 2) != -1) //$NON-NLS-1$
			return true; // enclosed another comment -> probably a new comment

		return false;

	} catch (BadLocationException e) {
		return false;
	}
}
 
Example 11
Source File: SmartSemicolonAutoEditStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a position in the first java partition after the last non-empty and non-comment partition.
 * There is no non-whitespace from the returned position to the end of the partition it is contained in.
 *
 * @param document the document being modified
 * @param line the line under investigation
 * @param offset the caret offset into <code>line</code>
 * @param partitioning the document partitioning
 * @return the position of the next Java partition, or the end of <code>line</code>
 */
private static int nextPartitionOrLineEnd(IDocument document, ITextSelection line, int offset, String partitioning) {
	// run relative to document
	final int docOffset= offset + line.getOffset();
	final int eol= line.getOffset() + line.getLength();
	int nextPartitionPos= eol; // init with line end
	int validPosition= docOffset;

	try {
		ITypedRegion partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos, true);
		validPosition= getValidPositionForPartition(document, partition, eol);
		while (validPosition == -1) {
			nextPartitionPos= partition.getOffset() - 1;
			if (nextPartitionPos < docOffset) {
				validPosition= docOffset;
				break;
			}
			partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos, false);
			validPosition= getValidPositionForPartition(document, partition, eol);
		}
	} catch (BadLocationException e) {
	}

	validPosition= Math.max(validPosition, docOffset);
	// make relative to line
	validPosition -= line.getOffset();
	return validPosition;
}
 
Example 12
Source File: SmartSemicolonAutoEditStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
 *
 * @param document the document being modified
 * @param position the position to be checked
 * @param partitioning the document partitioning
 * @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
 */
private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
	Assert.isTrue(position >= 0);
	Assert.isTrue(position <= document.getLength());

	try {
		// don't use getPartition2 since we're interested in the scanned character's partition
		ITypedRegion region= TextUtilities.getPartition(document, partitioning, position, false);
		return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);

	} catch (BadLocationException e) {
	}

	return false;
}
 
Example 13
Source File: JavaAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
 *
 * @param document the document being modified
 * @param position the position to be checked
 * @param partitioning the document partitioning
 * @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
 */
private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
	Assert.isTrue(position >= 0);
	Assert.isTrue(position <= document.getLength());

	try {
		ITypedRegion region= TextUtilities.getPartition(document, partitioning, position, false);
		return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);

	} catch (BadLocationException e) {
	}

	return false;
}
 
Example 14
Source File: TypeScriptAutoIndentStrategy.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
 *
 * @param document the document being modified
 * @param position the position to be checked
 * @param partitioning the document partitioning
 * @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
 */
private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
	Assert.isTrue(position >= 0);
	Assert.isTrue(position <= document.getLength());

	try {
		ITypedRegion region= TextUtilities.getPartition(document, partitioning, position, false);
		return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);

	} catch (BadLocationException e) {
	}

	return false;
}
 
Example 15
Source File: JSDocAutoIndentStrategy.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Guesses if the command operates within a newly created javadoc comment or
 * not. If in doubt, it will assume that the javadoc is new.
 *
 * @param document
 *            the document
 * @param commandOffset
 *            the command offset
 * @return <code>true</code> if the comment should be closed,
 *         <code>false</code> if not
 */
private boolean isNewComment(IDocument document, int commandOffset) {

	try {
		int lineIndex = document.getLineOfOffset(commandOffset) + 1;
		if (lineIndex >= document.getNumberOfLines())
			return true;

		IRegion line = document.getLineInformation(lineIndex);
		ITypedRegion partition = TextUtilities.getPartition(document, fPartitioning, commandOffset, false);
		int partitionEnd = partition.getOffset() + partition.getLength();
		if (line.getOffset() >= partitionEnd)
			return false;

		if (document.getLength() == partitionEnd)
			return true; // partition goes to end of document - probably a
							// new comment

		String comment = document.get(partition.getOffset(), partition.getLength());
		if (comment.indexOf("/*", 2) != -1) //$NON-NLS-1$
			return true; // enclosed another comment -> probably a new
							// comment

		return false;

	} catch (BadLocationException e) {
		return false;
	}
}
 
Example 16
Source File: JSDocAutoIndentStrategy.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Returns <code>true</code> if the comment being inserted at
 * <code>command.offset</code> is the first comment (the first javadoc
 * comment if <code>ignoreJavadoc</code> is <code>true</code>) of the given
 * member.
 * <p>
 * see also https://bugs.eclipse.org/bugs/show_bug.cgi?id=55325 (don't add
 * parameters if the member already has a comment)
 * </p>
 */
private boolean isFirstComment(IDocument document, DocumentCommand command, IMember member,
		boolean ignoreNonJavadoc) throws BadLocationException, JavaScriptModelException {
	IRegion partition = TextUtilities.getPartition(document, fPartitioning, command.offset, false);
	ISourceRange sourceRange = member.getSourceRange();
	if (sourceRange == null || sourceRange.getOffset() != partition.getOffset())
		return false;
	int srcOffset = sourceRange.getOffset();
	int srcLength = sourceRange.getLength();
	int nameRelativeOffset = member.getNameRange().getOffset() - srcOffset;
	int partitionRelativeOffset = partition.getOffset() - srcOffset;
	String token = ignoreNonJavadoc ? "/**" : "/*"; //$NON-NLS-1$ //$NON-NLS-2$
	return document.get(srcOffset, srcLength).lastIndexOf(token, nameRelativeOffset) == partitionRelativeOffset;
}
 
Example 17
Source File: ModulaDoubleClickStrategy.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected IRegion findExtendedDoubleClickSelection(IDocument document,
		int offset) {
	try {
		ITypedRegion region = TextUtilities.getPartition(document, IModulaPartitions.M2_PARTITIONING, offset, true);
		if (region.getType() == IModulaPartitions.M2_CONTENT_TYPE_DEFAULT) {
			_XdsFlexScanner lexer = new _XdsFlexScanner();
			IRegion lineReg = document.getLineInformationOfOffset(offset);
			lexer.reset(document.get(lineReg.getOffset(), lineReg.getLength()));

			List<TokenRegion> candidates = new ArrayList<>();
			TokenType tokenType;
			while ( ( tokenType = lexer.nextToken()) != ModulaTokenTypes.EOF) {
				if (ModulaTokenTypes.WHITE_SPACE.getDesignator().equals(tokenType.getDesignator())) {
					continue;
				}
				int tokenOffset = lineReg.getOffset() + lexer.getTokenOffset();
				if (tokenOffset <= offset && offset <= tokenOffset + lexer.yylength()) {
					candidates.add(new TokenRegion(new Region(tokenOffset, lexer.yylength()), tokenType));
				}
			}
			if (candidates.size() > 0){
				if (candidates.size() > 1){
					Collections.sort(candidates, new TokenRegionComparator());
				}
				return candidates.get(candidates.size() - 1);
			}
		}
	} catch (BadLocationException | IOException e) {
		LogHelper.logError(e);
	}
	return super.findExtendedDoubleClickSelection(document, offset);
}
 
Example 18
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void run() {

	final JavaSourceViewer viewer= (JavaSourceViewer) getSourceViewer();
	if (viewer.isEditable() && ElementValidator.check(getInputJavaElement(), getSite().getShell(), JavaEditorMessages.JavaEditor_FormatElementDialog_label, true)) {

		final Point selection= viewer.rememberSelection();
		try {
			viewer.setRedraw(false);

			boolean emptySelection= selection.y == 0;
			if (emptySelection) {
				final ITypedRegion partition= TextUtilities.getPartition(viewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, selection.x, true);
				String type= partition.getType();
				if (IJavaPartitions.JAVA_DOC.equals(type) || IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(type) || IJavaPartitions.JAVA_SINGLE_LINE_COMMENT.equals(type)) {
					viewer.setSelectedRange(partition.getOffset(), partition.getLength());
					viewer.doOperation(ISourceViewer.FORMAT);
					return;
				}
			}
			final IJavaElement element= getElementAt(selection.x, true);
			if (element != null && element.exists()) {
				try {
					final int kind= element.getElementType();
					if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) {

						final ISourceReference reference= (ISourceReference) element;
						final ISourceRange range= reference.getSourceRange();
						final ISourceRange nameRange= reference.getNameRange();
						final boolean seletionInNameRange= nameRange != null && selection.x >= nameRange.getOffset()
								&& selection.x + selection.y <= nameRange.getOffset() + nameRange.getLength();
						if (range != null && (emptySelection || seletionInNameRange))
							viewer.setSelectedRange(range.getOffset(), range.getLength());
					}
				} catch (JavaModelException exception) {
					// Should not happen
				}
			}
			viewer.doOperation(ISourceViewer.FORMAT);
		} catch (BadLocationException e) {
			// Cannot happen
		} finally {

			viewer.setRedraw(true);
			viewer.restoreSelection();
		}
	}
}
 
Example 19
Source File: CharacterPairMatcher.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
protected ITypedRegion getPartition(IDocument doc, int charOffset) throws BadLocationException
{
	return TextUtilities.getPartition(doc, fPartitioning, charOffset, false);
}
 
Example 20
Source File: JavaDocAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns <code>true</code> if the comment being inserted at
 * <code>command.offset</code> is the first comment (the first
 * Javadoc comment if <code>ignoreJavadoc</code> is
 * <code>true</code>) of the given member.
 * <p>
 * see also https://bugs.eclipse.org/bugs/show_bug.cgi?id=55325 (don't add parameters if the member already has a comment)
 * </p>
 * @param document the document
 * @param command the document command
 * @param member the Java member
 * @param ignoreNonJavadoc <code>true</code> if non Javadoc should be ignored
 * @return <code>true</code> if it is the first comment
 * @throws JavaModelException if accessing the Java model fails
 * @throws BadLocationException if accessing the document fails
 */
private boolean isFirstComment(IDocument document, DocumentCommand command, IMember member, boolean ignoreNonJavadoc) throws BadLocationException, JavaModelException {
	IRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset, false);
	ISourceRange sourceRange= member.getSourceRange();
	if (sourceRange == null)
		return false;
	int srcOffset= sourceRange.getOffset();
	int srcLength= sourceRange.getLength();
	int nameRelativeOffset= member.getNameRange().getOffset() - srcOffset;
	int partitionRelativeOffset= partition.getOffset() - srcOffset;
	String token= ignoreNonJavadoc ? "/**" :  "/*"; //$NON-NLS-1$ //$NON-NLS-2$
	return document.get(srcOffset, srcLength).lastIndexOf(token, nameRelativeOffset) == partitionRelativeOffset;
}