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

The following examples show how to use org.eclipse.jface.text.IDocument#getLineLength() . 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: AbstractNode.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the position of the node inside the given document. <br/>
 * The position matches the area that contains all the node's content.
 * 
 * @param document
 * @return position inside the document
 */
public Position getPosition(IDocument document) {
    boolean selectEntireElement = false;
    int startLine = getStart().getLine();
    int offset = 0;
    int length = 0;

    int endLine = getEnd().getLine();
    int endCol = getEnd().getColumn();
    try {
        offset = document.getLineOffset(startLine);
        if (selectEntireElement) {
            length = (document.getLineOffset(endLine) + endCol) - offset;
        } else if (startLine < document.getNumberOfLines() - 1) {
            length = document.getLineOffset(startLine+1) - offset;
        } else {
            length = document.getLineLength(startLine);
        }
    } catch (BadLocationException e) {
        return new Position(0);
    }

    return new Position(Math.max(0, offset), length);
}
 
Example 2
Source File: JsniAutoEditStrategy.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the line number of the next bracket after end.
 *
 * @param document - the document being parsed
 * @param line - the line to start searching back from
 * @param end - the end position to search back from
 * @param closingBracketIncrease - the number of brackets to skip
 * @return the line number of the next matching bracket after end
 * @throws BadLocationException in case the line numbers are invalid in the
 *           document
 */
protected int findMatchingOpenBracket(IDocument document, int line, int end,
    int closingBracketIncrease) throws BadLocationException {

  int start = document.getLineOffset(line);
  int brackcount = getBracketCount(document, start, end, false)
      - closingBracketIncrease;

  // sum up the brackets counts of each line (closing brackets count negative,
  // opening positive) until we find a line the brings the count to zero
  while (brackcount < 0) {
    line--;
    if (line < 0) {
      return -1;
    }
    start = document.getLineOffset(line);
    end = start + document.getLineLength(line) - 1;
    brackcount += getBracketCount(document, start, end, false);
  }
  return line;
}
 
