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

The following examples show how to use org.eclipse.jface.text.IDocument#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: AbstractLexemeProvider.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Convert the partition that contains the given offset into a list of lexemes. If the includeOffset is not within
 * the partition found at offset, then the range is extended to include it
 * 
 * @param document
 * @param offset
 * @param includeOffset
 * @param scanner
 */
protected AbstractLexemeProvider(IDocument document, int offset, int includeOffset, U scanner)
{
	int start = offset;
	int end = offset;

	try
	{
		ITypedRegion partition = document.getPartition(offset);

		start = partition.getOffset();
		end = start + partition.getLength();

		start = Math.max(0, Math.min(start, includeOffset));
		end = Math.min(Math.max(end, includeOffset), document.getLength());
	}
	catch (BadLocationException e)
	{
	}

	this.createLexemeList(document, start, end - start, scanner);
}
 
Example 2
Source File: XtextAutoEditStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected String getCurrentRuleUptoOffset(int offset, IDocument doc) throws BadLocationException {
	ITypedRegion currentPartition = doc.getPartition(offset);
	String partitionType = currentPartition.getType();
	String currentSegment = doc.get(currentPartition.getOffset(), offset - currentPartition.getOffset());
	StringBuilder ruleAsString = new StringBuilder(); 
	while(currentSegment.indexOf(';') == -1) {
		ruleAsString.insert(0, currentSegment);
		do {
			if(currentPartition.getOffset()==0) {
				return ruleAsString.toString();
			}
			currentPartition = doc.getPartition(currentPartition.getOffset()-1);
			currentSegment = doc.get(currentPartition.getOffset(), currentPartition.getLength());
		} while(!partitionType.equals(currentPartition.getType()));
	}
	ruleAsString.insert(0, currentSegment.substring(currentSegment.lastIndexOf(';') + 1));
	return ruleAsString.toString();
}
 
Example 3
Source File: DocumentUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * searches backwards for the given string within the same partition type
 * @return the region of the match or <code>null</code> if no match were found
 * @since 2.4
 */
public IRegion searchBackwardsInSamePartition(String toFind, String documentText, IDocument document, int endOffset) throws BadLocationException {
	if (endOffset < 0) {
		return null;
	}
	int length = toFind.length();
	String text = preProcessSearchString(documentText);
	ITypedRegion partition = document.getPartition(endOffset);
	int indexOf = text.lastIndexOf(toFind, endOffset - length);
	while (indexOf >= 0) {
		ITypedRegion partition2 = document.getPartition(indexOf);
		if (partition2.getType().equals(partition.getType())) {
			return new Region(indexOf, length);
		}
		indexOf = text.lastIndexOf(toFind, partition2.getOffset() - length);
	}
	String trimmed = toFind.trim();
	if (trimmed.length() > 0 && trimmed.length() != length) {
		return searchBackwardsInSamePartition(trimmed, documentText, document, endOffset);
	}
	return null;
}
 
Example 4
Source File: DocumentUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * searches for the given string within the same partition type
 * 
 * @return the region of the match or <code>null</code> if no match were found
 * @since 2.4
 */
public IRegion searchInSamePartition(String toFind, String documentText, IDocument document, int startOffset)
		throws BadLocationException {
	if (startOffset >= document.getLength()) {
		return null;
	}
	String text = preProcessSearchString(documentText);
	ITypedRegion partition = document.getPartition(startOffset);
	
	int indexOf = text.indexOf(toFind, getOffset(toFind, startOffset));
	while (indexOf >= 0 && indexOf < document.getLength()) {
		ITypedRegion partition2 = document.getPartition(indexOf);
		if (partition2.getType().equals(partition.getType())) {
			return new Region(indexOf, toFind.length());
		}
		indexOf = text.indexOf(toFind, partition2.getOffset() + partition2.getLength());
	}
	String trimmed = toFind.trim();
	if (trimmed.length() > 0 && trimmed.length() != toFind.length()) {
		return searchInSamePartition(trimmed, documentText, document, startOffset);
	}
	return null;
}
 
