org.eclipse.jface.text.TextUtilities Java Examples

The following examples show how to use org.eclipse.jface.text.TextUtilities. 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: 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 #2
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 #3
Source File: CompoundMultiLineTerminalsEditStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void internalCustomizeDocumentCommand(IDocument document, DocumentCommand command)
		throws BadLocationException {
	if (command.length != 0)
		return;
	String[] lineDelimiters = document.getLegalLineDelimiters();
	int delimiterIndex = TextUtilities.startsWith(lineDelimiters, command.text);
	if (delimiterIndex != -1) {
		MultiLineTerminalsEditStrategy bestStrategy = null;
		IRegion bestStart = null;
		for(MultiLineTerminalsEditStrategy strategy: strategies) {
			IRegion candidate = strategy.findStartTerminal(document, command.offset);
			if (candidate != null) {
				if (bestStart == null || bestStart.getOffset() < candidate.getOffset()) {
					bestStrategy = strategy;
					bestStart = candidate;
				}
			}
		}
		if (bestStrategy != null) {
			bestStrategy.internalCustomizeDocumentCommand(document, command);
		}
	}
}
 
Example #4
Source File: GetterSetterCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @param document
 * @param offset
 * @param importRewrite
 * @param completionSnippetsSupported
 * @param addComments
 * @return
 * @throws CoreException
 * @throws BadLocationException
 */
public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite, boolean completionSnippetsSupported, boolean addComments) throws CoreException, BadLocationException {
	int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic);
	String stub;
	if (fIsGetter) {
		String getterName= GetterSetterUtil.getGetterName(fField, null);
		stub = GetterSetterUtil.getGetterStub(fField, getterName, addComments, flags);
	} else {
		String setterName= GetterSetterUtil.getSetterName(fField, null);
		stub = GetterSetterUtil.getSetterStub(fField, setterName, addComments, flags);
	}

	// use the code formatter
	String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
	String replacement = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, 0, lineDelim, fField.getJavaProject());

	if (replacement.endsWith(lineDelim)) {
		replacement = replacement.substring(0, replacement.length() - lineDelim.length());
	}

	return replacement;
}
 
Example #5
Source File: JavadocTagsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void addEdits(IDocument document, TextEdit rootEdit) throws CoreException {
	try {
		String lineDelimiter= TextUtilities.getDefaultLineDelimiter(document);
		final IJavaProject project= getCompilationUnit().getJavaProject();
		IRegion region= document.getLineInformationOfOffset(fInsertPosition);

		String lineContent= document.get(region.getOffset(), region.getLength());
		String indentString= Strings.getIndentString(lineContent, project);
		String str= Strings.changeIndent(fComment, 0, project, indentString, lineDelimiter);
		InsertEdit edit= new InsertEdit(fInsertPosition, str);
		rootEdit.addChild(edit);
		if (fComment.charAt(fComment.length() - 1) != '\n') {
			rootEdit.addChild(new InsertEdit(fInsertPosition, lineDelimiter));
			rootEdit.addChild(new InsertEdit(fInsertPosition, indentString));
		}
	} catch (BadLocationException e) {
		throw new CoreException(StatusFactory.newErrorStatus("Invalid edit", e));
	}
}
 
Example #6
Source File: HackDefaultCharacterPairMatcher.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
protected IRegion performMatch(IDocument doc, int caretOffset) throws BadLocationException {
	final int charOffset= caretOffset - 1;
	final char prevChar= doc.getChar(Math.max(charOffset, 0));
	if (!fPairs.contains(prevChar)) return null;
	final boolean isForward= fPairs.isStartCharacter(prevChar);
	fAnchor= isForward ? ICharacterPairMatcher.LEFT : ICharacterPairMatcher.RIGHT;
	final int searchStartPosition= isForward ? caretOffset : caretOffset - 2;
	final int adjustedOffset= isForward ? charOffset : caretOffset;
	final String partition= TextUtilities.getContentType(doc, fPartitioning, charOffset, false);
	final DocumentPartitionAccessor partDoc= new DocumentPartitionAccessor(doc, fPartitioning, partition);
	int endOffset= findMatchingPeer(partDoc, prevChar, fPairs.getMatching(prevChar),
			isForward,  isForward ? doc.getLength() : -1,
			searchStartPosition);
	if (endOffset == -1) return null;
	final int adjustedEndOffset= isForward ? endOffset + 1: endOffset;
	if (adjustedEndOffset == adjustedOffset) return null;
	return new Region(Math.min(adjustedOffset, adjustedEndOffset),
			Math.abs(adjustedEndOffset - adjustedOffset));
}
 