Example 3
Source File: DocumentUtilN4.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Similar to {@link IDocument#getLineInformationOfOffset(int)}, but the client can provide a text region instead of
 * only an offset. If the given region spans multiple lines, all affected lines will be returned, i.e. entire line
 * containing beginning of region, all lines contained in the region, and entire line containing the end of the
 * region.
 */
public static IRegion getLineInformationOfRegion(IDocument doc, int offset, int length,
		boolean includeLineDelimiterOfLastLine) throws BadLocationException {
	// get the line containing the beginning of the given text region
	final int firstLineNo = doc.getLineOfOffset(offset);
	// get the line containing the end of the given text region
	// (may be the same line if removal does not span multiple lines)
	final int lastLineNo = doc.getLineOfOffset(offset + length);
	// compute result
	final int startOffset = doc.getLineOffset(firstLineNo);
	final int endOffset = doc.getLineOffset(lastLineNo) + (includeLineDelimiterOfLastLine ?
			doc.getLineLength(lastLineNo) // includes line delimiters!
			: doc.getLineInformation(lastLineNo).getLength()); // does *not* include line delimiters!
	return new Region(
			startOffset,
			endOffset - startOffset);
}
 
Example 4
Source File: SpellChecker.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Check spelling of the entire document.
 * 
 * @param doc the document
 * @param file
 */
private void checkDocumentSpelling(IDocument doc, IFile file, IProgressMonitor monitor) {
    deleteOldProposals(file);
    //doc.addDocumentListener(instance);
    try {
        int num = doc.getNumberOfLines();
        monitor.beginTask("Check spelling", num);
        for (int i = 0; i < num; i++) {
            if (monitor.isCanceled()) break;
            int offset = doc.getLineOffset(i);
            int length = doc.getLineLength(i);
            String line = doc.get(offset, length);
            checkLineSpelling(line, offset, i+1, file);
            monitor.worked(1);
        }
    } catch (BadLocationException e) {
        TexlipsePlugin.log("Checking spelling on a line", e);
    }
    stopProgram();
}
 
Example 5
Source File: TexAutoIndentStrategy.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Removes indentation if \end{...} is detected. We assume that 
 * command.text is the closing brace '}'
 * 
 * @param document
 *            Document where new line is detected.
 * @param command
 *            Command that represent the change of the document (here command text is "}").
 */
private void smartIndentAfterBrace(IDocument document, DocumentCommand command) {
    try {
        int commandOffset = command.offset;
        int line = document.getLineOfOffset(commandOffset);
        int lineOffset = document.getLineOffset(line);
        int lineLength = document.getLineLength(line);
        // the original line text
        String lineText = document.get(lineOffset, lineLength);
        // modified linetext
        String text = lineText.trim().concat(command.text);
        
        if (text.startsWith("\\end")) {
        	IRegion r = LatexParserUtils.getCommandArgument(text, 0);
        	//String envName = "";
        	if (r == null) {
        		super.customizeDocumentCommand(document, command);
        		return;
        	}
    		String envName = text.substring(r.getOffset(), r.getOffset() + r.getLength());            	
        	String docText = document.get();
        	IRegion rBegin = LatexParserUtils.findMatchingBeginEnvironment(docText, envName, lineOffset);
        	int beginLineNr = document.getLineOfOffset(rBegin.getOffset());
        	int beginLineLength = document.getLineLength(beginLineNr);
        	int beginLineStart = document.getLineOffset(beginLineNr);
        	String beginLine = document.get(beginLineStart, beginLineLength);
        	String beginInd = getIndentation(beginLine);
        	command.text = beginInd + text;
        	command.length = commandOffset - lineOffset;
        	command.offset = lineOffset;
        } else {
        	super.customizeDocumentCommand(document, command);
        }
        
    } catch (BadLocationException e) {
        TexlipsePlugin.log("TexAutoIndentStrategy:SmartIndentAfterBracket", e);
    }
}
 
Example 6
Source File: JsniAutoEditStrategy.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the content of the given line without the leading whitespace.
 *
 * @param document - the document being parsed
 * @param line - the line being searched
 * @return the content of the given line without the leading whitespace
 * @throws BadLocationException in case <code>line</code> is invalid in the
 *           document
 */
protected String getIndentOfLine(IDocument document, int line)
    throws BadLocationException {
  if (line > -1) {
    int start = document.getLineOffset(line);
    int end = start + document.getLineLength(line) - 1;
    int whiteend = findEndOfWhiteSpace(document, start, end);
    return document.get(start, whiteend - start);
  }
  return "";
}
 
Example 7
Source File: SelectionKeeper.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
private int getLineLength(IDocument doc, int line) {
    try {
        return doc.getLineLength(line);
    } catch (BadLocationException e) {
        return 0;
    }
}
 
Example 8
Source File: JsonQuickAssistProcessor.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
protected List<IMarker> getMarkersFor(ISourceViewer sourceViewer, int offset) throws BadLocationException {
    final IDocument document = sourceViewer.getDocument();

    int line = document.getLineOfOffset(offset);
    int lineOffset = document.getLineOffset(line);

    String delim = document.getLineDelimiter(line);
    int delimLength = delim != null ? delim.length() : 0;
    int lineLength = document.getLineLength(line) - delimLength;

    return getMarkersFor(sourceViewer, lineOffset, lineLength);
}
 
Example 9
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 10
Source File: KillLineHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument,
 *      ITextSelection, ExecutionEvent)
 */
@Override
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection,
		ExecutionEvent event) throws BadLocationException {
	int uArg = getUniversalCount();
	int offset = getCursorOffset(editor, currentSelection);
	int offsetLine = document.getLineOfOffset(offset);
	if (uArg == 1) {
		try {
			// gnu emacs: If the variable `kill-whole-line' is non-`nil', `C-k' at the very
			// beginning of a line kills the entire line including the following newline.
			boolean killWhole = isKillWholeLine() && (offset == document.getLineOffset(offsetLine));
			executeCommand(killWhole ? CUT_LINE : CUT_LINE_TO_END, null, editor);
		} catch (Exception e) {}
	} else {
		try {
			// flag us as a kill command
			KillRing.getInstance().setKill(IEmacsPlusCommandDefinitionIds.KILL_LINE, false);
			int lastOffset = offset;
			// note that line numbers start from 0
			int maxLine = document.getNumberOfLines() - 1;
			int endLine = uArg + document.getLineOfOffset(offset);
			// if range includes eof
			if (endLine >= maxLine) {
				// delete through to last character
				lastOffset = document.getLineOffset(maxLine) + document.getLineLength(maxLine);
			} else {
				// delete by whole lines
				lastOffset = document.getLineOffset(Math.min(Math.max(endLine, 0), maxLine));
			}
			updateText(document, ((lastOffset >= offset ? offset : lastOffset)), Math.abs(lastOffset - offset),
					EMPTY_STR);
		} finally {
			// clear kill command flag
			KillRing.getInstance().setKill(null, false);
		}
	}
	return NO_OFFSET;
}
 