Example 5
Source File: AbstractEditStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected String getDocumentContent(IDocument document, DocumentCommand command) throws BadLocationException {
	final ITypedRegion partition = document.getPartition(command.offset);
	ITypedRegion[] partitions = document.getDocumentPartitioner().computePartitioning(0, document.getLength());
	Iterable<ITypedRegion> partitionsOfCurrentType = Iterables.filter(Arrays.asList(partitions),
			new Predicate<ITypedRegion>() {
				@Override
				public boolean apply(ITypedRegion input) {
					return input.getType().equals(partition.getType());
				}
			});
	StringBuilder builder = new StringBuilder();
	for (ITypedRegion position : partitionsOfCurrentType) {
		builder.append(document.get(position.getOffset(), position.getLength()));
	}
	return builder.toString();
}
 
Example 6
Source File: ExtendedDocumentInfo.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public QualifiedContentType getContentType(IDocument document, int offset) throws BadLocationException
{
	QualifiedContentType result = new QualifiedContentType(defaultContentType);
	try
	{
		// If we're at the end of the document, back up one char to grab partition when we have bogus zero length
		// partition at EOF.
		if (offset == document.getLength())
		{
			ITypedRegion region = document.getPartition(offset);
			if (region.getLength() == 0 && offset > 0)
			{
				offset = offset - 1;
			}
		}
		// get partition at offset
		String contentType = document.getContentType(offset);
		// grab the top level document type that this partition is a subtype of
		String subdocContentType = contentTypesAssociation.get(contentType);
		if (subdocContentType != null && !subdocContentType.equals(result.getLastPart()))
		{
			// if our content type/scope doesn't have this language level scope at the end, add it to the end
			result = result.subtype(subdocContentType);
		}
		// add partition to end
		return result.subtype(contentType);
	}
	catch (Exception e)
	{
		return result;
	}
}
 
Example 7
Source File: DocumentUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public int findNextOffSetInPartition(IDocument doc, int partitionOffSet, int minIndex) throws BadLocationException {
	ITypedRegion partition = doc.getPartition(partitionOffSet);
	ITypedRegion partition2 = doc.getPartition(minIndex);
	if (partition.getType().equals(partition2.getType()) || partition2.getLength() == 0) {
		return minIndex;
	} else {
		return findNextOffSetInPartition(doc, partitionOffSet, minIndex + partition2.getLength());
	}
}
 
Example 8
Source File: MultiLineTerminalsEditStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * determines the offset of the next ITypedRegion of type {@link IDocument#DEFAULT_CONTENT_TYPE} starting from the given offset  
 * Fix for bug 403812.  
 */
private int findOffsetOfNextDftlContentPartition(IDocument document, int startOffset) throws BadLocationException{
	if (startOffset >= document.getLength()) {
		return startOffset;
	}
	ITypedRegion partition = document.getPartition(startOffset);
	if(IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())){
		return startOffset;
	}else{
		return findOffsetOfNextDftlContentPartition(document,partition.getOffset()+partition.getLength());
	}
}
 
Example 9
Source File: SupressingMLCommentPredicate.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean isInsertClosingBracket(IDocument doc, int offset) throws BadLocationException {
	if (offset >= 2) {
		ITypedRegion prevPartition = doc.getPartition(offset - 1);
		String prevPartitionType = prevPartition.getType();
		if (TerminalsTokenTypeToPartitionMapper.SL_COMMENT_PARTITION.equals(prevPartitionType)) {
			return false;
		}
		if (TokenTypeToPartitionMapper.REG_EX_PARTITION.equals(prevPartitionType)) {
			return prevPartition.getLength() == 1;
		}
	}
	return SingleLineTerminalsStrategy.DEFAULT.isInsertClosingBracket(doc, offset);
}
 
Example 10
Source File: TagUtil.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns null when no match found! Assumes the document has been partitioned via HTML partition scanner
 * 
 * @param document
 * @param offset
 * @param partitionsToSearch
 *            A collection of the string partition names to search for tags. Optimization to avoid looking in non
 *            HTML/XML tags!
 * @return
 */