Example #7
Source File: JavadocTagsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void addEdits(IDocument document, TextEdit rootEdit) throws CoreException {
	try {
		String lineDelimiter= TextUtilities.getDefaultLineDelimiter(document);
		final IJavaProject project= getCompilationUnit().getJavaProject();
		IRegion region= document.getLineInformationOfOffset(fInsertPosition);

		String lineContent= document.get(region.getOffset(), region.getLength());
		String indentString= Strings.getIndentString(lineContent, project);
		String str= Strings.changeIndent(fComment, 0, project, indentString, lineDelimiter);
		InsertEdit edit= new InsertEdit(fInsertPosition, str);
		rootEdit.addChild(edit);
		if (fComment.charAt(fComment.length() - 1) != '\n') {
			rootEdit.addChild(new InsertEdit(fInsertPosition, lineDelimiter));
			rootEdit.addChild(new InsertEdit(fInsertPosition, indentString));
		}
	} catch (BadLocationException e) {
		throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
	}
}
 
Example #8
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 #9
Source File: JSDocAutoIndentStrategy.java    From typescript.java with MIT License 6 votes vote down vote up
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {

		if (!isSmartMode())
			return;

		if (command.text != null) {
			if (command.length == 0) {
				String[] lineDelimiters = document.getLegalLineDelimiters();
				int index = TextUtilities.endsWith(lineDelimiters, command.text);
				if (index > -1) {
					// ends with line delimiter
					if (lineDelimiters[index].equals(command.text))
						// just the line delimiter
						indentAfterNewLine(document, command);
					return;
				}
			}

			if (command.text.equals("/")) { //$NON-NLS-1$
				indentAfterCommentEnd(document, command);
				return;
			}
		}
	}
 
Example #10
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 #11
Source File: JavaDocAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {

	if (!isSmartMode())
		return;

	if (command.text != null) {
		if (command.length == 0) {
			String[] lineDelimiters= document.getLegalLineDelimiters();
			int index= TextUtilities.endsWith(lineDelimiters, command.text);
			if (index > -1) {
				// ends with line delimiter
				if (lineDelimiters[index].equals(command.text))
					// just the line delimiter
					indentAfterNewLine(document, command);
				return;
			}
		}

		if (command.text.equals("/")) { //$NON-NLS-1$
			indentAfterCommentEnd(document, command);
			return;
		}
	}
}
 
Example #12
Source File: SpecificContentAssistAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
* Computes the partition type at the selection start and checks whether the proposal category
* has any computers for this partition.
*
* @param selection the selection
* @return <code>true</code> if there are any computers for the selection
*/
  private boolean isValidSelection(ISelection selection) {
  	if (!(selection instanceof ITextSelection))
  		return false;
  	int offset= ((ITextSelection) selection).getOffset();

  	IDocument document= getDocument();
  	if (document == null)
  		return false;

  	String contentType;
  	try {
       contentType= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, offset, true);
      } catch (BadLocationException x) {
      	return false;
      }

      return fCategory.hasComputers(contentType);
  }
 
Example #13
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the method content of the moved method.
 *
 * @param document
 *            the document representing the source compilation unit
 * @param declaration
 *            the source method declaration
 * @param rewrite
 *            the ast rewrite to use
 * @return the string representing the moved method body
 * @throws BadLocationException
 *             if an offset into the document is invalid
 */
