public void focusOnLines(ILocation range) { if (range instanceof ILineLocation) { ILineLocation lineLocation = (ILineLocation) range; // editors count lines from 0, Crucible counts from 1 final int startLine = lineLocation.getRangeMin() - 1; final int endLine = lineLocation.getRangeMax() - 1; if (sourceViewer != null) { IDocument document = sourceViewer.getDocument(); if (document != null) { try { int offset = document.getLineOffset(startLine); int length = document.getLineOffset(endLine) - offset; StyledText widget = sourceViewer.getTextWidget(); try { widget.setRedraw(false); // sourceViewer.revealRange(offset, length); // sourceViewer.setSelectedRange(offset, 0); sourceViewer.setSelection(new TextSelection(offset, length), true); } finally { widget.setRedraw(true); } } catch (BadLocationException e) { StatusHandler.log( new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, e.getMessage(), e)); } } } } }
/** * This is kinda hackish, because the last character in a block is not included in the AST, so we * do not really know where a multi-line statement ends */ private Position computePosition(AstNode node, IDocument doc) { try { int start = doc.getLineOffset(node.getLine() - 1) + node.getOffset(); int end; if (node.getLine() == node.getEndLine()) end = node.getText().length(); else end = doc.getLineOffset(node.getEndLine() + 1) - start; return new Position(start, end); } catch (BadLocationException e) { e.printStackTrace(); return null; } }
/** * Returns the index of the first line whose start offset is in the given text range. * * @param region the text range in characters where to find the line * @param document The document * @return the first line whose start index is in the given range, -1 if there is no such line */ private int getFirstCompleteLineOfRegion(IRegion region, IDocument document) { try { int startLine = document.getLineOfOffset(region.getOffset()); int offset = document.getLineOffset(startLine); if (offset >= region.getOffset()) return startLine; offset = document.getLineOffset(startLine + 1); return (offset > region.getOffset() + region.getLength() ? -1 : startLine + 1); } catch (BadLocationException x) { // should not happen } return -1; }
/** * Extend the selection that the action will work on. Default implementation, extend to whole * lines. Might be overridden. * * @param document text {@link IDocument} * @param selection original selection * @return new {@link ITextSelection} extended to the whole lines intersected by selection */ public static ITextSelection extendSelectionToWholeLines( final IDocument document, final ITextSelection selection) { final int startLine = selection.getStartLine(); final int endLine = selection.getEndLine(); int startLineOffset; try { startLineOffset = document.getLineOffset(startLine); final int endTextOffset = document.getLineOffset(endLine) + document.getLineLength(endLine); return new TextSelection(document, startLineOffset, endTextOffset - startLineOffset); } catch (final BadLocationException e) { e.printStackTrace(); } return selection; }
protected int getValidPosition(IDocument idoc, int lineNumber) { if (!(getSourceEditingTextTools() instanceof IDOMSourceEditingTextTools)) { return NO_VALID_CONTENT; } if (idoc == null) return NO_VALID_CONTENT; int startOffset, endOffset; try { startOffset = idoc.getLineOffset(lineNumber - 1); endOffset = idoc.getLineOffset(lineNumber) - 1; if (idoc == null) return NO_VALID_CONTENT; String lineText = idoc.get(startOffset, endOffset - startOffset).trim(); // blank lines or lines with only an open or close brace or // scriptlet tag cannot have a breakpoint if (lineText.equals("") || lineText.equals("{") || //$NON-NLS-2$//$NON-NLS-1$ lineText.equals("}") || lineText.equals("<%")) // $NON-NLS-2$//$NON-NLS-1$ return NO_VALID_CONTENT; } catch (BadLocationException e) { return NO_VALID_CONTENT; } IStructuredDocumentRegion flatNode = ((IStructuredDocument) idoc).getRegionAtCharacterOffset(startOffset); // go through the node's regions looking for JSP content // until reaching the end of the line while (flatNode != null) { int validPosition = getValidRegionPosition( ((IDOMDocument) ((IDOMSourceEditingTextTools) getSourceEditingTextTools()).getDOMDocument()) .getModel(), flatNode, startOffset, endOffset); if (validPosition == END_OF_LINE) return NO_VALID_CONTENT; if (validPosition >= 0) return validPosition; flatNode = flatNode.getNext(); } return NO_VALID_CONTENT; }
/** * Updates all the cached information about the lines to be painted and to be cleared. Returns * <code>true</code> if the line number of the cursor line has changed. * * @return <code>true</code> if cursor line changed */ private boolean updateHighlightLine() { try { IDocument document = fViewer.getDocument(); int modelCaret = getModelCaret(); int lineNumber = document.getLineOfOffset(modelCaret); Point selection = fViewer.getTextWidget().getSelectionRange(); // redraw if the current line number is different from the last line number we painted // initially fLastLineNumber is -1 if (lineNumber != fLastLineNumber || !overlaps(fCurrentLine, modelCaret) || (selection.y != 0)) { // Handle non-empty selections (turn off highlight line) if (selection.y != 0 && fLastLine.equals(fCurrentLine)) { if (fLastSelection.equals(selection)) // selection didn't change { return false; // don't redraw the highlight line } fLastSelection = selection; return true; // selection changed } fLastSelection = selection; // Update the current and last lines fLastLine.offset = fCurrentLine.offset; fLastLine.length = fCurrentLine.length; fLastLine.isDeleted = fCurrentLine.isDeleted; if (fCurrentLine.isDeleted) { fCurrentLine.isDeleted = false; fPositionManager.managePosition(fCurrentLine); } fCurrentLine.offset = document.getLineOffset(lineNumber); if (lineNumber == document.getNumberOfLines() - 1) { fCurrentLine.length = document.getLength() - fCurrentLine.offset; } else { fCurrentLine.length = document.getLineOffset(lineNumber + 1) - fCurrentLine.offset; } fLastLineNumber = lineNumber; return true; } } catch (BadLocationException e) { } return false; }
@Override public ICompletionProposal getCompletionProposal(final IMarker marker, final IDocument document) { String msg = marker.getAttribute(IMarker.MESSAGE, ""); // $NON-NLS-1$ String toSearch = GhcMessages.WARNING_INFERREDTYPE_START; int ix = msg.toLowerCase().indexOf(toSearch); String type = msg.substring(ix + toSearch.length()).trim(); int line = marker.getAttribute(IMarker.LINE_NUMBER, 0); try { int offset = document.getLineOffset(line - 1); String txt = type + PlatformUtil.NL; return new CompletionProposal( getLineStartAddition(txt, marker.getResource()), offset, 0, offset + txt.length(), HaskellUIImages.getImage(IImageNames.TYPE_SIGNATURE), getLabel(), null, null); // doc.replace( offset, 0, type+NL ); } catch (BadLocationException ex) { HaskellUIPlugin.log(ex); } return null; }
private boolean openFileImpl(IProject project, IPath sourceLoc, int lineNumber) { if (sourceLoc == null || "??".equals(sourceLoc.toString())) return false; try { IEditorInput editorInput = getEditorInput(sourceLoc, project); IWorkbenchPage p= CUIPlugin.getActivePage(); if (p != null) { if (editorInput == null) { p.openEditor( new STCSourceNotFoundEditorInput(project, sourceLoc, lineNumber), "org.eclipse.linuxtools.binutils.link2source.STCSourceNotFoundEditor", true); } else { IEditorPart editor = p.openEditor(editorInput, CUIPlugin.EDITOR_ID, true); if (lineNumber > 0 && editor instanceof ITextEditor){ IDocumentProvider provider= ((ITextEditor)editor).getDocumentProvider(); IDocument document= provider.getDocument(editor.getEditorInput()); try { int start = document.getLineOffset(lineNumber-1); ((ITextEditor)editor).selectAndReveal(start, 0); IWorkbenchPage page= editor.getSite().getPage(); page.activate(editor); return true; } catch (BadLocationException x) { // ignore } } } } } catch (Exception _) { } return false; }
private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) { if (c.offset == -1 || d.getLength() == 0) return; try { int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset); int line = d.getLineOfOffset(p); int start = d.getLineOffset(line); int whiteend = findEndOfWhiteSpace(d, start, c.offset); JavaHeuristicScanner scanner = new JavaHeuristicScanner(d); JavaIndenter indenter = new JavaIndenter(d, scanner, fProject); // shift only when line does not contain any text up to the closing bracket if (whiteend == c.offset) { // evaluate the line with the opening bracket that matches out closing bracket int reference = indenter.findReferencePosition(c.offset, false, true, false, false); int indLine = d.getLineOfOffset(reference); if (indLine != -1 && indLine != line) { // take the indent of the found line StringBuffer replaceText = new StringBuffer(getIndentOfLine(d, indLine)); // add the rest of the current line including the just added close bracket replaceText.append(d.get(whiteend, c.offset - whiteend)); replaceText.append(c.text); // modify document command c.length += c.offset - start; c.offset = start; c.text = replaceText.toString(); } } } catch (BadLocationException e) { JavaPlugin.log(e); } }
@Override public IFigure getTooltip(Object element) { if (element instanceof BasicBlock) { BasicBlock bb = (BasicBlock) element; IR ir = irView.getIR(); IDocument doc = irView.getDocument(); IMethod method = ir.getMethod(); StringBuffer result = new StringBuffer(); int start = bb.getFirstInstructionIndex(); int end = bb.getLastInstructionIndex(); SSAInstruction[] instructions = ir.getInstructions(); for (int j = start; j <= end; j++) { if (instructions[j] != null) { int sourceLineNum = method.getLineNumber(j); int lineNumber = sourceLineNum - 1; // IDocument indexing is 0-based try { int lineOffset = doc.getLineOffset(lineNumber); int lineLength = doc.getLineLength(lineNumber); String sourceCode = doc.get(lineOffset, lineLength).trim(); result.append(sourceCode); } catch (BadLocationException e) { } result.append("\n"); } } return new Label(result.toString()); } return null; }
private String normalizeBlockIndentation(ITextSelection selection, String selectedText) throws Throwable { String[] lines = selectedText.split("\\n"); if (lines.length < 2) { return selectedText; } String firstLine = doc.get( doc.getLineOffset(selection.getStartLine()), doc.getLineLength(selection.getStartLine())); String lineDelimiter = TextUtilities.getDefaultLineDelimiter(doc); String indentation = ""; int bodyIndent = 0; while (firstLine.startsWith(" ")) { indentation += " "; firstLine = firstLine.substring(1); bodyIndent += 1; } if (bodyIndent > 0) { StringBuffer selectedCode = new StringBuffer(); for (String line : lines) { if (line.startsWith(indentation)) { selectedCode.append(line.substring(bodyIndent) + lineDelimiter); } else { selectedCode.append(line + lineDelimiter); } } selectedText = selectedCode.toString(); } return selectedText; }
// XXX Lambda4jdt helper method private boolean includes(int line, IDocument document, Position p) { try { return p.includes(document.getLineOffset(line)); } catch (BadLocationException e) { return false; } }
/** Creates Annotations for FOP */ private void createFOPAnnotations() throws BadLocationException { AnnotationModelEvent event = new AnnotationModelEvent(this); FSTModel model = project.getFSTModel(); if (model == null) { composer.buildFSTModel(); model = project.getFSTModel(); } if (model == null) { return; } clear(); if (file.getParent() instanceof IFolder) { if (isInBuildFolder((IFolder) file.getParent())) { /* annotations for generated files */ FSTClass clazz = model.getClass(model.getAbsoluteClassName(file)); if (clazz == null) { return; } if (!clazz.hasComposedLines) { clazz.hasComposedLines = true; composer.postCompile(null, file); } for (FSTFeature fstFeature : model.getFeatures()) { FSTRole role = clazz.getRole(fstFeature.getName()); if (role == null) { continue; } for (FSTMethod m : role.getAllMethods()) { createFOPComposedAnnotations(event, fstFeature, m); } for (FSTField f : role.getAllFields()) { createFOPComposedAnnotations(event, fstFeature, f); } } } else { /* annotations for source files */ String featureName = getFeature((IFolder) file.getParent()); if (featureName != null) { FSTFeature fstFeature = model.getFeature(featureName); if (fstFeature != null) { // bar at the left of the editor final int color = fstFeature.getColor(); for (int line = 0; line < document.getNumberOfLines(); line++) { Position position = new Position(document.getLineOffset(line), 1); ColorAnnotation cafh = new ColorAnnotation(color, position, ColorAnnotation.TYPE_IMAGE); cafh.setText(fstFeature.getName()); annotations.add(cafh); event.annotationAdded(cafh); } } } } } }
private void gotoLineEnd() throws BadLocationException { int line = fDocument.getLineOfOffset(fOffset); int lines = fDocument.getNumberOfLines(); if (line + 1 == lines) { fOffset = fDocument.getLength() - 1; } else { fOffset = fDocument.getLineOffset(line + 1); } }
/** * Create a highlighted range on the previewers document with the given line, column, length and * key. * * @param line the line * @param column the column * @param length the length * @param key the key * @return the highlighted range */ private HighlightedRange createHighlightedRange(int line, int column, int length, String key) { try { IDocument document = fPreviewViewer.getDocument(); int offset = document.getLineOffset(line) + column; return new HighlightedRange(offset, length, key); } catch (BadLocationException x) { CUIPlugin.log(x); } return null; }
private String getIndentOfLine(IDocument d, int line) throws BadLocationException { if (line > -1) { int start = d.getLineOffset(line); int end = start + d.getLineLength(line) - 1; int whiteEnd = findEndOfWhiteSpace(d, start, end); return d.get(start, whiteEnd - start); } else { return ""; //$NON-NLS-1$ } }
public static int getLineOffset(IFile file, int line) { int offset = 0; IDocument doc = getDocument(file); if (doc == null) return offset; try { offset = doc.getLineOffset(line - 1); } catch (BadLocationException e) { e.printStackTrace(); } return offset; }
private void addFoldingRegions( Set<Position> regions, IDocumentElementNode[] nodes, IDocument document) throws BadLocationException { for (int i = 0; i < nodes.length; i++) { IDocumentElementNode element = nodes[i]; int startLine = document.getLineOfOffset(element.getOffset()); int endLine = document.getLineOfOffset(element.getOffset() + element.getLength()); if (startLine < endLine) { int start = document.getLineOffset(startLine); int end = document.getLineOffset(endLine) + document.getLineLength(endLine); Position position = new Position(start, end - start); regions.add(position); fPositionToElement.put(position, element); } IDocumentElementNode[] children = element.getChildNodes(); if (children != null) { addFoldingRegions(regions, children, document); } } }
protected void selectInEditor(Token token) { int line = token.getLine(); line--; // -1 because SableCC lines are 1-based WorkingCopy workingCopy = editor.getWorkingCopy(); IDocument document = workingCopy.getDocument(); try { int start = document.getLineOffset(line); editor.selectAndReveal(start, 0); } catch (BadLocationException e) { UIUtils.log(e); } }
public String getContents() { IDocument document = getSpecfile().getDocument(); int beginning = getLineStartPosition(); try { int end = document.getLineOffset(getSectionEndLine()); return document.get(beginning, end - beginning); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; //$NON-NLS-1$ }
/** * Creates Annotations for FOP Composed File * * @param event * @param fstFeature * @param m * @throws BadLocationException */ private void createFOPComposedAnnotations( AnnotationModelEvent event, FSTFeature fstFeature, RoleElement<?> m) throws BadLocationException { if (m.getComposedLine() <= 0) { return; } int startline = m.getComposedLine() - 1; int endline = m.getComposedLine() + m.getMethodLength() - 1; int lineOffset = document.getLineOffset(startline); int length = 0; for (int line = startline; line <= endline; line++) { length += document.getLineLength(line); // bar at the left of the editor Position methodposition = new Position(document.getLineOffset(line), document.getLineLength(line)); ColorAnnotation cafh = new ColorAnnotation( m.getRole().getFeature().getColor(), methodposition, ColorAnnotation.TYPE_IMAGE); cafh.setText(m.getRole().getFeature().getName()); annotations.add(cafh); event.annotationAdded(cafh); } Position methodposition = new Position(lineOffset, length); // bar at the right of the editor ColorAnnotation cafho = new ColorAnnotation( m.getRole().getFeature().getColor(), methodposition, ColorAnnotation.TYPE_OVERVIEW); cafho.setText(m.getRole().getFeature().getName()); annotations.add(cafho); event.annotationAdded(cafho); if (highlighting) { // background colors ColorAnnotation cafhh = new ColorAnnotation( m.getRole().getFeature().getColor(), methodposition, ColorAnnotation.TYPE_HIGHLIGHT); cafhh.setText(fstFeature.getName()); annotations.add(cafhh); event.annotationAdded(cafhh); } }
protected void setEditorTextPreservingCarret(String newContents) throws CommonException { if (areEqual(newContents, doc.get())) { return; } LangSourceViewer sourceViewer = getEditorSourceViewer(); ISelection sel = sourceViewer.getSelectionProvider().getSelection(); int line = -1; int col = -1; if (sel instanceof ITextSelection) { ITextSelection textSelection = (ITextSelection) sel; try { line = doc.getLineOfOffset(textSelection.getOffset()); col = textSelection.getOffset() - doc.getLineOffset(line); } catch (BadLocationException e) { // Ignore } } IDocument document = sourceViewer.getDocument(); if (document instanceof IDocumentExtension4) { IDocumentExtension4 doc_4 = (IDocumentExtension4) document; // We use the DocumentRewriteSession to prevent the caret from jumping around DocumentRewriteSession rewriteSession = doc_4.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL); document.set(newContents); doc_4.stopRewriteSession(rewriteSession); } else { int topIndex = sourceViewer.getTopIndex(); document.set(newContents); sourceViewer.setTopIndex(topIndex); } int newOffset = -1; if (line != -1 && col != -1) { try { newOffset = getOffsetFor(line, col); } catch (BadLocationException e) { // ignore } } if (newOffset != -1) { sourceViewer.getSelectionProvider().setSelection(new TextSelection(newOffset, 0)); } else { sourceViewer.getSelectionProvider().setSelection(sel); } }
/** * Edits the file given by the fileName. The number of characters indicated by length are replaced * by the given text beginning at the character located at the given line number and the line * character offset. * * @param fileName * @param lineNum * @param lineRelativeCharOffset * @param length * @param text * @throws Exception */ public void editFile( String fileName, int lineNum, int lineRelativeCharOffset, int length, String text) throws Exception { IFile file = this.getFile(fileName); AbstractTextEditor editor = this.getEditor(file); IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput()); int offset = doc.getLineOffset(lineNum) + lineRelativeCharOffset; doc.replace(offset, length, text); waitForIndexManager(); }
/** Retrieves the FSTDirectives from the changed document. */ private LinkedList<FSTDirective> getNewDirectives() { Vector<String> lines = new Vector<String>(); for (int i = 0; i < document.getNumberOfLines(); i++) { try { lines.add(document.get(document.getLineOffset(i), document.getLineLength(i))); } catch (BadLocationException e) { LogService.getInstance().log(LogLevel.DEBUG, e.getMessage()); } } return composer.buildModelDirectivesForFile(lines); }
private int getNextLineOffset(final IDocument doc, final int endLine) { try { if (endLine >= 0 && endLine + 1 < doc.getNumberOfLines()) { return doc.getLineOffset(endLine + 1); } else { return -1; } } catch (final BadLocationException e) { // don't show an error RUIPlugin.logError(RUIPlugin.INTERNAL_ERROR, "Error while find next line.", e); // $NON-NLS-1$ return -1; } }
/** Retrieves the FSTDirectives from the changed document. */ private LinkedList<FSTDirective> getNewDirectives() { Vector<String> lines = new Vector<String>(); for (int i = 0; i < document.getNumberOfLines(); i++) { try { lines.add(document.get(document.getLineOffset(i), document.getLineLength(i))); } catch (BadLocationException e) { UIPlugin.getDefault().logError(e); } } return composer.buildModelDirectivesForFile(lines); }
/** * Handles a single node when traversing the outline tree. Used recursively. * * @param node * @param document * @param parentDepth * @param newOutlineInput * @return */ private int addNodePosition( OutlineNode node, IDocument document, int parentDepth, TexOutlineInput newOutlineInput) { // add the Document position int beginOffset = 0; int length = 0; Position position = null; try { beginOffset = document.getLineOffset(node.getBeginLine() - 1); if (node.getEndLine() - 1 == document.getNumberOfLines()) length = document.getLength() - beginOffset; else length = document.getLineOffset(node.getEndLine() - 1) - beginOffset; position = new Position(beginOffset, length); document.addPosition("__outline", position); } catch (BadLocationException bpe) { throw new OperationCanceledException(); } catch (BadPositionCategoryException bpce) { throw new OperationCanceledException(); } node.setPosition(position); // add node to outline input newOutlineInput.addNode(node); // iterate through the children List<OutlineNode> children = node.getChildren(); int maxDepth = parentDepth + 1; if (children != null) { for (Iterator<OutlineNode> iter = children.iterator(); iter.hasNext(); ) { int localDepth = addNodePosition(iter.next(), document, parentDepth + 1, newOutlineInput); if (localDepth > maxDepth) { maxDepth = localDepth; } } } return maxDepth; }
public void run(IIntroSite site, Properties params) { String path = (String) params.get("path"); if (path.startsWith("<A href")) { // screwed up link! return; } String rawLine = (String) params.get("line"); int line = -1; try { line = Integer.parseInt(rawLine); } catch (NumberFormatException e1) { line = -1; } try { IFile file = getFile(path); IEditorPart part; if (file == null) { IEditorInput input = new ExternalRubyFileEditorInput(new File(path)); part = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getActivePage() .openEditor(input, RubyUI.ID_EXTERNAL_EDITOR); } else { part = IDE.openEditor( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file); } if (part == null) { RailsUILog.logError("Error creating editor input for stack trace from browser", null); // wrongly detected stack trace return; } if (line == -1) return; if (part instanceof ITextEditor) { ITextEditor editor = (ITextEditor) part; IDocument doc = editor.getDocumentProvider().getDocument(part.getEditorInput()); try { int offset = doc.getLineOffset(line - 1); EditorUtility.revealInEditor(part, offset, 0); } catch (NumberFormatException e) { // ignore } catch (BadLocationException e) { // ignore } } } catch (CoreException e) { RailsUILog.logError("Could not open editor or set line in editor", e); } }
private void handleSingleLineComment() throws BadLocationException { int line = fDocument.getLineOfOffset(fOffset); if (line < fCachedLineNumber) { fCachedLineNumber = line; fCachedLineOffset = fDocument.getLineOffset(line); int offset = fOffset; while (fCachedLineOffset < offset) { char current = fDocument.getChar(offset--); if (current == '/' && fCachedLineOffset <= offset && fDocument.getChar(offset) == '/') { fOffset = offset; return; } } } }
/** * Searches for the name of a method at the line number specified in the given reference. * * @param name method name * @param document document to search in * @param reference provides line number * @return method name range * @throws CoreException */ protected Position getMethodNameRange( boolean isContructor, String name, IDocument document, IReference reference) throws CoreException, BadLocationException { int linenumber = reference.getLineNumber(); if (linenumber > 0) { linenumber--; } String methodname = name; int idx = methodname.indexOf('$'); if (idx > -1) { methodname = methodname.substring(0, idx); } idx = methodname.indexOf(Signatures.getLT()); if (idx > -1) { methodname = methodname.substring(0, idx); } int offset = document.getLineOffset(linenumber); String line = document.get(offset, document.getLineLength(linenumber)); int start = line.indexOf('='); if (start < 0) { if (isContructor) { // new keyword should only be checked if the method is a constructor start = line.indexOf("new"); // $NON-NLS-1$ if (start < 0) { start = 0; } } else { start = 0; } } else { char charat = line.charAt(start - 1); // make sure its not '==' | '!=' | '<=' | '>=' if (line.charAt(start + 1) == '=' || charat == '!' || charat == '<' || charat == '>') { start = 0; } } int first = findMethodNameStart(methodname, line, start); if (first < 0) { methodname = "super"; // $NON-NLS-1$ first = findMethodNameStart(methodname, line, start); } if (first > -1) { return new Position(offset + first, methodname.length()); } return null; }