Example 11
Source File: PropertyFileDocumentModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void parsePropertyDocument(IDocument document) {
      fKeyValuePairs = new ArrayList<KeyValuePairModell>();

      SimpleLineReader reader = new SimpleLineReader(document);
      int offset = 0;
      String line = reader.readLine();
      int leadingWhiteSpaces = 0;
      while (line != null) {
          if (!SimpleLineReader.isCommentOrWhiteSpace(line)) {
              int idx = getIndexOfSeparationCharacter(line);
              if (idx != -1) {
			String key= line.substring(0, idx);
			String trimmedKey= key.trim();
			String value= line.substring(idx + 1);
			String trimmedValue= Strings.trimLeadingTabsAndSpaces(value);
			int length= key.length() + 1 + value.length();
                  fKeyValuePairs.add(new KeyValuePairModell(trimmedKey, trimmedValue, offset, length, leadingWhiteSpaces));
                  leadingWhiteSpaces = 0;
              }
          } else {
              leadingWhiteSpaces += line.length();
          }
          offset += line.length();
          line = reader.readLine();
      }
      int lastLine= document.getNumberOfLines() - 1;
      boolean needsNewLine= false;
      try {
      	needsNewLine= !(document.getLineLength(lastLine) == 0);
} catch (BadLocationException ignore) {
	// treat last line having no new line
}
      LastKeyValuePair lastKeyValuePair = new LastKeyValuePair(offset, needsNewLine);
fKeyValuePairs.add(lastKeyValuePair);
  }
 
Example 12
Source File: DocumentHelper.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
public static String getLineText(IDocument document, int line, boolean withLineDelimiter)
		throws BadLocationException {
	int lo = document.getLineOffset(line);
	int ll = document.getLineLength(line);
	if (!withLineDelimiter) {
		String delim = document.getLineDelimiter(line);
		ll = ll - (delim != null ? delim.length() : 0);
	}
	return document.get(lo, ll);
}
 
Example 13
Source File: TMPresentationReconciler.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
private int getTokenLengh(int tokenStartIndex, TMToken nextToken, int line, IDocument document)
		throws BadLocationException {
	if (nextToken != null) {
		return nextToken.startIndex - tokenStartIndex;
	}
	return document.getLineLength(line) - tokenStartIndex;
}
 
Example 14
Source File: DefaultJavaFoldingStructureProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Aligns <code>region</code> to start and end at a line offset. The region's start is
 * decreased to the next line offset, and the end offset increased to the next line start or the
 * end of the document. <code>null</code> is returned if <code>region</code> is
 * <code>null</code> itself or does not comprise at least one line delimiter, as a single line
 * cannot be folded.
 *
 * @param region the region to align, may be <code>null</code>
 * @param ctx the folding context
 * @return a region equal or greater than <code>region</code> that is aligned with line
 *         offsets, <code>null</code> if the region is too small to be foldable (e.g. covers
 *         only one line)
 */
protected final IRegion alignRegion(IRegion region, FoldingStructureComputationContext ctx) {
	if (region == null)
		return null;

	IDocument document= ctx.getDocument();

	try {

		int start= document.getLineOfOffset(region.getOffset());
		int end= document.getLineOfOffset(region.getOffset() + region.getLength());
		if (start >= end)
			return null;

		int offset= document.getLineOffset(start);
		int endOffset;
		if (document.getNumberOfLines() > end + 1)
			endOffset= document.getLineOffset(end + 1);
		else
			endOffset= document.getLineOffset(end) + document.getLineLength(end);

		return new Region(offset, endOffset - offset);

	} catch (BadLocationException x) {
		// concurrent modification
		return null;
	}
}
 