protected String createMethodContent(final IDocument document, final MethodDeclaration declaration, final ASTRewrite rewrite) throws BadLocationException {
	Assert.isNotNull(document);
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	final IRegion range= new Region(declaration.getStartPosition(), declaration.getLength());
	final RangeMarker marker= new RangeMarker(range.getOffset(), range.getLength());
	final IJavaProject project= fMethod.getJavaProject();
	final TextEdit[] edits= rewrite.rewriteAST(document, project.getOptions(true)).removeChildren();
	for (int index= 0; index < edits.length; index++)
		marker.addChild(edits[index]);
	final MultiTextEdit result= new MultiTextEdit();
	result.addChild(marker);
	final TextEditProcessor processor= new TextEditProcessor(document, new MultiTextEdit(0, document.getLength()), TextEdit.UPDATE_REGIONS);
	processor.getRoot().addChild(result);
	processor.performEdits();
	final IRegion region= document.getLineInformation(document.getLineOfOffset(marker.getOffset()));
	return Strings.changeIndent(document.get(marker.getOffset(), marker.getLength()), Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project), project, "", TextUtilities.getDefaultLineDelimiter(document)); //$NON-NLS-1$
}
 
Example #14
Source File: ContentAssistant.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the code assist processor for the content type of the specified document position.
 * 
 * @param contentAssistSubjectControl
 *            the code assist subject control
 * @param offset
 *            a offset within the document
 * @return a content-assist processor or <code>null</code> if none exists
 * @since 3.0
 */
private IContentAssistProcessor getProcessor(IContentAssistSubjectControl contentAssistSubjectControl, int offset)
{
	try
	{

		IDocument document = contentAssistSubjectControl.getDocument();
		String type;
		if (document != null)
		{
			type = TextUtilities.getContentType(document, getDocumentPartitioning(), offset, true);
		}
		else
		{
			type = IDocument.DEFAULT_CONTENT_TYPE;
		}

		return getContentAssistProcessor(type);

	}
	catch (BadLocationException x)
	{
	}

	return null;
}
 
Example #15
Source File: ContentAssistant.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the code assist processor for the content type of the specified document position.
 * 
 * @param viewer
 *            the text viewer
 * @param offset
 *            a offset within the document
 * @return a content-assist processor or <code>null</code> if none exists
 * @since 3.0
 */
public IContentAssistProcessor getProcessor(ITextViewer viewer, int offset)
{
	try
	{

		IDocument document = viewer.getDocument();
		String type = TextUtilities.getContentType(document, getDocumentPartitioning(), offset, true);

		return getContentAssistProcessor(type);

	}
	catch (BadLocationException x)
	{
	}

	return null;
}
 
Example #16
Source File: QuickFixer.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IRegion processFix(IDocument document, IMarker marker) throws CoreException {
    int line = (int) marker.getAttribute(IMarker.LINE_NUMBER);
    try {
        String indent = getIndent(document, line);
        // getLineOffset() is zero-based, and imarkerLine is one-based.
        int endOfCurrLine = document.getLineInformation(line - 1).getOffset()
                + document.getLineInformation(line - 1).getLength();
        // should be fine for first and last lines in the doc as well
        String replacementText = indent + "type: object";
        String delim = TextUtilities.getDefaultLineDelimiter(document);
        document.replace(endOfCurrLine, 0, delim + replacementText);
        return new Region(endOfCurrLine + delim.length(), replacementText.length());
    } catch (BadLocationException e) {
        throw new CoreException(createStatus(e, "Cannot process the IMarker"));
    }
}
 
Example #17
Source File: JsniFormattingUtil.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public static String[] getJsniMethods(IDocument document) {

    try {
      List<String> jsniMethods = new LinkedList<String>();
      ITypedRegion[] regions = TextUtilities.computePartitioning(document,
          GWTPartitions.GWT_PARTITIONING, 0, document.getLength(), false);

      // Format all JSNI blocks in the document
      for (ITypedRegion region : regions) {
        if (region.getType().equals(GWTPartitions.JSNI_METHOD)) {
          String jsni = document.get(region.getOffset(), region.getLength());
          jsniMethods.add(jsni);
        }
      }

      return jsniMethods.toArray(new String[0]);

    } catch (BadLocationException e) {
      GWTPluginLog.logError(e);
      return null;
    }
  }
 
Example #18
Source File: SseUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Finds the partition containing the given offset.
 * 
 * @param document the document to search
 * @param offset the offset used to find a matching partition
 * @return the partition, or null
 */