public static IRegion findMatchingTag(IDocument document, int offset, Collection<String> partitionsToSearch)
{
	try
	{
		ITypedRegion region = document.getPartition(offset);
		if (!partitionsToSearch.contains(region.getType()))
		{
			return null;
		}
		String src = document.get(region.getOffset(), region.getLength());
		if (src.startsWith("</")) //$NON-NLS-1$
		{
			return findMatchingOpen(document, region, partitionsToSearch);
		}
		// Handle self-closing tags!
		if (src.endsWith("/>")) //$NON-NLS-1$
		{
			return null;
		}
		return findMatchingClose(document, region, partitionsToSearch);
	}
	catch (BadLocationException e)
	{
		IdeLog.logError(XMLPlugin.getDefault(), e);
	}
	return null;
}
 
Example 11
Source File: XMLFormatter.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Detects the indentation level.
 */
public int detectIndentationLevel(IDocument document, int offset, boolean isSelection,
		IFormattingContext formattingContext)
{

	int indent = 0;
	try
	{
		// detect the indentation offset with the parser, only if the given offset is not the first one in the
		// current partition.
		ITypedRegion partition = document.getPartition(offset);
		if (partition != null && partition.getOffset() == offset)
		{
			return super.detectIndentationLevel(document, offset);
		}

		String source = document.get();
		IParseRootNode parseResult = ParserPoolFactory.parse(getMainContentType(), source).getRootNode();
		if (parseResult != null)
		{
			final XMLFormatterNodeBuilder builder = new XMLFormatterNodeBuilder();
			final FormatterDocument formatterDocument = createFormatterDocument(source, offset);
			IFormatterContainerNode root = builder.build(parseResult, formatterDocument);
			new XMLFormatterNodeRewriter().rewrite(root);
			IFormatterContext context = new XMLFormatterContext(0);
			FormatterIndentDetector detector = new FormatterIndentDetector(offset);
			try
			{
				root.accept(context, detector);
				return detector.getLevel();
			}
			catch (Exception e)
			{
				// ignore
			}
		}
	}
	catch (Throwable t)
	{
		return super.detectIndentationLevel(document, offset);
	}
	return indent;
}
 
Example 12
Source File: HTMLEditor.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Given the offset, tries to determine if we're on an HTML close/start tag, and if so it will find the matching
 * open/close and highlight the pair.
 * 
 * @param offset
 */
private void highlightTagPair(int offset)
{
	IDocumentProvider documentProvider = getDocumentProvider();
	if (documentProvider == null)
	{
		return;
	}
	IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput());
	if (annotationModel == null)
	{
		return;
	}

	if (fTagPairOccurrences != null)
	{
		// if the offset is included by one of these two positions, we don't need to wipe and re-calculate!
		for (Position pos : fTagPairOccurrences.values())
		{
			if (pos.includes(offset))
			{
				return;
			}
		}
		// New position, wipe the existing annotations in preparation for re-calculating...
		for (Annotation a : fTagPairOccurrences.keySet())
		{
			annotationModel.removeAnnotation(a);
		}
		fTagPairOccurrences = null;
	}

	// Calculate current pair
	Map<Annotation, Position> occurrences = new HashMap<Annotation, Position>();
	IDocument document = getSourceViewer().getDocument();
	IRegion match = TagUtil.findMatchingTag(document, offset, tagPartitions);
	if (match != null)
	{
		// TODO Compare versus last positions, if they're the same don't wipe out the old ones and add new ones!
		occurrences.put(new Annotation(IHTMLConstants.TAG_PAIR_OCCURRENCE_ID, false, null),
				new Position(match.getOffset(), match.getLength()));

		try
		{
			// The current tag we're in!
			ITypedRegion partition = document.getPartition(offset);
			occurrences.put(new Annotation(IHTMLConstants.TAG_PAIR_OCCURRENCE_ID, false, null), new Position(
					partition.getOffset(), partition.getLength()));
		}
		catch (BadLocationException e)
		{
			IdeLog.logError(HTMLPlugin.getDefault(), e);
		}
		for (Map.Entry<Annotation, Position> entry : occurrences.entrySet())
		{
			annotationModel.addAnnotation(entry.getKey(), entry.getValue());
		}
		fTagPairOccurrences = occurrences;
	}
	else
	{
		// no new pair, so don't highlight anything
		fTagPairOccurrences = null;
	}
}
 
