Java Code Examples for org.eclipse.jface.text.IRegion#getLength()
The following examples show how to use
org.eclipse.jface.text.IRegion#getLength() .
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: JavaAutoIndentStrategy.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Cuts the visual equivalent of <code>toDelete</code> characters out of the * indentation of line <code>line</code> in <code>document</code>. Leaves * leading comment signs alone. * * @param document the document * @param line the line * @param toDelete the number of space equivalents to delete * @param tabLength the length of a tab * @throws BadLocationException on concurrent document modification */ private void cutIndent(Document document, int line, int toDelete, int tabLength) throws BadLocationException { IRegion region= document.getLineInformation(line); int from= region.getOffset(); int endOffset= region.getOffset() + region.getLength(); // go behind line comments while (from < endOffset - 2 && document.get(from, 2).equals(LINE_COMMENT)) from += 2; int to= from; while (toDelete > 0 && to < endOffset) { char ch= document.getChar(to); if (!Character.isWhitespace(ch)) break; toDelete -= computeVisualLength(ch, tabLength); if (toDelete >= 0) to++; else break; } document.replace(from, to - from, ""); //$NON-NLS-1$ }
Example 2
Source File: ColumnSupport.java From e4macs with Eclipse Public License 1.0 | 6 votes |
/** * Get the insert position of the current line of the rectangle. * Updates the line with spaces if necessary * * @param document * @param offset an offset in the current line; cursor offset on initialization request * @param column the start column position of the rectangle; or -1 on initialization request * @return an IRegion(insert position, charLen) */ public IRegion getInsertPosition(IDocument document, int offset, int column, boolean force) { IRegion result = null; try { IRegion reg = document.getLineInformationOfOffset(offset); int off = reg.getOffset(); int numChars; if (column == -1) { column = Integer.MAX_VALUE; numChars = offset - off; } else { numChars = reg.getLength(); } result = getColumn(document, off, numChars, column,true); } catch (BadLocationException e) { result = null; } return result; }
Example 3
Source File: ModelHelper.java From tlaplus with MIT License | 6 votes |
/** * Recalculate region in a document to four-int-coordinates * @param document * @param region * @param singleLine true, if the region covers one line only * @return four ints: begin line, begin column, end line, end column * @throws BadLocationException */ public static int[] regionToLocation(IDocument document, IRegion region, boolean singleLine) throws BadLocationException { if (!singleLine) { throw new IllegalArgumentException("Not implemented"); } int[] coordinates = new int[4]; // location of the id found in the provided document int offset = region.getOffset(); int length = region.getLength(); // since the id is written as one word, we are in the same line coordinates[0] = document.getLineOfOffset(offset) + 1; // begin line coordinates[2] = document.getLineOfOffset(offset) + 1; // end line // the columns are relative to the offset of the line IRegion line = document.getLineInformationOfOffset(offset); coordinates[1] = offset - line.getOffset(); // begin column coordinates[3] = coordinates[1] + length; // end column // return the coordinates return coordinates; }
Example 4
Source File: XbaseEditor.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
/** * Returns the line of the given selection. It is assumed that it covers an entire line in the Java file. * * @return the line in the Java file (zero based) or <code>-1</code> if the selection does not cover a complete * line. */ protected int getLineInJavaDocument(Document document, int selectionStart, int selectionLength) throws BadLocationException { int line = document.getLineOfOffset(selectionStart); int length = document.getLineLength(line); int lineOffset = document.getLineOffset(line); if (lineOffset == selectionStart && length == selectionLength) { return line; } IRegion region = document.getLineInformation(line); if (region.getOffset() == selectionStart || region.getLength() == selectionLength) { return line; } return -1; }
Example 5
Source File: PyDocumentTemplateContext.java From Pydev with Eclipse Public License 1.0 | 5 votes |
/** * Creates a concrete template context for the given region in the document. This involves finding out which * context type is valid at the given location, and then creating a context of this type. The default implementation * returns a <code>DocumentTemplateContext</code> for the context type at the given location. * * @param contextType the context type for the template. * @param viewer the viewer for which the context is created * @param region the region into <code>document</code> for which the context is created * @return a template context that can handle template insertion at the given location, or <code>null</code> */ public static PyDocumentTemplateContext createContext(final TemplateContextType contextType, final ITextViewer viewer, final IRegion region, String indent) { if (contextType != null) { IDocument document = viewer.getDocument(); final String indentTo = indent; return new PyDocumentTemplateContext(contextType, document, region.getOffset(), region.getLength(), indentTo, viewer); } return null; }
Example 6
Source File: TextSelectionUtils.java From Pydev with Eclipse Public License 1.0 | 5 votes |
/** * In event of partial selection, used to select the full lines involved. */ public void selectCompleteLine() { if (doc.getNumberOfLines() == 1) { this.textSelection = new CoreTextSelection(doc, 0, doc.getLength()); return; } IRegion endLine = getEndLine(); IRegion startLine = getStartLine(); this.textSelection = new CoreTextSelection(doc, startLine.getOffset(), endLine.getOffset() + endLine.getLength() - startLine.getOffset()); }
Example 7
Source File: JavadocDoubleClickStrategy.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Returns a region describing the word around <code>position</code>. * * @param document the document * @param position the offset around which to return the word * @return the word's region, or <code>null</code> for no selection */ @Override protected IRegion findExtendedDoubleClickSelection(IDocument document, int position) { try { IRegion match= super.findExtendedDoubleClickSelection(document, position); if (match != null) return match; IRegion word= findWord(document, position); IRegion line= document.getLineInformationOfOffset(position); if (position == line.getOffset() + line.getLength()) return null; int start= word.getOffset(); int end= start + word.getLength(); if (start > 0 && document.getChar(start - 1) == '@' && Character.isJavaIdentifierPart(document.getChar(start)) && (start == 1 || Character.isWhitespace(document.getChar(start - 2)) || document.getChar(start - 2) == '{')) { // double click after @ident start--; } else if (end == position && end == start + 1 && end < line.getOffset() + line.getLength() && document.getChar(end) == '@') { // double click before " @ident" return findExtendedDoubleClickSelection(document, position + 1); } if (start == end) return null; return new Region(start, end - start); } catch (BadLocationException x) { return null; } }
Example 8
Source File: NLSScanner.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private static void setTagPositions(IDocument document, NLSLine line) throws BadLocationException { IRegion info= document.getLineInformation(line.getLineNumber()); int defaultValue= info.getOffset() + info.getLength(); NLSElement[] elements= line.getElements(); for (int i= 0; i < elements.length; i++) { NLSElement element= elements[i]; if (!element.hasTag()) { element.setTagPosition(computeInsertOffset(elements, i, defaultValue), 0); } } }
Example 9
Source File: JavaDoubleClickSelector.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
@Override protected IRegion findExtendedDoubleClickSelection(IDocument document, int offset) { IRegion match= fPairMatcher.match(document, offset); if (match != null && match.getLength() >= 2) return new Region(match.getOffset() + 1, match.getLength() - 2); return findWord(document, offset); }
Example 10
Source File: TexHover.java From texlipse with Eclipse Public License 1.0 | 5 votes |
public IRegion getHoverRegion(ITextViewer textViewer, int offset) { try { // Extract current line int lineNr = textViewer.getDocument().getLineOfOffset(offset); int lOffset = textViewer.getDocument().getLineOffset(lineNr); String line = textViewer.getDocument().get(lOffset, textViewer.getDocument().getLineLength(lineNr)); int start = offset - lOffset; IRegion r = LatexParserUtils.getCommand(line, start); if (r == null) return new Region(offset, 0); IRegion rArg = LatexParserUtils.getCommandArgument(line, r.getOffset()); if (rArg == null) return new Region(lOffset + r.getOffset(), r.getLength()); String command = line.substring(r.getOffset()+1, r.getOffset() + r.getLength()); if (command.indexOf("cite") >= 0 && start > r.getOffset() + r.getLength()) { //Return only the citation entry, not the full command string int cEnd = rArg.getOffset() + rArg.getLength(); int regionStart = line.lastIndexOf(',', start) < line.lastIndexOf('{', start) ? line.lastIndexOf('{', start) + 1 : line.lastIndexOf(',', start) + 1; int lastComma = line.indexOf(',', start); if (lastComma >= 0 && lastComma < cEnd) { return new Region(lOffset + regionStart, lastComma - regionStart); } else { return new Region(lOffset + regionStart, cEnd - regionStart); } } int length = rArg.getOffset() - r.getOffset() + rArg.getLength() + 1; return new Region(lOffset + r.getOffset(), length); } catch (BadLocationException ex) { return new Region(offset, 0); } }
Example 11
Source File: NonRuleBasedDamagerRepairer.java From birt with Eclipse Public License 1.0 | 5 votes |
/** * @see IPresentationDamager#getDamageRegion(ITypedRegion, DocumentEvent, * boolean) */ public IRegion getDamageRegion( ITypedRegion partition, DocumentEvent event, boolean documentPartitioningChanged ) { if ( !documentPartitioningChanged ) { try { IRegion info = fDocument.getLineInformationOfOffset( event.getOffset( ) ); int start = Math.max( partition.getOffset( ), info.getOffset( ) ); int end = event.getOffset( ) + ( event.getText( ) == null ? event.getLength( ) : event.getText( ).length( ) ); if ( info.getOffset( ) <= end && end <= info.getOffset( ) + info.getLength( ) ) { // optimize the case of the same line end = info.getOffset( ) + info.getLength( ); } else { end = endOfLineOf( end ); } end = Math.min( partition.getOffset( ) + partition.getLength( ), end ); return new Region( start, end - start ); } catch ( BadLocationException x ) { } } return partition; }
Example 12
Source File: TypeScriptAutoIndentStrategy.java From typescript.java with MIT License | 5 votes |
/** * 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 13
Source File: MarkerPlacementStrategy.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
private boolean isDuplicate(IResource resource, IRegion position, String msg) throws CoreException { int start = position.getOffset(); int end = position.getOffset() + position.getLength(); return MarkerUtilities.findMarker(markerId, start, end, resource, msg, true) != null; }
Example 14
Source File: DefaultCodeFormatter.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private TextEdit formatComment(int kind, String source, int indentationLevel, String lineSeparator, IRegion[] regions) { Object oldOption = oldCommentFormatOption(); boolean isFormattingComments = false; if (oldOption == null) { switch (kind & K_MASK) { case K_SINGLE_LINE_COMMENT: isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT)); break; case K_MULTI_LINE_COMMENT: isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT)); break; case K_JAVA_DOC: isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT)); } } else { isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(oldOption); } if (isFormattingComments) { if (lineSeparator != null) { this.preferences.line_separator = lineSeparator; } else { this.preferences.line_separator = Util.LINE_SEPARATOR; } this.preferences.initial_indentation_level = indentationLevel; if (this.codeSnippetParsingUtil == null) this.codeSnippetParsingUtil = new CodeSnippetParsingUtil(); this.codeSnippetParsingUtil.parseCompilationUnit(source.toCharArray(), getDefaultCompilerOptions(), true); this.newCodeFormatter = new CodeFormatterVisitor(this.preferences, this.options, regions, this.codeSnippetParsingUtil, true); IRegion coveredRegion = getCoveredRegion(regions); int start = coveredRegion.getOffset(); int end = start + coveredRegion.getLength(); this.newCodeFormatter.formatComment(kind, source, start, end, indentationLevel); return this.newCodeFormatter.scribe.getRootEdit(); } return null; }
Example 15
Source File: LangHyperlinkDetector.java From goclipse with Eclipse Public License 1.0 | 4 votes |
public static int getEndPos(IRegion region) { return region.getOffset() + region.getLength(); }
Example 16
Source File: ExcludeRegionList.java From APICloud-Studio with GNU General Public License v3.0 | 4 votes |
public void excludeRegion(IRegion region, EXCLUDE_STRATEGY strategy) { int start = region.getOffset(); int end = region.getOffset() + region.getLength(); if (!excludes.isEmpty()) { for (Iterator<IRegion> i = excludes.iterator(); i.hasNext();) { final IRegion r = i.next(); final int rEnd = r.getOffset() + r.getLength(); if (r.getOffset() <= end && start <= rEnd) { if (region.getOffset() >= r.getOffset() && region.getOffset() + region.getLength() <= rEnd) { // new region is inside one of the old regions return; } // calculate the surrounding bounds if (r.getOffset() < start) { start = r.getOffset(); } if (rEnd > end) { end = rEnd; } i.remove(); } } } // use input region or create the new one if (start == region.getOffset() && end == region.getOffset() + region.getLength()) { excludes.add(region); excludeActions.put(region, strategy); } else { Region newRegion = new Region(start, end - start); excludes.add(newRegion); excludeActions.put(newRegion, strategy); } Collections.sort(excludes, REGION_COMPARATOR); }
Example 17
Source File: AnonymousTypeCompletionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
@Override protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException { fImportRewrite= impRewrite; String newBody= createNewBody(impRewrite); if (newBody == null) return false; CompletionProposal coreProposal= ((MemberProposalInfo)getProposalInfo()).fProposal; boolean isAnonymousConstructorInvoc= coreProposal.getKind() == CompletionProposal.ANONYMOUS_CLASS_CONSTRUCTOR_INVOCATION; boolean replacementStringEndsWithParentheses= isAnonymousConstructorInvoc || getReplacementString().endsWith(")"); //$NON-NLS-1$ // construct replacement text: an expression to be formatted StringBuffer buf= new StringBuffer("new A("); //$NON-NLS-1$ if (!replacementStringEndsWithParentheses || isAnonymousConstructorInvoc) buf.append(')'); buf.append(newBody); // use the code formatter String lineDelim= TextUtilities.getDefaultLineDelimiter(document); final IJavaProject project= fCompilationUnit.getJavaProject(); IRegion lineInfo= document.getLineInformationOfOffset(getReplacementOffset()); int indent= Strings.computeIndentUnits(document.get(lineInfo.getOffset(), lineInfo.getLength()), project); Map<String, String> options= project != null ? project.getOptions(true) : JavaCore.getOptions(); options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES, DefaultCodeFormatterConstants.TRUE); String replacementString= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, buf.toString(), 0, lineDelim, options); int lineEndOffset= lineInfo.getOffset() + lineInfo.getLength(); int p= offset; char ch= document.getChar(p); while (p < lineEndOffset) { if (ch == '(' || ch == ')' || ch == ';' || ch == ',') break; ch= document.getChar(++p); } if (ch != ';' && ch != ',' && ch != ')') replacementString= replacementString + ';'; replacementString= Strings.changeIndent(replacementString, 0, project, CodeFormatterUtil.createIndentString(indent, project), lineDelim); int beginIndex= replacementString.indexOf('('); if (!isAnonymousConstructorInvoc) beginIndex++; replacementString= replacementString.substring(beginIndex); int pos= offset; if (isAnonymousConstructorInvoc && (insertCompletion() ^ isInsertModeToggled())) { // Keep existing code int endPos= pos; ch= document.getChar(endPos); while (endPos < lineEndOffset && ch != '(' && ch != ')' && ch != ';' && ch != ',' && !Character.isWhitespace(ch)) ch= document.getChar(++endPos); int keepLength= endPos - pos; if (keepLength > 0) { String keepStr= document.get(pos, keepLength); replacementString= replacementString + keepStr; setCursorPosition(replacementString.length() - keepLength); } } else setCursorPosition(replacementString.length()); setReplacementString(replacementString); if (pos < document.getLength() && document.getChar(pos) == ')') { int currentLength= getReplacementLength(); if (replacementStringEndsWithParentheses) setReplacementLength(currentLength + pos - offset); else setReplacementLength(currentLength + pos - offset + 1); } return false; }
Example 18
Source File: IndentAction.java From typescript.java with MIT License | 4 votes |
/** * Computes and returns the indentation for a javadoc line. The line must be * inside a javadoc comment. * * @param document * the document * @param line * the line in document * @param scanner * the scanner * @param partition * the javadoc partition * @return the indent, or <code>null</code> if not computable * @throws BadLocationException * */ private String computeJavadocIndent(IDocument document, int line, JavaHeuristicScanner scanner, ITypedRegion partition) throws BadLocationException { if (line == 0) // impossible - the first line is never inside a javadoc // comment return null; // don't make any assumptions if the line does not start with \s*\* - it // might be // commented out code, for which we don't want to change the indent final IRegion lineInfo = document.getLineInformation(line); final int lineStart = lineInfo.getOffset(); final int lineLength = lineInfo.getLength(); final int lineEnd = lineStart + lineLength; int nonWS = scanner.findNonWhitespaceForwardInAnyPartition(lineStart, lineEnd); if (nonWS == JavaHeuristicScanner.NOT_FOUND || document.getChar(nonWS) != '*') { if (nonWS == JavaHeuristicScanner.NOT_FOUND) return document.get(lineStart, lineLength); return document.get(lineStart, nonWS - lineStart); } // take the indent from the previous line and reuse IRegion previousLine = document.getLineInformation(line - 1); int previousLineStart = previousLine.getOffset(); int previousLineLength = previousLine.getLength(); int previousLineEnd = previousLineStart + previousLineLength; StringBuffer buf = new StringBuffer(); int previousLineNonWS = scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd); if (previousLineNonWS == JavaHeuristicScanner.NOT_FOUND || document.getChar(previousLineNonWS) != '*') { // align with the comment start if the previous line is not an // asterisked line previousLine = document.getLineInformationOfOffset(partition.getOffset()); previousLineStart = previousLine.getOffset(); previousLineLength = previousLine.getLength(); previousLineEnd = previousLineStart + previousLineLength; previousLineNonWS = scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd); if (previousLineNonWS == JavaHeuristicScanner.NOT_FOUND) previousLineNonWS = previousLineEnd; // add the initial space // TODO this may be controlled by a formatter preference in the // future buf.append(' '); } String indentation = document.get(previousLineStart, previousLineNonWS - previousLineStart); buf.insert(0, indentation); return buf.toString(); }
Example 19
Source File: CopiedOverviewRuler.java From Pydev with Eclipse Public License 1.0 | 4 votes |
/** * Returns the position of the first annotation found in the given line range. * * @param lineNumbers the line range * @return the position of the first found annotation */ protected Position getAnnotationPosition(int[] lineNumbers) { if (lineNumbers[0] == -1) { return null; } Position found = null; try { IDocument d = fTextViewer.getDocument(); IRegion line = d.getLineInformation(lineNumbers[0]); int start = line.getOffset(); line = d.getLineInformation(lineNumbers[lineNumbers.length - 1]); int end = line.getOffset() + line.getLength(); for (int i = fAnnotationsSortedByLayer.size() - 1; i >= 0; i--) { Object annotationType = fAnnotationsSortedByLayer.get(i); Iterator e = new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY); while (e.hasNext() && found == null) { Annotation a = (Annotation) e.next(); if (a.isMarkedDeleted()) { continue; } if (skip(a.getType())) { continue; } Position p = fModel.getPosition(a); if (p == null) { continue; } int posOffset = p.getOffset(); int posEnd = posOffset + p.getLength(); IRegion region = d.getLineInformationOfOffset(posEnd); // trailing empty lines don't count if (posEnd > posOffset && region.getOffset() == posEnd) { posEnd--; region = d.getLineInformationOfOffset(posEnd); } if (posOffset <= end && posEnd >= start) { found = p; } } } } catch (BadLocationException x) { } return found; }
Example 20
Source File: DocumentHelper.java From tlaplus with MIT License | 3 votes |
/** * Combines the effect of backwards and forwards region expansion * @param document * @param offset * @param defaultWordDetector * @return A {@link WordRegion} or null if no region could be found. * @throws BadLocationException */ public static WordRegion getRegionExpandedBoth(IDocument document, int documentOffset, IWordDetector detector) throws BadLocationException { final IRegion backwards = getRegionExpandedBackwards(document, documentOffset, detector); final IRegion forwards = getRegionExpandedForwards(document, documentOffset, detector); final String word = document.get(backwards.getOffset(), backwards.getLength() + forwards.getLength()); return new WordRegion(backwards.getOffset(), backwards.getLength() + forwards.getLength(), word); }