public static ITypedRegion getPartition(IStructuredDocument document, int offset) {
  ITypedRegion[] partitions;
  try {
    partitions = TextUtilities.computePartitioning(document,
        IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING, 0,
        document.getLength(), true);
  } catch (BadLocationException e) {
    CorePluginLog.logError(e, "Unexpected bad location exception.");
    return null;
  }

  for (ITypedRegion partition : partitions) {
    if (partition.getOffset() <= offset
        && offset < partition.getOffset() + partition.getLength()) {
      return partition;
    }
  }
  
  return null;
}
 
Example #19
Source File: PartitionTokenScanner.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected ILexerTokenRegion computeNext() {
	while(delegate.hasNext()) {
		ILexerTokenRegion candidate = delegate.next();
		if (overlapRegion.getOffset() + overlapRegion.getLength() < candidate.getOffset())
			return endOfData();
		if (TextUtilities.overlaps(overlapRegion, candidate))
			return candidate;
	}
	return endOfData();
}
 
Example #20
Source File: MultiLineTerminalsEditStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isLineDelimiter(IDocument document, DocumentCommand command) {
	if (command.length != 0) {
		return false;
	}
	String originalText = command.text;
	String[] lineDelimiters = document.getLegalLineDelimiters();
	int delimiterIndex = TextUtilities.startsWith(lineDelimiters, originalText);
	return delimiterIndex != -1 && originalText.trim().length() == 0;
}
 
Example #21
Source File: TypeScriptAutoIndentStrategy.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Returns the indentation of the line <code>line</code> in <code>document</code>.
 * The returned string may contain pairs of leading slashes that are considered
 * part of the indentation. The space before the asterisk in a javadoc-like
 * comment is not considered part of the indentation.
 *
 * @param document the document
 * @param line the line
 * @return the indentation of <code>line</code> in <code>document</code>
 * @throws BadLocationException if the document is changed concurrently
 */
private static String getCurrentIndent(Document document, int line) throws BadLocationException {
	IRegion region= document.getLineInformation(line);
	int from= region.getOffset();
	int endOffset= region.getOffset() + region.getLength();

	// go behind line comments
	int to= from;
	while (to < endOffset - 2 && document.get(to, 2).equals(LINE_COMMENT))
		to += 2;

	while (to < endOffset) {
		char ch= document.getChar(to);
		if (!Character.isWhitespace(ch))
			break;
		to++;
	}

	// don't count the space before javadoc like, asterisk-style comment lines
	if (to > from && to < endOffset - 1 && document.get(to - 1, 2).equals(" *")) { //$NON-NLS-1$
		String type= TextUtilities.getContentType(document, IJavaScriptPartitions.JAVA_PARTITIONING, to, true);
		if (type.equals(IJavaScriptPartitions.JAVA_DOC) || type.equals(IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT))
			to--;
	}

	return document.get(from, to - from);
}
 
Example #22
Source File: JavaPairMatcher.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns true if the character at the specified offset is a greater-than sign, rather than an
 * type parameter list close angle bracket.
 * 
 * @param document a document
 * @param offset an offset within the document
 * @return true if the character at the specified offset is a greater-than sign
 * @throws BadLocationException if offset is invalid in the document
 */
private boolean isGreaterThanOperator(IDocument document, int offset) throws BadLocationException {
	if (offset < 0)
		return false;
	String contentType= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, offset, false);
	if (!IDocument.DEFAULT_CONTENT_TYPE.equals(contentType)) {
		return false;
	}
	JavaHeuristicScanner scanner= new JavaHeuristicScanner(document, IJavaPartitions.JAVA_PARTITIONING, contentType);
	return !isTypeParameterClosingBracket(offset, document, scanner);
}
 
Example #23
Source File: JavaPairMatcher.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns <code>true</code> if the character at the specified offset is a less-than sign, rather than
 * the opening angle bracket of a type parameter list.
 * 
 * @param document a document
 * @param offset an offset within the document
 * @return <code>true</code> if the character at the specified offset is a less-than sign
 * @throws BadLocationException if offset is invalid in the document
 */
private boolean isLessThanOperator(IDocument document, int offset) throws BadLocationException {
	if (offset < 0) return false;
	String contentType= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, offset, false);
	if (!IDocument.DEFAULT_CONTENT_TYPE.equals(contentType)) {
		return false;
	}
	JavaHeuristicScanner scanner= new JavaHeuristicScanner(document, IJavaPartitions.JAVA_PARTITIONING, contentType);
	return !isTypeParameterOpeningBracket(offset, document, scanner);
}
 