Example 13
Source File: HTMLContentAssistProcessor.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * This method looks at the partition that contains the specified offset and from that partition type determines if
 * the offset is: 1. Within an open tag 2. Within a close tag 3. Within a text area If the partition type is
 * unrecognized, the ERROR location will be returned.
 * 
 * @param lexemeProvider
 * @param offset
 * @return
 */
LocationType getCoarseLocationType(IDocument document, ILexemeProvider<HTMLTokenType> lexemeProvider, int offset)
{
	LocationType result = LocationType.ERROR;

	try
	{
		ITypedRegion partition = document.getPartition((offset > 0) ? offset - 1 : offset);
		String type = partition.getType();

		if (locationMap.containsKey(type))
		{
			// assume partition cleanly maps to a location type
			result = locationMap.get(type);

			// If the partition isn't empty, then we'll have at least one lexeme which we can use for any partion to
			// location mappings we need to fix up
			Lexeme<HTMLTokenType> firstLexeme = lexemeProvider.getFirstLexeme();

			if (firstLexeme != null)
			{
				Lexeme<HTMLTokenType> lastLexeme = lexemeProvider.getLastLexeme();
				HTMLTokenType lastLexemeType = lastLexeme.getType();

				switch (result)
				{
					case IN_OPEN_TAG:
					case IN_CLOSE_TAG:
						if (offset <= firstLexeme.getStartingOffset())
						{
							// if we're before the open/close tag, then we're in text
							result = LocationType.IN_TEXT;
						}
						else if (lastLexeme.getEndingOffset() < offset
								&& (lastLexemeType == HTMLTokenType.TAG_END || lastLexemeType == HTMLTokenType.TAG_SELF_CLOSE))
						{
							// if we after a tag end, then we're in text
							result = LocationType.IN_TEXT;
						}
						break;

					case IN_TEXT:
						// special case to support <!DOCTYPE
						if (firstLexeme.getType() == HTMLTokenType.TAG_START
								&& lastLexemeType == HTMLTokenType.META
								&& lastLexeme.getText().equalsIgnoreCase("DOCTYPE")) //$NON-NLS-1$
						{
							result = LocationType.IN_DOCTYPE;
						}
						break;

					default:
						break;
				}
			}
			else
			{
				result = LocationType.IN_TEXT;
			}
		}
	}
	catch (BadLocationException e)
	{
		IdeLog.logWarning(HTMLPlugin.getDefault(),
				MessageFormat.format(Messages.HTMLContentAssistProcessor_ErrorFetchingPartition, offset), e,
				IHTMLEditorDebugScopes.CONTENT_ASSIST);
	}

	if (IdeLog.isTraceEnabled(HTMLPlugin.getDefault(), IDebugScopes.CONTENT_ASSIST))
	{
		IdeLog.logTrace(HTMLPlugin.getDefault(), MessageFormat.format("Coarse location: {0}", result), //$NON-NLS-1$
				IDebugScopes.CONTENT_ASSIST);
	}

	return result;
}
 
Example 14
Source File: JSFormatter.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Detects the indentation level.
 */
