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 Project: xtext-eclipse   Author: eclipse   File: CompoundMultiLineTerminalsEditStrategy.java    License: 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 #2
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 Project: eclipse.jdt.ls   Author: eclipse   File: GetterSetterCompletionProposal.java    License: 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 #4
Source Project: eclipse.jdt.ls   Author: eclipse   File: JavadocTagsSubProcessor.java    License: 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 #5
Source Project: e4macs   Author: MulgaSoft   File: HackDefaultCharacterPairMatcher.java    License: 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 #6
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: JavadocTagsSubProcessor.java    License: 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 #7
Source Project: typescript.java   Author: angelozerr   File: JSDocAutoIndentStrategy.java    License: 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 #8
Source Project: typescript.java   Author: angelozerr   File: JSDocAutoIndentStrategy.java    License: 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 #9
@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 #10
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: SseUtilities.java    License: 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 #11
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: JavaChangeHover.java    License: 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 #12
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: JsniFormattingUtil.java    License: 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 #13
Source Project: KaiZen-OpenAPI-Editor   Author: RepreZen   File: QuickFixer.java    License: 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 #14
Source Project: APICloud-Studio   Author: apicloudcom   File: ContentAssistant.java    License: 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 #15
Source Project: APICloud-Studio   Author: apicloudcom   File: ContentAssistant.java    License: 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 #16
/**
 * 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 #17
/**
* 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 #18
@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 #19
Source Project: xtext-eclipse   Author: eclipse   File: XtextEditor.java    License: Eclipse Public License 2.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, IDocumentExtension3.DEFAULT_PARTITIONING, offset, false);
	} catch (BadLocationException exception) {
		// Should not happen
	}

	int lineStartPosition = super.getLineStartPosition(document, line, length, offset);
	if (tokenTypeToPartitionTypeMapperExtension.isMultiLineComment(type)
			|| tokenTypeToPartitionTypeMapperExtension.isSingleLineComment(type)) {
		try {
			IRegion lineInformation = document.getLineInformationOfOffset(offset);
			int offsetInLine = offset - lineInformation.getOffset();
			return getCommentLineStartPosition(line, length, offsetInLine, lineStartPosition);
		} catch(BadLocationException e) {
			// Should not happen
		}
	} 
	if (type.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
		if (isStartOfSingleLineComment(line, length, lineStartPosition) && !isStartOfMultiLineComment(line, length, lineStartPosition)) {
			return getTextStartPosition(line, length, lineStartPosition + 1);
		}
	}
	return lineStartPosition;
}
 
Example #20
Source Project: xtext-eclipse   Author: eclipse   File: PartitionTokenScanner.java    License: 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 #21
Source Project: xtext-eclipse   Author: eclipse   File: AbstractEObjectHover.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Call this method only from within an IUnitOfWork
 */
protected Pair<EObject, IRegion> getXtextElementAt(XtextResource resource, final int offset) {
	// check for cross reference
	EObject crossLinkedEObject = eObjectAtOffsetHelper.resolveCrossReferencedElementAt(resource, offset);
	if (crossLinkedEObject != null) {
		if (!crossLinkedEObject.eIsProxy()) {
			IParseResult parseResult = resource.getParseResult();
			if (parseResult != null) {
				ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset);
				if(leafNode != null && leafNode.isHidden() && leafNode.getOffset() == offset) {
					leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset - 1);
				}
				if (leafNode != null) {
					ITextRegion leafRegion = leafNode.getTextRegion();
					return Tuples.create(crossLinkedEObject, (IRegion) new Region(leafRegion.getOffset(), leafRegion.getLength()));
				}
			}
		}
	} else {
		EObject o = eObjectAtOffsetHelper.resolveElementAt(resource, offset);
		if (o != null) {
			ITextRegion region = locationInFileProvider.getSignificantTextRegion(o);
			final IRegion region2 = new Region(region.getOffset(), region.getLength());
			if (TextUtilities.overlaps(region2, new Region(offset, 0)))
				return Tuples.create(o, region2);
		}
	}
	return null;
}
 
Example #22
Source Project: xtext-eclipse   Author: eclipse   File: ToggleSLCommentAction.java    License: 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 #23
Source Project: xtext-eclipse   Author: eclipse   File: MultiLineTerminalsEditStrategy.java    License: 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 #24
Source Project: xtext-eclipse   Author: eclipse   File: WhitespaceHelper.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void initialize(IDocument document, int offset, int length, boolean ensureEmptyLinesAround) {
	this.offset = offset;
	this.length = length;
	this.lineSeparator = TextUtilities.getDefaultLineDelimiter(document);
	if (ensureEmptyLinesAround) {
		prefix = calculateLeadingWhitespace(document);
		suffix = calculateTrailingWhitespace(document);
	}
}
 