Example #24
Source File: ToggleSLCommentAction.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Determines whether each line is prefixed by one of the prefixes.
 *
 * @param startLine Start line in document
 * @param endLine End line in document
 * @param prefixes Possible comment prefixes
 * @param document The document
 * @return <code>true</code> iff each line from <code>startLine</code>
 *             to and including <code>endLine</code> is prepended by one
 *             of the <code>prefixes</code>, ignoring whitespace at the
 *             begin of line
 * @since 2.1
 */
protected boolean isBlockCommented(int startLine, int endLine, String[] prefixes, IDocument document) {

	try {

		// check for occurrences of prefixes in the given lines
		for (int i= startLine; i <= endLine; i++) {

			IRegion line= document.getLineInformation(i);
			String text= document.get(line.getOffset(), line.getLength());

			int[] found= TextUtilities.indexOf(prefixes, text, 0);

			if (found[0] == -1)
				// found a line which is not commented
				return false;

			String s= document.get(line.getOffset(), found[0]);
			s= s.trim();
			if (s.length() != 0)
				// found a line which is not commented
				return false;

		}

		return true;

	} catch (BadLocationException x) {
		// should not happen
		log.error(x.getMessage(), x);
	}

	return false;
}
 
Example #25
Source File: TexEditorTools.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a length of a line.
 * @param document 	IDocument that contains the line.
 * @param command 	DocumentCommand that determines the line.
 * @param delim 	are line delimiters counted to the line length 
 * @param target 	-1 = previous line, 0 = current line, 1 = next line etc... 
 * @return 			the line length 
 */
public int getLineLength(IDocument document, DocumentCommand command, 
		boolean delim, int target) {
	int line;
	
	int length = 0;
	try{
		line = document.getLineOfOffset(command.offset) + target;
		if (line < 0 || line >= document.getNumberOfLines()){
			//line = document.getLineOfOffset(command.offset);
			return 0;
		}
		
		length = document.getLineLength(line);
		if (length == 0){
			return 0;
		}
		if (!delim){
			String txt = document.get(document.getLineOffset(line), document.getLineLength(line));
			String[] del = document.getLegalLineDelimiters();
			int cnt = TextUtilities.endsWith(del ,txt);
			if (!delim && cnt > -1){
				length = length - del[cnt].length();				
			}
		}
	}catch(BadLocationException e){
		TexlipsePlugin.log("TexEditorTools.getLineLength:",e);
	}
	return length;
}
 
Example #26
Source File: JsniFormattingUtil.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a text edit that formats the given document according to the given
 * settings.
 * 
 * @param document The document to format.
 * @param javaFormattingPrefs The formatting preferences for Java, used to
 *          determine the method level indentation.
 * @param javaScriptFormattingPrefs The formatting preferences for JavaScript.
 *          See org.eclipse.wst.jsdt.internal.formatter
 *          .DefaultCodeFormatterOptions and
 *          org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants
 * @param originalJsniMethods The original jsni methods to use if the
 *          formatter fails to format the method. The original jsni Strings
 *          must be in the same order that the jsni methods occur in the
 *          document. This is to work around the Java formatter blasting the
 *          jsni tabbing for the format-on-save action. May be null.
 * @return A text edit that when applied to the document, will format the jsni
 *         methods.
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public static TextEdit format(IDocument document, Map javaFormattingPrefs,
    Map javaScriptFormattingPrefs, String[] originalJsniMethods) {
  TextEdit combinedEdit = new MultiTextEdit();
  try {
    ITypedRegion[] regions = TextUtilities.computePartitioning(document,
        GWTPartitions.GWT_PARTITIONING, 0, document.getLength(), false);

    // Format all JSNI blocks in the document
    int i = 0;
    for (ITypedRegion region : regions) {
      if (region.getType().equals(GWTPartitions.JSNI_METHOD)) {
        String originalJsniMethod = null;
        if (originalJsniMethods != null && i < originalJsniMethods.length) {
          originalJsniMethod = originalJsniMethods[i];
        }
        TextEdit edit = format(document, new TypedPosition(region),
            javaFormattingPrefs, javaScriptFormattingPrefs,
            originalJsniMethod);
        if (edit != null) {
          combinedEdit.addChild(edit);
        }
        i++;
      }
    }
    return combinedEdit;

  } catch (BadLocationException e) {
    GWTPluginLog.logError(e);
    return null;
  }
}
 
