Java Code Examples for org.eclipse.jface.text.ITypedRegion#getType()

The following examples show how to use org.eclipse.jface.text.ITypedRegion#getType() . 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: 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 2
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 3
Source File: AddBlockCommentAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Handle the partition under the start offset of the selection.
 *
 * @param partition the partition under the start of the selection
 * @param edits the list of edits to later execute
 * @param factory the factory for edits
 * @param offset the start of the selection, which must lie inside
 *        <code>partition</code>
 */
private void handleFirstPartition(ITypedRegion partition, List<Edit> edits, Edit.EditFactory factory, int offset) throws BadLocationException {

	int partOffset= partition.getOffset();
	String partType= partition.getType();

	Assert.isTrue(partOffset <= offset, "illegal partition"); //$NON-NLS-1$

	// first partition: mark start of comment
	if (partType == IDocument.DEFAULT_CONTENT_TYPE) {
		// Java code: right where selection starts
		edits.add(factory.createEdit(offset, 0, getCommentStart()));
	} else if (isSpecialPartition(partType)) {
		// special types: include the entire partition
		edits.add(factory.createEdit(partOffset, 0, getCommentStart()));
	}	// javadoc: no mark, will only start after comment

}
 
Example 4
Source File: GamaFoldingRegionProvider.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void computeCommentFolding(final IXtextDocument xtextDocument,
		final IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor, final ITypedRegion typedRegion,
		final boolean initiallyFolded) throws BadLocationException {
	final int offset = typedRegion.getOffset();
	final int length = typedRegion.getLength();
	final Matcher matcher = getTextPatternInComment().matcher(xtextDocument.get(offset, length));
	((GamaFoldingRegionAcceptor) foldingRegionAcceptor).type = typedRegion.getType();
	if (matcher.find()) {
		final TextRegion significant = new TextRegion(offset + matcher.start(), 0);
		((IFoldingRegionAcceptorExtension<ITextRegion>) foldingRegionAcceptor).accept(offset, length,
				initiallyFolded, significant);
	} else {
		((IFoldingRegionAcceptorExtension<ITextRegion>) foldingRegionAcceptor).accept(offset, length,
				initiallyFolded);
	}
}
 
Example 5
Source File: TagBasedTLCAnalyzer.java    From tlaplus with MIT License 6 votes vote down vote up
/**
 * Add start of coverage
 * @param start
 */
public void addTagStart(ITypedRegion start)
{
    // Assert.isTrue(inTag() && !inTag() == !hasUserPartitions(),
    // "Found user partitions which have not been removed. This is a bug.");

    ITypedRegion userRegion = getUserRegion();
    if (userRegion != null)
    {
        stack.push(userRegion);
    }
    TLCRegion startRegion = new TLCRegion(start.getOffset(), start.getLength(), start.getType());
    startRegion.setMessageCode(getMessageCode(start, START));
    startRegion.setSeverity(getSeverity(start));
    // add start to stack
    stack.push(startRegion);
}
 
Example 6
Source File: XtextSpellingReconcileStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean shouldProcess(ITypedRegion typedRegion) {
	String type = typedRegion.getType();
	if (partitionMapperExtension != null) {
		if (partitionMapperExtension.isMultiLineComment(type) || partitionMapperExtension.isSingleLineComment(type)) {
			return true;
		}
		if (STRING_LITERAL_PARTITION.equals(type)) {
			return true;
		}
		return false;
	}
	if (STRING_LITERAL_PARTITION.equals(type)
			|| SL_COMMENT_PARTITION.equals(type)
			|| COMMENT_PARTITION.equals(type)) {
		return true;
	}
	return false;
}
 
Example 7
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 8
Source File: PartitionToolkit.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * Prints partition information
 * @param region
 * @param document
 */