Example #25
Source Project: xtext-eclipse   Author: eclipse   File: ReplAutoEdit.java    License: 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 #26
Source Project: texlipse   Author: eclipse   File: TexEditorTools.java    License: 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 #27
Source Project: texlipse   Author: eclipse   File: TexAutoIndentStrategy.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
    if (this.indent) {
        if (itemSetted && autoItem && command.length == 0 && command.text != null
                && TextUtilities.endsWith(document.getLegalLineDelimiters(), command.text) != -1) {
            dropItem(document, command);
        } else if (command.length == 0 && command.text != null
                &&  TextUtilities.endsWith(document.getLegalLineDelimiters(), command.text) != -1) {
            smartIndentAfterNewLine(document, command);
        } else if ("}".equals(command.text)) {
            smartIndentAfterBrace(document, command);
        } else {
            itemSetted = false;
        }
    }

    if (TexAutoIndentStrategy.hardWrap && command.length == 0 && command.text != null) {
        try {
            final String contentType = ((IDocumentExtension3) document).getContentType(
                    TexEditor.TEX_PARTITIONING, command.offset, true);
            // Do not wrap in verbatim partitions
            if (!FastLaTeXPartitionScanner.TEX_VERBATIM.equals(contentType)) {
                hlw.doWrapB(document, command, lineLength);
            }
        }
        catch (Exception e) {
            // If we cannot retrieve the current content type, do not break lines
        }
    }
}
 
Example #28
Source Project: textuml   Author: abstratt   File: WorkingCopy.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void setSource(String source) {
    this.source = source;
    setLineDelimiter(TextUtilities.getDefaultLineDelimiter(document));
    root = null;
    rootNode = null;
    lines = null;
}
 
Example #29
Source Project: eclipse.jdt.ls   Author: eclipse   File: AnonymousTypeCompletionProposal.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public String updateReplacementString(IDocument document, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {
	// Construct empty body for performance concern
	// See https://github.com/microsoft/language-server-protocol/issues/1032#issuecomment-648748013
	String newBody = fSnippetSupport ? "{\n\t${0}\n}" : "{\n\n}";

	StringBuilder buf = new StringBuilder("new A()"); //$NON-NLS-1$
	buf.append(newBody);
	// use the code formatter
	String lineDelim = TextUtilities.getDefaultLineDelimiter(document);
	final IJavaProject project = fCompilationUnit.getJavaProject();
	IRegion lineInfo = document.getLineInformationOfOffset(fReplacementOffset);
	Map<String, String> options = project != null ? project.getOptions(true) : JavaCore.getOptions();
	String replacementString = CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, buf.toString(), 0, lineDelim, options);
	int lineEndOffset = lineInfo.getOffset() + lineInfo.getLength();
	int p = offset;
	if (p < document.getLength()) {
		char ch = document.getChar(p);
		while (p < lineEndOffset) {
			if (ch == '(' || ch == ')' || ch == ';' || ch == ',') {
				break;
			}
			ch = document.getChar(++p);
		}
		if (ch != ';' && ch != ',' && ch != ')') {
			replacementString = replacementString + ';';
		}
	}
	int beginIndex = replacementString.indexOf('(');
	replacementString = replacementString.substring(beginIndex);
	return replacementString;
}
 
Example #30
Source Project: xds-ide   Author: excelsior-oss   File: PairedBracketsMatcher.java    License: Eclipse Public License 1.0 5 votes vote down vote up
protected ITypedRegion getPartition(IDocument document, int pos) {
        if (fCachedListenedDocument == null) {
            fCachedListenedDocument = document;
            fCachedListenedDocument.addDocumentListener(fDocumentListener);
        }
        if (fCachedPartition != null) {
            int offs = fCachedPartition.getOffset();
            if (offs <= pos && pos < offs + fCachedPartition.getLength()) {

//                /////---- dbg:
//                try {
//                    ITypedRegion pp = TextUtilities.getPartition(document, fPartitioning, pos, false);
//                    if (!pp.getType().equals(fCachedPartition.getType())) {
//                        System.out.println("****** Partition " + pp.getType() + 
//                                           "(" + pp.getOffset() + 
//                                           " / " + pp.getLength() + 
//                                           ") is cached as '" + fCachedPartition.getType() + 
//                                           "(" + fCachedPartition.getOffset() + 
//                                           " / " + fCachedPartition.getLength() + ")");
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                /////----
                
                return fCachedPartition;
            }
        }
        try {
            fCachedPartition= TextUtilities.getPartition(document, fPartitioning, pos, false);
        } catch (BadLocationException e) {
            fCachedPartition= null;
        }
        return fCachedPartition;
    }