public int detectIndentationLevel(IDocument document, int offset, boolean isSelection,
		IFormattingContext formattingContext)
{
	int indent = 0;
	try
	{
		// detect the indentation offset with the parser, only if the given offset is not the first one in the
		// current partition.
		ITypedRegion partition = document.getPartition(offset);
		if (partition != null && partition.getOffset() == offset)
		{
			return super.detectIndentationLevel(document, offset);
		}
		String source = document.get();
		IParseRootNode parseResult = ParserPoolFactory.parse(getMainContentType(), source).getRootNode();
		if (parseResult != null)
		{
			final JSFormatterNodeBuilder builder = new JSFormatterNodeBuilder();
			final FormatterDocument formatterDocument = createFormatterDocument(source, offset);
			IFormatterContainerNode root = builder.build(parseResult, formatterDocument);
			new JSFormatterNodeRewriter(parseResult, formatterDocument).rewrite(root);
			IFormatterContext context = new JSFormatterContext(0);
			FormatterIndentDetector detector = new FormatterIndentDetector(offset);
			try
			{
				root.accept(context, detector);
				return detector.getLevel();
			}
			catch (Exception e)
			{
				// ignore
			}
		}
	}
	catch (Throwable t)
	{
		return super.detectIndentationLevel(document, offset);
	}
	return indent;
}
 
Example 15
Source File: OpenTagCloser.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
private String getOpenTag(IDocument document, int offset) throws BadLocationException
{
	ITypedRegion partition = document.getPartition(offset - 1);
	int length = Math.min(partition.getLength(), offset - partition.getOffset());
	String tagContents = document.get(partition.getOffset(), length);

	// Find last '<' not in a string
	int lessThanIndex = 0;
	boolean inString = false;
	for (int i = 0; i < length; i++)
	{
		char c = tagContents.charAt(i);
		switch (c)
		{
			case '<':
				if (!inString)
				{
					lessThanIndex = i;
				}
				break;
			case '\\':
				if (inString)
				{
					i++; // skip next char
				}
				break;
			case '\'':
			case '"':
				// FIXME Handle storing opening string char and only toggle this when it makes sense!
				inString = !inString;
				break;
			default:
				break;
		}
	}
	tagContents = tagContents.substring(lessThanIndex);

	if (tagContents.length() > 0 && tagContents.charAt(0) == '<')
	{
		tagContents = tagContents.substring(1);
	}
	// If it ends in a slash, we probably can just return null because it's self-closed!
	if (tagContents.length() > 0 && tagContents.charAt(tagContents.length() - 1) == '/')
	{
		return null;
	}
	String tagName = tagContents.trim();
	// Modify tag for some tag name checks
	int spaceIndex = tagName.indexOf(' ');
	if (spaceIndex != -1)
	{
		tagName = tagName.substring(0, spaceIndex);
	}
	String toCheck = tagName;
	if (toCheck.endsWith(">"))
	{
		toCheck = toCheck.substring(0, toCheck.length() - 1);
	}
	// Don't close self-closing tags, or tags with no tag name in them
	if (tagContents.length() == 0 || toCheck.length() == 0 || toCheck.charAt(0) == '/')
	{
		return null;
	}
	// Check to see if this tag type is one that self-closes by HTML definition based on doctype.
	if (isEmptyTagType(document, toCheck))
	{
		return null;
	}
	// Return a not necessarily good tag. May contain attrs and an additional ">", but we rely on that later...
	return new String("<" + tagName + ">");
}
 
Example 16
Source File: XMLEditor.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Given the offset, tries to determine if we're on an HTML close/start tag, and if so it will find the matching
 * open/close and highlight the pair.
 * 
 * @param offset
 */