public static void printPartition(ITypedRegion region, IDocument document)
{
    if (region == null)
    {
        return;
    }

    try
    {
        StringBuffer messageBuffer = new StringBuffer();
        String location = "[" + region.getOffset() + ":" + region.getLength() + "]";

        if (region instanceof TLCRegion)
        {
            TLCRegion tlcRegion = (TLCRegion) region;
            messageBuffer.append("TLC:" + tlcRegion.getMessageCode() + " " + tlcRegion.getSeverity() + " "
                    + location);
        } else
        {
            int offset = region.getOffset();
            int printLength = Math.min(region.getLength(), 255);

            String type = region.getType();
            Assert.isTrue(type.equals(TagBasedTLCOutputTokenScanner.DEFAULT_CONTENT_TYPE));

            String head = document.get(offset, printLength);
            messageBuffer.append("OUTPUT:" + location + ": >" + head + "< ...");
        }

        TLCUIActivator.getDefault().logDebug(messageBuffer.toString());

    } catch (BadLocationException e)
    {
        TLCUIActivator.getDefault().logError("Error printing partition", e);
    }

}
 
Example 9
Source File: AddBlockCommentAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Handles the partition under the end of the selection. For normal java
 * code, the comment end token is inserted at the selection end; if the
 * selection ends inside a special (i.e. string, character, line comment)
 * partition, the entire partition is included inside the comment.
 *
 * @param partition the partition under the selection end offset
 * @param edits the list of edits to add to
 * @param factory the edit factory
 * @param endOffset the end offset of the selection
 */
private void handleLastPartition(ITypedRegion partition, List<Edit> edits, Edit.EditFactory factory, int endOffset) throws BadLocationException {

	String partType= partition.getType();

	if (partType == IDocument.DEFAULT_CONTENT_TYPE) {
		// normal java: end comment where selection ends
		edits.add(factory.createEdit(endOffset, 0, getCommentEnd()));
	} else if (isSpecialPartition(partType)) {
		// special types: consume entire partition
		edits.add(factory.createEdit(partition.getOffset() + partition.getLength(), 0, getCommentEnd()));
	}

}
 
Example 10
Source File: RemoveBlockCommentAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void runInternal(ITextSelection selection, IDocumentExtension3 docExtension, Edit.EditFactory factory) throws BadPartitioningException, BadLocationException {
	List<Edit> edits= new LinkedList<Edit>();
	int tokenLength= getCommentStart().length();

	int offset= selection.getOffset();
	int endOffset= offset + selection.getLength();

	ITypedRegion partition= docExtension.getPartition(IJavaPartitions.JAVA_PARTITIONING, offset, false);
	int partOffset= partition.getOffset();
	int partEndOffset= partOffset + partition.getLength();

	while (partEndOffset < endOffset) {

		if (partition.getType() == IJavaPartitions.JAVA_MULTI_LINE_COMMENT) {
			edits.add(factory.createEdit(partOffset, tokenLength, "")); //$NON-NLS-1$
			edits.add(factory.createEdit(partEndOffset - tokenLength, tokenLength, "")); //$NON-NLS-1$
		}

		partition= docExtension.getPartition(IJavaPartitions.JAVA_PARTITIONING, partEndOffset, false);
		partOffset= partition.getOffset();
		partEndOffset= partOffset + partition.getLength();
	}

	if (partition.getType() == IJavaPartitions.JAVA_MULTI_LINE_COMMENT) {
		edits.add(factory.createEdit(partOffset, tokenLength, "")); //$NON-NLS-1$
		edits.add(factory.createEdit(partEndOffset - tokenLength, tokenLength, "")); //$NON-NLS-1$
	}

	executeEdits(edits);
}
 