Example #27
Source File: LangAutoEditStrategy.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
protected void smartIndentAfterNewLine(IDocument doc, DocumentCommand2 cmd) throws BadLocationException {
	if(cmd.length > 0 || cmd.text == null)
		return;
	
	IRegion lineRegion = doc.getLineInformationOfOffset(cmd.offset);
	int lineEnd = getRegionEnd(lineRegion);
	
	int postWsEndPos = TextSourceUtils.findEndOfIndent(docContents, cmd.offset); 
	boolean hasPendingTextAfterEdit = postWsEndPos != lineEnd;
	
	
	BlockHeuristicsScannner bhscanner = createBlockHeuristicsScanner(doc);
	
	int offsetForBalanceCalculation = findOffsetForBalanceCalculation(doc, bhscanner, cmd.offset);
	int lineForBalanceCalculation = doc.getLineOfOffset(cmd.offset);
	
	// Find block balances of preceding text (line start to edit cursor)
	LineIndentResult nli = determineIndent(doc, bhscanner, lineForBalanceCalculation, offsetForBalanceCalculation);
	cmd.text += nli.nextLineIndent;
	
	BlockBalanceResult blockInfo = nli.blockInfo;
	if(blockInfo.unbalancedOpens > 0) {
		if(preferences.closeBraces() && !hasPendingTextAfterEdit){
			
			if(bhscanner.shouldCloseBlock(blockInfo.rightmostUnbalancedBlockOpenOffset)) {
				//close block
				cmd.caretOffset = cmd.offset + cmd.text.length();
				cmd.shiftsCaret = false;
				String delimiter = TextUtilities.getDefaultLineDelimiter(doc);
				char openChar = doc.getChar(blockInfo.rightmostUnbalancedBlockOpenOffset);
				char closeChar = bhscanner.getClosingPeer(openChar); 
				cmd.text += delimiter + addIndent(nli.editLineIndent, blockInfo.unbalancedOpens - 1) + closeChar;
			}
		}
		return;
	}
}
 
Example #28
Source File: GWTSpellingEngine.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void check(IDocument document, IRegion[] regions,
    ISpellChecker checker, ISpellingProblemCollector collector,
    IProgressMonitor monitor) {
  try {
    List<IRegion> regionList = new ArrayList<IRegion>();
    for (int i = 0; i < regions.length; i++) {
      IRegion region = regions[i];
      // Compute the GWT partitioning so we can identify JSNI blocks
      ITypedRegion[] partitions = TextUtilities.computePartitioning(
          document, GWTPartitions.GWT_PARTITIONING, region.getOffset(),
          region.getLength(), false);
      // Spelling engine should ignore all JSNI block regions
      for (int j = 0; j < partitions.length; j++) {
        ITypedRegion partition = partitions[j];
        if (!GWTPartitions.JSNI_METHOD.equals(partition.getType())) {
          regionList.add(partition);
        }
      }
    }
    super.check(document,
        regionList.toArray(new IRegion[regionList.size()]), checker,
        collector, monitor);
  } catch (BadLocationException e) {
    // Ignore: the document has been changed in another thread and will be
    // checked again (our super class JavaSpellingEngine does the same).
  }
}
 
Example #29
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) {

	String type= IDocument.DEFAULT_CONTENT_TYPE;
	try {
		type= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, offset, true);
	} catch (BadLocationException exception) {
		// Should not happen
	}

	int index= super.getLineStartPosition(document, line, length, offset);
	if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) {
		if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') {
			do {
				++index;
			} while (index < length && Character.isWhitespace(line.charAt(index)));
		}
	} else {
		if (index < length - 1 && line.charAt(index) == '/' && line.charAt(index + 1) == '/') {
			index++;
			do {
				++index;
			} while (index < length && Character.isWhitespace(line.charAt(index)));
		}
	}
	return index;
}
 
Example #30
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;
	}
}