private void highlightTagPair(int offset)
{
	IDocumentProvider documentProvider = getDocumentProvider();
	if (documentProvider == null)
	{
		return;
	}
	IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput());
	if (annotationModel == null)
	{
		return;
	}

	if (fTagPairOccurrences != null)
	{
		// if the offset is included by one of these two positions, we don't need to wipe and re-calculate!
		for (Position pos : fTagPairOccurrences.values())
		{
			if (pos.includes(offset))
			{
				return;
			}
		}
		// New position, wipe the existing annotations in preparation for re-calculating...
		for (Annotation a : fTagPairOccurrences.keySet())
		{
			annotationModel.removeAnnotation(a);
		}
		fTagPairOccurrences = null;
	}

	// Calculate current pair
	Map<Annotation, Position> occurrences = new HashMap<Annotation, Position>();
	IDocument document = getSourceViewer().getDocument();

	IParseNode node = getASTNodeAt(offset, getAST());
	if (node instanceof XMLElementNode)
	{
		XMLElementNode en = (XMLElementNode) node;
		if (!en.isSelfClosing())
		{
			IRegion match = TagUtil.findMatchingTag(document, offset, tagPartitions);
			if (match != null)
			{
				// TODO Compare versus last positions, if they're the same don't wipe out the old ones and add new
				// ones!
				occurrences.put(new Annotation(IXMLEditorConstants.TAG_PAIR_OCCURRENCE_ID, false, null),
						new Position(match.getOffset(), match.getLength()));

				try
				{
					// The current tag we're in!
					ITypedRegion partition = document.getPartition(offset);
					occurrences.put(new Annotation(IXMLEditorConstants.TAG_PAIR_OCCURRENCE_ID, false, null),
							new Position(partition.getOffset(), partition.getLength()));
				}
				catch (BadLocationException e)
				{
					IdeLog.logError(XMLPlugin.getDefault(), e);
				}
				for (Map.Entry<Annotation, Position> entry : occurrences.entrySet())
				{
					annotationModel.addAnnotation(entry.getKey(), entry.getValue());
				}
				fTagPairOccurrences = occurrences;
				return;
			}
		}
	}
	// no new pair, so don't highlight anything
	fTagPairOccurrences = null;
}
 
Example 17
Source File: CSSFormatter.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Detects the indentation level.
 */
public int detectIndentationLevel(IDocument document, int offset, boolean isSelection,
		IFormattingContext formattingContext)
{

	int indent = 0;
	try
	{
		// detect the indentation offset with the parser, only if the given offset is not the first one in the
		// current partition.
		ITypedRegion partition = document.getPartition(offset);
		if (partition != null && partition.getOffset() == offset)
		{
			return super.detectIndentationLevel(document, offset);
		}

		String source = document.get();
		IParseRootNode parseResult = ParserPoolFactory.parse(getMainContentType(), source).getRootNode();
		if (parseResult != null)
		{
			final CSSFormatterNodeBuilder builder = new CSSFormatterNodeBuilder();
			final FormatterDocument formatterDocument = createFormatterDocument(source, offset);
			IFormatterContainerNode root = builder.build(parseResult, formatterDocument);
			new CSSFormatterNodeRewriter(parseResult, formatterDocument).rewrite(root);
			IFormatterContext context = new CSSFormatterContext(0);
			FormatterIndentDetector detector = new FormatterIndentDetector(offset);
			try
			{
				root.accept(context, detector);
				return detector.getLevel();
			}
			catch (Exception e)
			{
				// ignore
			}
		}
	}
	catch (Throwable t)
	{
		return super.detectIndentationLevel(document, offset);
	}
	return indent;
}
 
Example 18
Source File: PartitionInsertEditStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected void internalCustomizeDocumentCommand(IDocument document, DocumentCommand command)
		throws BadLocationException {
	if (left.length() >= command.text.length() && command.text.length() > 0 && left.endsWith(command.text)) {
		ITypedRegion partition = document.getPartition(command.offset);
		if (command.offset != 0 && partition.getLength() == 0 && document.getLength() != 0) {
			ITypedRegion precedingPartition = document.getPartition(command.offset - 1);
			partition = precedingPartition;
		}
		if (partition.getOffset() + partition.getLength() >= command.offset + right.length()) {
			if (!left.equals(right) && right.equals(document.get(command.offset, right.length())))
				return;
		}
		if (isIdentifierPart(document, command.offset + command.length))
			return;
		if (left.length() > 1) {
			int minDocumentLength = left.length() - command.text.length();
			if (minDocumentLength > document.getLength()) {
				return;
			}
			if (command.offset - minDocumentLength < 0)
				return;
			String existingLeftPart = document.get(command.offset - minDocumentLength, minDocumentLength);
			if (!left.equals(existingLeftPart + command.text))
				return;
		}
		if (left.equals(right)) {
			String partitionContent = document.get(partition.getOffset(), partition.getLength());
			if (count(left, partitionContent) % 2 != 0)
				return;
			IRegion currentLine = document.getLineInformationOfOffset(command.offset);
			if (partition.getOffset() == command.offset && 
					partition.getOffset() + partition.getLength() > currentLine.getOffset() + currentLine.getLength()) {
				String trailingLine = document.get(command.offset, currentLine.getLength() - (command.offset - currentLine.getOffset()));
				if (count(left, trailingLine) % 2 != 0)
					return;
			}
		}
		command.caretOffset = command.offset + command.text.length();
		command.shiftsCaret = false;
		command.text += right;
	}
}
 