Example 11
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 12
Source File: EditorAction.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
public void run(IAction action) {
  if (targetEditor == null) {
    GWTPluginLog.logWarning("targetEditor is null");
    return;
  }

  IEditorInput editorInput = targetEditor.getEditorInput();
  IResource resource = (IResource) editorInput.getAdapter(IResource.class);
  ITextEditor javaEditor = (ITextEditor) targetEditor;
  ITextSelection sel = (ITextSelection) javaEditor.getSelectionProvider().getSelection();
  IDocument document = javaEditor.getDocumentProvider().getDocument(
      javaEditor.getEditorInput());

  IDocumentExtension3 document3 = (IDocumentExtension3) document;
  IDocumentPartitioner gwtPartitioner = document3.getDocumentPartitioner(GWTPartitions.GWT_PARTITIONING);

  String[] partitionings = document3.getPartitionings();
  String partitioning = (gwtPartitioner != null
      ? GWTPartitions.GWT_PARTITIONING : IJavaPartitions.JAVA_PARTITIONING);

  ITypedRegion[] types;
  try {
    types = TextUtilities.computePartitioning(document, partitioning,
        sel.getOffset(), sel.getLength(), false);
  } catch (BadLocationException e) {
    GWTPluginLog.logError(e);
    return;
  }

  String msg = "File: " + resource.getName();

  msg += "\nPartitionings: ";
  for (String part : partitionings) {
    msg += "\n" + part;
  }

  msg += "\n\nContent types: ";
  for (ITypedRegion type : types) {
    msg += "\n" + type.getType();
  }

  msg += "\n\nSelection range: (offset = " + sel.getOffset() + ", length = "
      + sel.getLength() + ")";

  MessageDialog.openInformation(targetEditor.getSite().getShell(),
      "Selection Info", msg);
}
 
Example 13
Source File: PairedBracketsMatcher.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
protected IRegion performMatch(IDocument document, int offs) throws BadLocationException {
    final int doclen = document.getLength();
    fMatchFlags = 0; 
    if (document == null || doclen < 1 || offs < 0 || offs > doclen) {
        return null;
    }
    char begCh = 0;
    int idx = -1;
    if (offs > 0) {
    // Try char on the left of caret:
        begCh = document.getChar(offs - 1);
        idx = BRACE_PAIRS.indexOf(begCh);
    }
    if (idx < 0) {
        // No bracket on the left. Try the caret position (move offs+=1 and try it):
        ++offs;
        if (offs <= doclen) {
            begCh = document.getChar(offs - 1);
            idx = BRACE_PAIRS.indexOf(begCh);
        }
    }

    if (idx < 0) {
        return null;
    }
    int pos = offs-1;
        
    // Bracket 'ch' found at [pos]
    int pos0 = pos;
    int step = ((idx & 0x1) == 0) ? 1 : -1; // open/close bracket
    
    ITypedRegion partition = getPartition(document, pos);

    final String partType = partition.getType(); 
    
    // Search direction depends on step. Search area is current partition if the partition type
    // is not 'CONTENT_TYPE_DEFAULT' or all document in other case
    int minPos = 0;
    int maxPos = doclen-1;
    if (!partType.equals(fDefaultPartition)) {
        minPos = Math.max(0,  partition.getOffset());
        maxPos = Math.min(maxPos, partition.getOffset() + partition.getLength() - 1);
    }
    char pairCh = BRACE_PAIRS.charAt(idx ^ 0x1);

    fAnchor = step > 0 ? LEFT : RIGHT;
    
    int  deep = 1;
    while(true) {
        pos += step;
        if (pos < minPos || pos>maxPos) {
            // unmatched
            fMatchFlags |= MATCH_FLAG_NO_MATCH; 
            return new Region(pos0, 1); 
        }
        if (getPartition(document, pos).getType().equals(partType)) {
            // skip other partitions (required in default partition)
            char c = document.getChar(pos);
            if (c == begCh) {
                ++deep;
            } else if (c == pairCh) {
                if (--deep == 0) {
                    break;
                }
            }
        }
    } // while
    
    // While was breaked => found:
    if (step > 0) {
        fAnchor = LEFT;
        return new Region(pos0, pos-pos0+1);
    } else {
        fAnchor = RIGHT;
        return new Region(pos, pos0-pos+1);
    }
}
 