Example 15
Source File: TexAutoIndentStrategy.java    From texlipse with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Inserts an \item or an \item[] string. Works ONLY it \item is found at
 * the beginning of a preceeding line
 * 
 * @param d
 * @param c
 * @return <code>true</code> if item was inserted, <code>false</code>
 *         otherwise
 */
private boolean itemInserted(IDocument d, DocumentCommand c) {
    itemSetted = false;
    try {
        int lineNr = d.getLineOfOffset(c.offset);
        int lineEnd = d.getLineOffset(lineNr) + d.getLineLength(lineNr);
        //Test if there is no text behind the cursor in the line
        if (c.offset < lineEnd - 1) return false;
        int currentLineNr = lineNr;
        
        String indentation = null;
        while (lineNr >= 0) {
        	IRegion r = d.getLineInformation(lineNr);
        	String prevLine = d.get(r.getOffset(), r.getLength());
        	if (indentation == null) indentation = getIndentation(prevLine);
        	
            if (prevLine.trim().startsWith("\\item")) {
                StringBuilder buf = new StringBuilder(c.text);
                buf.append(indentation);
                if (prevLine.trim().startsWith("\\item[")) {
                	c.shiftsCaret = false;
                	c.caretOffset = c.offset
                	+ buf.length() + 5
                	+ c.text.length();
                	buf.append("\\item[]");
                } else {
                	buf.append("\\item ");
                }
                itemSetted = true;
                itemAtLine = currentLineNr;
                c.text = buf.toString();
                return true;
            }
            if (prevLine.trim().startsWith("\\begin") || prevLine.trim().startsWith("\\end"))
                return false;
            lineNr--;
        }
    } catch (BadLocationException e) {
    	//Ignore
    }
    return false;
}
 
Example 16
Source File: ImpexDocumentPartitioner.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 4 votes vote down vote up
private int getLineEndOffset(int line, IDocument document) throws BadLocationException {
	
	int length = document.getLineLength(line);
	int start = document.getLineOffset(line);
	return start + length - 1;
}
 