Example 19
Source File: TagContentAssistProcessor.java    From http4e with Apache License 2.0 4 votes vote down vote up
/**
 * Used to determine whether there is any text after the current offset
 * within the same partition, excluding the current word Also returns true
 * if there is no white
 */
private boolean useContractedElementCompletion( int documentOffset,
        IDocument document){
    
    boolean textReached = false;
    boolean isRemainingWhiteSpace = true;
    
    try {
        ITypedRegion region = document.getPartition(documentOffset);
        
        int partitionOffset = region.getOffset();
        int partitionLength = region.getLength();
        
        int readLength = documentOffset - partitionOffset;
        int remainingLength = partitionLength - readLength;
        
        if( document.getLength() >= documentOffset + 1) {
            String firstTwo = document.get(partitionOffset, 2);
            if( firstTwo.equals("<<"))
                return false;
        }
        
        scanner.setRange(document, documentOffset, remainingLength);
        
        IToken token = null;
        while ((token = scanner.nextToken()) != Token.WHITESPACE
                && token != Token.EOF) {
            isRemainingWhiteSpace = false;
            continue;
        }
        
        while ((token = scanner.nextToken()) == Token.WHITESPACE
                && token != Token.EOF) {
            isRemainingWhiteSpace = true;
            continue;
        }
        
        char c = (char) 0;
        
        while ((c == scanner.read())) {
            if( c == XMLTagScanner.EOF)
                break;
            if( c == '<') {
                break;
            }
            if( !Character.isWhitespace(c))
                textReached = true;
            
        }
        
    } catch (BadLocationException e) {
       ExceptionHandler.handle(e);
    }
    
    if( textReached)
        return true;
    if( !isRemainingWhiteSpace && !textReached)
        return true;
    else
        return false;
    
}
 
Example 20
Source File: TagContentAssistProcessor.java    From http4e with Apache License 2.0 4 votes vote down vote up
private TextInfo currentText( IDocument document, int documentOffset){
    
    try {
        
        ITypedRegion region = document.getPartition(documentOffset);
        
        int partitionOffset = region.getOffset();
        int partitionLength = region.getLength();
        
        int index = documentOffset - partitionOffset;
        
        String partitionText = document.get(partitionOffset,
                partitionLength);
        
        char c = partitionText.charAt(index);
        
        if( Character.isWhitespace(c) || Character.isWhitespace(partitionText.charAt(index - 1))) {
            return new TextInfo("", documentOffset, true);
        } else if( c == '<') {
            return new TextInfo("", documentOffset, true);
        } else {
            int start = index;
            c = partitionText.charAt(start);
            
            while (!Character.isWhitespace(c) && c != '<' && start >= 0) {
                start--;
                c = partitionText.charAt(start);
            }
            start++;
            
            int end = index;
            c = partitionText.charAt(end);
            
            while (!Character.isWhitespace(c) && c != '>' && end < partitionLength - 1) {
                end++;
                c = partitionText.charAt(end);
            }
            
            String substring = partitionText.substring(start, end);
            return new TextInfo(substring, partitionOffset + start, false);
            
        }
        
    } catch (BadLocationException e) {
       ExceptionHandler.handle(e);
    }
    return null;
}