Example 14
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 15
Source File: CharacterPairMatcher.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
private IRegion performMatch(IDocument doc, int caretOffset) throws BadLocationException
{
	int charOffset = Math.max(caretOffset - 1, 0);
	char prevChar = doc.getChar(charOffset);
	if (!fPairs.contains(prevChar))
	{
		// Now try to right of caret
		charOffset = caretOffset;
		caretOffset += 1;
		if (charOffset >= doc.getLength())
		{
			return null;
		}
		prevChar = doc.getChar(charOffset);
		if (!fPairs.contains(prevChar))
		{
			return null;
		}
	}

	ITypedRegion partition = getPartition(doc, charOffset);
	// FIXME if we're inside a string or comment, we should limit our search to just this particular partition!
	// Drop out if the char is inside a comment
	if (isComment(doc, partition))
	{
		return null;
	}

	boolean isForward = fPairs.isStartCharacter(prevChar);
	String contentType = partition.getType();
	if (fPairs.isAmbiguous(prevChar))
	{
		// If this is common start tag, look forward, if common end tag look backwards!
		if (CompositePartitionScanner.START_SWITCH_TAG.equals(contentType))
		{
			isForward = true;
		}
		else if (CompositePartitionScanner.END_SWITCH_TAG.equals(contentType))
		{
			isForward = false;
		}
		else
		{
			// Need to look at partition transition to tell if we're at end or beginning!
			String partitionAhead = TextUtilities.getContentType(doc, fPartitioning, charOffset + 1, false);
			String partitionBehind = TextUtilities.getContentType(doc, fPartitioning, charOffset - 1, false);
			if (contentType.equals(partitionBehind) && !contentType.equals(partitionAhead))
			{
				// End because we're transitioning out of a partition on this character
				isForward = false;
			}
			else if (isUnclosedPair(prevChar, doc, charOffset))
			{
				isForward = false;
			}
		}
	}
	fAnchor = isForward ? ICharacterPairMatcher.LEFT : ICharacterPairMatcher.RIGHT;
	int searchStartPosition = isForward ? charOffset + 1 : charOffset - 1;
	char endChar = fPairs.getMatching(prevChar);

	int endOffset = -1;
	if (isForward)
	{
		endOffset = searchForward(doc, searchStartPosition, prevChar, endChar, contentType);
	}
	else
	{
		endOffset = searchBackwards(doc, searchStartPosition, prevChar, endChar, contentType);
	}

	if (endOffset == -1)
	{
		return null;
	}
	final int adjustedOffset = isForward ? charOffset : caretOffset;
	final int adjustedEndOffset = isForward ? endOffset + 1 : endOffset;
	if (adjustedEndOffset == adjustedOffset)
	{
		return null;
	}
	return new Region(Math.min(adjustedOffset, adjustedEndOffset), Math.abs(adjustedEndOffset - adjustedOffset));
}
 
Example 16
Source File: PropertiesQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean getEscapeUnescapeBackslashProposals(IQuickAssistInvocationContext invocationContext, ArrayList<ICompletionProposal> resultingCollections) throws BadLocationException,
		BadPartitioningException {
	ISourceViewer sourceViewer= invocationContext.getSourceViewer();
	IDocument document= sourceViewer.getDocument();
	Point selectedRange= sourceViewer.getSelectedRange();
	int selectionOffset= selectedRange.x;
	int selectionLength= selectedRange.y;
	int proposalOffset;
	int proposalLength;
	String text;
	if (selectionLength == 0) {
		if (selectionOffset != document.getLength()) {
			char ch= document.getChar(selectionOffset);
			if (ch == '=' || ch == ':') { //see PropertiesFilePartitionScanner()
				return false;
			}
		}

		ITypedRegion partition= null;
		if (document instanceof IDocumentExtension3)
			partition= ((IDocumentExtension3)document).getPartition(IPropertiesFilePartitions.PROPERTIES_FILE_PARTITIONING, invocationContext.getOffset(), false);
		if (partition == null)
			return false;

		String type= partition.getType();
		if (!(type.equals(IPropertiesFilePartitions.PROPERTY_VALUE) || type.equals(IDocument.DEFAULT_CONTENT_TYPE))) {
			return false;
		}
		proposalOffset= partition.getOffset();
		proposalLength= partition.getLength();
		text= document.get(proposalOffset, proposalLength);

		if (type.equals(IPropertiesFilePartitions.PROPERTY_VALUE)) {
			text= text.substring(1); //see PropertiesFilePartitionScanner()
			proposalOffset++;
			proposalLength--;
		}
	} else {
		proposalOffset= selectionOffset;
		proposalLength= selectionLength;
		text= document.get(proposalOffset, proposalLength);
	}

	if (PropertiesFileEscapes.containsUnescapedBackslash(text)) {
		if (resultingCollections == null)
			return true;
		resultingCollections.add(new EscapeBackslashCompletionProposal(PropertiesFileEscapes.escape(text, false, true, false), proposalOffset, proposalLength,
				PropertiesFileEditorMessages.EscapeBackslashCompletionProposal_escapeBackslashes));
		return true;
	}
	if (PropertiesFileEscapes.containsEscapedBackslashes(text)) {
		if (resultingCollections == null)
			return true;
		resultingCollections.add(new EscapeBackslashCompletionProposal(PropertiesFileEscapes.unescapeBackslashes(text), proposalOffset, proposalLength,
				PropertiesFileEditorMessages.EscapeBackslashCompletionProposal_unescapeBackslashes));
		return true;
	}
	return false;
}
 