Example 17
Source File: AddBlockCommentHandler.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    try {
        ITextSelection selection = WorkbenchUtils.getActiveTextSelection();
        IDocument      doc       = WorkbenchUtils.getActiveDocument();
        IEditorInput   input     = WorkbenchUtils.getActiveInput();
        IEditorPart    editor    = WorkbenchUtils.getActiveEditor(false);

        boolean isTextOperationAllowed = (selection != null) && (doc != null) 
                                      && (input != null)     && (editor != null) 
                                      && (editor instanceof ModulaEditor);

        if (isTextOperationAllowed) {
            ITextEditor iTextEditor = (ITextEditor)editor;
            final ITextOperationTarget operationTarget = (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
            String commentPrefix = ((SourceCodeTextEditor)editor).getEOLCommentPrefix();
            isTextOperationAllowed = (operationTarget != null)
                                  && (operationTarget instanceof TextViewer)
                                  && (validateEditorInputState(iTextEditor))
                                  && (commentPrefix != null);
            
            if ((isTextOperationAllowed)) {
                int startLine = selection.getStartLine();
                int endLine = selection.getEndLine(); 
                int selOffset = selection.getOffset();
                int selLen = selection.getLength();
                int realEndLine = doc.getLineOfOffset(selOffset + selLen); // for selection end at pos=0 (endLine is line before here) 
                
                // Are cursor and anchor at 0 positions?
                boolean is0pos = false;
                if (doc.getLineOffset(startLine) == selOffset) {
                    if ((doc.getLineOffset(endLine) + doc.getLineLength(endLine) == selOffset + selLen)) {
                        is0pos = true;
                    }
                }
                
                
                ArrayList<ReplaceEdit> edits = null;
                int offsAfter[] = {0};
                if (is0pos || selLen == 0) {
                    edits = commentWholeLines(startLine, (selLen == 0) ? startLine : endLine, realEndLine, doc, offsAfter);
                } else {
                    edits = commentRange(selOffset, selLen, "(*", "*)", offsAfter); //$NON-NLS-1$ //$NON-NLS-2$
                }
                
                if (edits != null && !edits.isEmpty()) {
                    DocumentRewriteSession drws = null;
                    try {
                        if (doc instanceof IDocumentExtension4) {
                            drws = ((IDocumentExtension4)doc).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
                        }
                        MultiTextEdit edit= new MultiTextEdit(0, doc.getLength());
                        edit.addChildren((TextEdit[]) edits.toArray(new TextEdit[edits.size()]));
                        edit.apply(doc, TextEdit.CREATE_UNDO);
                        iTextEditor.getSelectionProvider().setSelection(new TextSelection(offsAfter[0], 0));
                    }
                    finally {
                        if (doc instanceof IDocumentExtension4 && drws != null) {
                            ((IDocumentExtension4)doc).stopRewriteSession(drws);
                        }
                    }
                    
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 18
Source File: DocumentHelper.java    From tm4e with Eclipse Public License 1.0 4 votes vote down vote up
public static IRegion getRegion(IDocument document, int fromLine, int toLine) throws BadLocationException {
	int startOffset = document.getLineOffset(fromLine);
	int endOffset = document.getLineOffset(toLine) + document.getLineLength(toLine);
	return new Region(startOffset, endOffset - startOffset);
}
 
Example 19
Source File: AssistAssignCompletionProposal.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void apply(IDocument document) {
    try {
        //default apply
        int lineOfOffset = document.getLineOfOffset(fReplacementOffset);
        document.replace(fReplacementOffset, fReplacementLength, fReplacementString);

        if (SharedCorePlugin.inTestMode()) {
            return;
        }
        int lineOffset = document.getLineOffset(lineOfOffset);
        int lineLength = document.getLineLength(lineOfOffset);
        String lineDelimiter = document.getLineDelimiter(lineOfOffset);
        int lineDelimiterLen = lineDelimiter != null ? lineDelimiter.length() : 0;

        ISourceViewer viewer = sourceViewer;

        LinkedModeModel model = new LinkedModeModel();
        LinkedPositionGroup group = new LinkedPositionGroup();

        //the len-3 is because of the end of the string: " = " because the replacement string is
        //something like "xxx = "
        ProposalPosition proposalPosition = new ProposalPosition(document, fReplacementOffset,
                fReplacementString.length() - 3, 0, new ICompletionProposal[0]);
        group.addPosition(proposalPosition);

        model.addGroup(group);
        model.forceInstall();

        final LinkedModeUI ui = new EditorLinkedModeUI(model, viewer);
        ui.setExitPosition(viewer, lineOffset + lineLength - lineDelimiterLen, 0, Integer.MAX_VALUE);
        Runnable r = new Runnable() {
            @Override
            public void run() {
                ui.enter();
            }
        };
        RunInUiThread.async(r);

    } catch (Throwable x) {
        // ignore
        Log.log(x);
    }
}
 
Example 20
Source File: JavaMoveLinesAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Given a selection on a document, computes the lines fully or partially covered by
 * <code>selection</code>. A line in the document is considered covered if
 * <code>selection</code> comprises any characters on it, including the terminating delimiter.
 * <p>Note that the last line in a selection is not considered covered if the selection only
 * comprises the line delimiter at its beginning (that is considered part of the second last
 * line).
 * As a special case, if the selection is empty, a line is considered covered if the caret is
 * at any position in the line, including between the delimiter and the start of the line. The
 * line containing the delimiter is not considered covered in that case.
 * </p>
 *
 * @param document the document <code>selection</code> refers to
 * @param selection a selection on <code>document</code>
 * @param viewer the <code>ISourceViewer</code> displaying <code>document</code>
 * @return a selection describing the range of lines (partially) covered by
 * <code>selection</code>, without any terminating line delimiters
 * @throws BadLocationException if the selection is out of bounds (when the underlying document has changed during the call)
 */
private ITextSelection getMovingSelection(IDocument document, ITextSelection selection, ISourceViewer viewer) throws BadLocationException {
	int low= document.getLineOffset(selection.getStartLine());
	int endLine= selection.getEndLine();
	int high= document.getLineOffset(endLine) + document.getLineLength(endLine);

	// get everything up to last line without its delimiter
	String delim= document.getLineDelimiter(endLine);
	if (delim != null)
		high -= delim.length();

	return new TextSelection(document, low, high - low);
}