Java Code Examples for org.eclipse.jface.text.IDocument#getLineOfOffset()
The following examples show how to use
org.eclipse.jface.text.IDocument#getLineOfOffset() .
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: StubUtility.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private static String fixEmptyVariables(TemplateBuffer buffer, String[] variables) throws MalformedTreeException, BadLocationException { IDocument doc= new Document(buffer.getString()); int nLines= doc.getNumberOfLines(); MultiTextEdit edit= new MultiTextEdit(); HashSet<Integer> removedLines= new HashSet<Integer>(); for (int i= 0; i < variables.length; i++) { TemplateVariable position= findVariable(buffer, variables[i]); // look if Javadoc tags have to be added if (position == null || position.getLength() > 0) { continue; } int[] offsets= position.getOffsets(); for (int k= 0; k < offsets.length; k++) { int line= doc.getLineOfOffset(offsets[k]); IRegion lineInfo= doc.getLineInformation(line); int offset= lineInfo.getOffset(); String str= doc.get(offset, lineInfo.getLength()); if (Strings.containsOnlyWhitespaces(str) && nLines > line + 1 && removedLines.add(new Integer(line))) { int nextStart= doc.getLineOffset(line + 1); edit.addChild(new DeleteEdit(offset, nextStart - offset)); } } } edit.apply(doc, 0); return doc.get(); }
Example 2
Source File: ReverseRegionHandler.java From e4macs with Eclipse Public License 1.0 | 6 votes |
/** * @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 { ITextSelection selection = getLineSelection(editor,document,currentSelection); if (selection != null) { int offset = selection.getOffset(); int endOffset = offset+selection.getLength(); int begin = document.getLineOfOffset(offset); int end = document.getLineOfOffset(endOffset); if (begin != end && begin < end) { // grab the lines int len = end-begin+1; String[] array = new String[len]; for (int i = 0; i < len; i++) { IRegion region = document.getLineInformation(begin+i); array[i] = document.get(region.getOffset(),region.getLength()); } // and reverse them updateLines(document,new TextSelection(document,offset,endOffset-offset),reverse(array)); } } else { EmacsPlusUtils.showMessage(editor, NO_REGION, true); } return NO_OFFSET; }
Example 3
Source File: XtendProposalProvider.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
public void completeInRichString(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { INode node = context.getCurrentNode(); ITextRegion textRegion = node.getTextRegion(); int offset = textRegion.getOffset(); int length = textRegion.getLength(); String currentNodeText = node.getText(); if (currentNodeText.startsWith("\u00BB") && offset + 1 <= context.getOffset() || currentNodeText.startsWith("'''") && offset + 3 <= context.getOffset()) { if (context.getOffset() > offset && context.getOffset() < offset + length) addGuillemotsProposal(context, acceptor); } else if (currentNodeText.startsWith("\u00AB\u00AB")) { try { IDocument document = context.getViewer().getDocument(); int nodeLine = document.getLineOfOffset(offset); int completionLine = document.getLineOfOffset(context.getOffset()); if (completionLine > nodeLine) { addGuillemotsProposal(context, acceptor); } } catch (BadLocationException e) { // ignore } } }
Example 4
Source File: SemanticHighlightingDiffCalculator.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
protected int getLineShift(IDocument oldState, DocumentEvent event) throws BadLocationException { // Insert edit. if (event.fLength == 0) { Preconditions.checkNotNull(event.fText, "fText"); int beforeEndLine = event.fDocument.getLineOfOffset(event.fOffset + event.fLength); int afterEndLine = event.fDocument.getLineOfOffset(event.fOffset + event.fText.length()); return afterEndLine - beforeEndLine; // Delete edit. } else if (event.fText == null || event.fText.isEmpty()) { return event.fDocument.getLineOfOffset(event.fOffset) - oldState.getLineOfOffset(event.fOffset + event.fLength); // Replace edit. } else { int startLine = oldState.getLineOfOffset(event.fOffset + event.fLength); int lineShift = event.fDocument.getLineOfOffset(event.fOffset + event.fText.length()) - startLine; return lineShift; } }
Example 5
Source File: IndentForTabHandler.java From e4macs with Eclipse Public License 1.0 | 6 votes |
/** * Insert tab/spaces at selection offset and each subsequent line origin * * @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 { // if we're here, either ^U or no relevant ^I ColumnSupport cs = new ColumnSupport(document,editor); String tab = cs.getSpaces(0,cs.getTabWidth()); int off = currentSelection.getOffset(); Position coff = new Position(getCursorOffset(editor,currentSelection),0); try { document.addPosition(coff); int begin = document.getLineOfOffset(off); int end = document.getLineOfOffset(off+ currentSelection.getLength()); if (begin != end) { while (++begin <= end) { document.replace(document.getLineOffset(begin), 0, tab); } } document.replace(off, 0, tab); } finally { document.removePosition(coff); } return coff.offset; }
Example 6
Source File: XtextMarkerRulerAction.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
@Override public void run() { try { // Move offset to the line of the annotation, if necessary IDocument document = getDocument(); int annotationLine = ruler.getLineOfLastMouseButtonActivity(); int annotationLineOffet = document.getLineOffset(annotationLine); Point currentSelection = textEditor.getInternalSourceViewer().getSelectedRange(); int currentLine = document.getLineOfOffset(currentSelection.x); if (currentLine != annotationLine) textEditor.getInternalSourceViewer().setSelectedRange(annotationLineOffet, 0); // show QuickFix dialog ITextOperationTarget operation = textEditor.getAdapter(ITextOperationTarget.class); final int opCode = ISourceViewer.QUICK_ASSIST; if (operation != null && operation.canDoOperation(opCode)) operation.doOperation(opCode); } catch (BadLocationException e) { // Ignore -> do nothing } }
Example 7
Source File: Location.java From Pydev with Eclipse Public License 1.0 | 5 votes |
/** * Utility: Converts document's offset to Location * @return Location */ static public Location offsetToLocation(IDocument document, int offset) { try { int line = document.getLineOfOffset(offset); int line_start = document.getLineOffset(line); return new Location(line, offset - line_start); } catch (BadLocationException e) { return new Location(); } }
Example 8
Source File: TexEditorTools.java From texlipse with Eclipse Public License 1.0 | 5 votes |
/** * 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 9
Source File: JavaMoveLinesAction.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Checks if <code>selection</code> is contained by the visible region of <code>viewer</code>. * As a special case, a selection is considered contained even if it extends over the visible * region, but the extension stays on a partially contained line and contains only white space. * * @param selection the selection to be checked * @param viewer the viewer displaying a visible region of <code>selection</code>'s document. * @return <code>true</code>, if <code>selection</code> is contained, <code>false</code> otherwise. */ private boolean containedByVisibleRegion(ITextSelection selection, ISourceViewer viewer) { int min= selection.getOffset(); int max= min + selection.getLength(); IDocument document= viewer.getDocument(); IRegion visible; if (viewer instanceof ITextViewerExtension5) visible= ((ITextViewerExtension5) viewer).getModelCoverage(); else visible= viewer.getVisibleRegion(); int visOffset= visible.getOffset(); try { if (visOffset > min) { if (document.getLineOfOffset(visOffset) != selection.getStartLine()) return false; if (!isWhitespace(document.get(min, visOffset - min))) { showStatus(); return false; } } int visEnd= visOffset + visible.getLength(); if (visEnd < max) { if (document.getLineOfOffset(visEnd) != selection.getEndLine()) return false; if (!isWhitespace(document.get(visEnd, max - visEnd))) { showStatus(); return false; } } return true; } catch (BadLocationException e) { } return false; }
Example 10
Source File: XtextSourceViewerEx.java From statecharts with Eclipse Public License 1.0 | 5 votes |
/** * Overwritten to handle offset properly. */ @Override protected boolean updateSlaveDocument(IDocument slaveDocument, int modelRangeOffset, int modelRangeLength) throws BadLocationException { if (slaveDocument instanceof ProjectionDocument) { ProjectionDocument projection = (ProjectionDocument) slaveDocument; int offset = modelRangeOffset; int length = modelRangeLength; if (!isProjectionMode()) { // mimic original TextViewer behavior IDocument master = projection.getMasterDocument(); int line = master.getLineOfOffset(modelRangeOffset); offset += master.getLineOffset(line); length = (modelRangeOffset - offset) + modelRangeLength; } try { // fHandleProjectionChanges= false; setPrivateHandleProjectionChangesField(false); projection.replaceMasterDocumentRanges(offset, length); } finally { // fHandleProjectionChanges= true; setPrivateHandleProjectionChangesField(true); } return true; } return false; }
Example 11
Source File: ParagraphTransposeHandler.java From e4macs with Eclipse Public License 1.0 | 5 votes |
private int swapParagraphs(IDocument document, Paragraph para1, Paragraph para2) throws BadLocationException { int result = -1; if (para1.isOk() && para2.isOk()) { // we're cool, so swap // check that we're not at a non-blank line (top) before adjusting line int bline = document.getLineOfOffset(para1.getBegin()); if (isBlank(document,bline)) { ++bline; } // check that we're not at a non-blank line (bottom) before adjusting line int eline = document.getLineOfOffset(para2.getEnd()); if (isBlank(document,eline)) { --eline; } // get the text for paragraph 1 IRegion line1Begin = document.getLineInformation(bline); IRegion lineEnd = document.getLineInformation(document.getLineOfOffset(para1.getEnd()) -1); int para1len = lineEnd.getOffset() + lineEnd.getLength() - line1Begin.getOffset(); String para1text = document.get(line1Begin.getOffset(), para1len); // get the text for paragraph 2 IRegion line2Begin = document.getLineInformation(document.getLineOfOffset(para2.getBegin()) + 1); lineEnd = document.getLineInformation(eline); int para2len = lineEnd.getOffset() + lineEnd.getLength() - line2Begin.getOffset(); String para2text = document.get(line2Begin.getOffset(), para2len); // swap the text from bottom up updateText(document,line2Begin.getOffset(), para2len, para1text); updateText(document,line1Begin.getOffset(), para1len, para2text); // cursor goes below swapped paragraphs result = para2.getEnd(); } return result; }
Example 12
Source File: TexAnnotationHover.java From texlipse with Eclipse Public License 1.0 | 5 votes |
private boolean isRulerLine(Position position, IDocument document, int line) { if (position.getOffset() > -1 && position.getLength() > -1) { try { return line == document.getLineOfOffset(position.getOffset()); } catch (BadLocationException x) { } } return false; }
Example 13
Source File: CommentSupport.java From tm4e with Eclipse Public License 1.0 | 5 votes |
public boolean isInComment(IDocument document, int offset) { try { if (isInBlockComment(document.get(0, offset))) { return true; } int line = document.getLineOfOffset(offset); int lineOffset = document.getLineOffset(line); return isInLineComment(document.get(lineOffset, offset - lineOffset)); } catch (BadLocationException e) { return false; } }
Example 14
Source File: JSDocAutoIndentStrategy.java From typescript.java with MIT License | 5 votes |
/** * 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; } }
Example 15
Source File: Utils.java From jdt-codemining with Eclipse Public License 1.0 | 5 votes |
public static ILineRange getLineRange(IJavaElement element, IDocument document) throws JavaModelException, BadLocationException { ISourceRange r = ((ISourceReference) element).getSourceRange(); int offset = r.getOffset(); int startLine = document.getLineOfOffset(offset); int endLine = document.getLineOfOffset(offset + r.getLength()); return new LineRange(startLine, endLine - startLine); }
Example 16
Source File: UIHelper.java From tlaplus with MIT License | 4 votes |
/** * For all {@link TheoremNode} in the tree rooted at theoremNode, this * returns the {@link TheoremNode} that is first on the line containing the * caret, or null if none satisfy that criteria. * * @param theoremNode * @return */ public static TheoremNode getThmNodeStepWithCaret(TheoremNode theoremNode, int caretOffset, IDocument document) { try { /* * Get the location of the step. * * theoremNode.getTheorem() returns the node corresponding to the * statement of the step (or theorem). * * Return theoremNode if the caret is on any of the lines from the * first line of the theoremNode to the last line of the statement * of the node. * * If the caret is not on any of those lines, then recursively * search for a substep containing the caret. */ int nodeBeginLine = theoremNode.getLocation().beginLine(); int nodeEndLine = theoremNode.getTheorem().getLocation().endLine(); /* * IDocument lines are 0-based and SANY Location lines are 1-based. */ int caretLine = document.getLineOfOffset(caretOffset) + 1; // IRegion stepRegion = AdapterFactory.locationToRegion(document, // stepLoc); if (nodeBeginLine <= caretLine && nodeEndLine >= caretLine/* * stepRegion. * getOffset * () <= * caretOffset * && * stepRegion * . * getOffset * () + * stepRegion * . * getLength * () >= * caretOffset */) { return theoremNode; } /* * Theorem node does not contain the caret. Recursively try to find * a sub-step containing the caret if the proof contains the caret. */ ProofNode proof = theoremNode.getProof(); if (proof != null) { Location proofLoc = proof.getLocation(); if (caretLine >= proofLoc.beginLine() && caretLine <= proofLoc.endLine()) { if (proof instanceof NonLeafProofNode) { NonLeafProofNode nonLeafProof = (NonLeafProofNode) proof; LevelNode[] steps = nonLeafProof.getSteps(); /* * From the documentation of NonLeafProofNode, a step * can be one of four types: * * DefStepNode UseOrHideNode InstanceNode TheoremNode * * Only TheoremNode can have a proof. Recursively * compute the proof positions for those steps. */ for (int i = 0; i < steps.length; i++) { if (steps[i] instanceof TheoremNode) { TheoremNode node = getThmNodeStepWithCaret((TheoremNode) steps[i], caretOffset, document); if (node != null) { return node; } } } } } } } catch (BadLocationException e) { Activator.getDefault().logError("Error finding step containing caret.", e); } return null; }
Example 17
Source File: JavaAutoIndentStrategy.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) { if (c.offset < 1 || d.getLength() == 0) return; JavaHeuristicScanner scanner= new JavaHeuristicScanner(d); int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); try { // current line int line= d.getLineOfOffset(p); int lineOffset= d.getLineOffset(line); // make sure we don't have any leading comments etc. if (d.get(lineOffset, p - lineOffset).trim().length() != 0) return; // line of last Java code int pos= scanner.findNonWhitespaceBackward(p, JavaHeuristicScanner.UNBOUND); if (pos == -1) return; int lastLine= d.getLineOfOffset(pos); // only shift if the last java line is further up and is a braceless block candidate if (lastLine < line) { JavaIndenter indenter= new JavaIndenter(d, scanner, fProject); StringBuffer indent= indenter.computeIndentation(p, true); String toDelete= d.get(lineOffset, c.offset - lineOffset); if (indent != null && !indent.toString().equals(toDelete)) { c.text= indent.append(c.text).toString(); c.length += c.offset - lineOffset; c.offset= lineOffset; } } } catch (BadLocationException e) { JavaPlugin.log(e); } }
Example 18
Source File: PairedBracketsPainter.java From xds-ide with Eclipse Public License 1.0 | 4 votes |
/** * Handles a redraw request. * * @param gc the GC to draw into. */ private void handleDrawRequest(GC gc) { if (fPairPosition.isDeleted) return; int offset= fPairPosition.getOffset(); int length= fPairPosition.getLength(); if (length < 1) return; if (fSourceViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5) fSourceViewer; IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length)); if (widgetRange == null) return; try { // don't draw if the pair position is really hidden and widgetRange just // marks the coverage around it. IDocument doc= fSourceViewer.getDocument(); int startLine= doc.getLineOfOffset(offset); int endLine= doc.getLineOfOffset(offset + length); if (extension.modelLine2WidgetLine(startLine) == -1 || extension.modelLine2WidgetLine(endLine) == -1) return; } catch (BadLocationException e) { return; } offset= widgetRange.getOffset(); length= widgetRange.getLength(); } else { IRegion region= fSourceViewer.getVisibleRegion(); if (region.getOffset() > offset || region.getOffset() + region.getLength() < offset + length) return; offset -= region.getOffset(); } boolean digraph = ((fMatchFlags & PairedBracketsMatcher.MATCH_FLAG_DIGRAPH) != 0); int cx = digraph ? 1 : 0; if (ICharacterPairMatcher.RIGHT == fAnchor) draw(gc, offset + length -1 - cx, offset, cx); else draw(gc, offset, offset + length -1 - cx, cx); }
Example 19
Source File: Utils.java From jdt-codemining with Eclipse Public License 1.0 | 4 votes |
public static int getLineNumber(IJavaElement element, IDocument document) throws JavaModelException, BadLocationException { ISourceRange r = ((ISourceReference) element).getNameRange(); int offset = r.getOffset(); return document.getLineOfOffset(offset); }
Example 20
Source File: AdapterFactory.java From tlaplus with MIT License | 3 votes |
/** * If location = -1, then it returns -1. Else it returns the number of the line with * this location. * @param document * @param location * @return * @throws BadLocationException */ private static int LocationToLine(IDocument document, int location) throws BadLocationException { if (location == -1) { return -1; } else { return document.getLineOfOffset(location); } }