Example 17
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 18
Source File: AddBlockCommentAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Handles partition boundaries within the selection. The end of the current
 * partition and the start of the next partition are examined for whether
 * they contain comment tokens that interfere with the created comment.
 * <p>
 * Comment tokens are removed from interior multi-line comments. Javadoc
 * comments are left as is; instead, multi-line comment tokens are inserted
 * before and after Javadoc partitions to ensure that the entire selected
 * area is commented.
 * </p>
 * <p>
 * The next partition is returned.
 * </p>
 *
 * @param partition the current partition
 * @param edits the list of edits to add to
 * @param factory the edit factory
 * @param docExtension the document to get the partitions from
 * @return the next partition after the current
 * @throws BadLocationException if accessing the document fails - this can
 *         only happen if the document gets modified concurrently
 * @throws BadPartitioningException if the document does not have a Java
 *         partitioning
 */
private ITypedRegion handleInteriorPartition(ITypedRegion partition, List<Edit> edits, Edit.EditFactory factory, IDocumentExtension3 docExtension) throws BadPartitioningException, BadLocationException {

	// end of previous partition
	String partType= partition.getType();
	int partEndOffset= partition.getOffset() + partition.getLength();
	int tokenLength= getCommentStart().length();

	boolean wasJavadoc= false; // true if the previous partition is javadoc

	if (partType == IJavaPartitions.JAVA_DOC) {

		wasJavadoc= true;

	} else if (partType == IJavaPartitions.JAVA_MULTI_LINE_COMMENT) {

		// already in a comment - remove ending mark
		edits.add(factory.createEdit(partEndOffset - tokenLength, tokenLength, "")); //$NON-NLS-1$

	}

	// advance to next partition
	partition= docExtension.getPartition(IJavaPartitions.JAVA_PARTITIONING, partEndOffset, false);
	partType= partition.getType();

	// start of next partition
	if (wasJavadoc) {

		// if previous was javadoc, and the current one is not a comment,
		// then add a block comment start
		if (partType == IDocument.DEFAULT_CONTENT_TYPE
				|| isSpecialPartition(partType)) {
			edits.add(factory.createEdit(partition.getOffset(), 0, getCommentStart()));
		}

	} else { // !wasJavadoc

		if (partType == IJavaPartitions.JAVA_DOC) {
			// if next is javadoc, end block comment before
			edits.add(factory.createEdit(partition.getOffset(), 0, getCommentEnd()));
		} else if (partType == IJavaPartitions.JAVA_MULTI_LINE_COMMENT) {
			// already in a comment - remove startToken
			edits.add(factory.createEdit(partition.getOffset(), getCommentStart().length(), "")); //$NON-NLS-1$
		}
	}

	return partition;
}