Java Code Examples for org.eclipse.jface.text.IDocument#getLineOffset()
The following examples show how to use
org.eclipse.jface.text.IDocument#getLineOffset() .
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: HoverHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Test public void testHoverThrowable() throws Exception { String uriString = ClassFileUtil.getURI(project, "java.lang.Exception"); IClassFile classFile = JDTUtils.resolveClassFile(uriString); String contents = JavaLanguageServerPlugin.getContentProviderManager().getSource(classFile, monitor); IDocument document = new Document(contents); IRegion region = new FindReplaceDocumentAdapter(document).find(0, "Throwable", true, false, false, false); int offset = region.getOffset(); int line = document.getLineOfOffset(offset); int character = offset - document.getLineOffset(line); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uriString); Position position = new Position(line, character); TextDocumentPositionParams params = new TextDocumentPositionParams(textDocument, position); Hover hover = handler.hover(params, monitor); assertNotNull(hover); assertTrue("Unexpected hover ", !hover.getContents().getLeft().isEmpty()); }
Example 2
Source File: GamlEditor.java From gama with GNU General Public License v3.0 | 6 votes |
/** * @see msi.gama.lang.gaml.ui.editor.IGamlEditor#applyTemplate(org.eclipse.jface.text.templates.Template) */ public void applyTemplateAtTheEnd(final Template t) { try { final IDocument doc = getDocument(); int offset = doc.getLineOffset(doc.getNumberOfLines() - 1); doc.replace(offset, 0, "\n\n"); offset += 2; final int length = 0; final Position pos = new Position(offset, length); final XtextTemplateContextType ct = new XtextTemplateContextType(); final DocumentTemplateContext dtc = new DocumentTemplateContext(ct, doc, pos); final IRegion r = new Region(offset, length); final TemplateProposal tp = new TemplateProposal(t, dtc, r, null); tp.apply(getInternalSourceViewer(), (char) 0, 0, offset); } catch (final BadLocationException e) { e.printStackTrace(); } }
Example 3
Source File: CodeFoldingSetter.java From Pydev with Eclipse Public License 1.0 | 6 votes |
/** * @return an annotation that should be added (or null if that entry already has an annotation * added for it). */ private Tuple<ProjectionAnnotation, Position> getAnnotationToAdd(FoldingEntry node, int start, int end, ProjectionAnnotationModel model, List<Annotation> existing) throws BadLocationException { try { IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); int offset = document.getLineOffset(start); int endOffset = offset; try { endOffset = document.getLineOffset(end); } catch (Exception e) { //sometimes when we are at the last line, the command above will not work very well IRegion lineInformation = document.getLineInformation(end); endOffset = lineInformation.getOffset() + lineInformation.getLength(); } Position position = new Position(offset, endOffset - offset); return getAnnotationToAdd(position, node, model, existing); } catch (BadLocationException x) { //this could happen } return null; }
Example 4
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 5
Source File: JsniAutoEditStrategy.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 6 votes |
/** * 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 6
Source File: DefaultJavaFoldingStructureProvider.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * 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 7
Source File: AbstractOpenElementOperation.java From goclipse with Eclipse Public License 1.0 | 5 votes |
protected static int getOffsetFrom(IDocument doc, int line_oneBased, int column_oneBased) throws CoreException { int lineOffset; try { lineOffset = doc.getLineOffset(line_oneBased-1); } catch (BadLocationException e) { throw EclipseCore.createCoreException("Invalid line number: " + line_oneBased, e); } return lineOffset + column_oneBased-1; }
Example 8
Source File: PyMarkerUIUtils.java From Pydev with Eclipse Public License 1.0 | 5 votes |
/** * @return the position for a marker. */ public static Position getMarkerPosition(IDocument document, IMarker marker, IAnnotationModel model) { if (model instanceof AbstractMarkerAnnotationModel) { Position ret = ((AbstractMarkerAnnotationModel) model).getMarkerPosition(marker); if (ret != null) { return ret; } } int start = MarkerUtilities.getCharStart(marker); int end = MarkerUtilities.getCharEnd(marker); if (start > end) { end = start + end; start = end - start; end = end - start; } if (start == -1 && end == -1) { // marker line number is 1-based int line = MarkerUtilities.getLineNumber(marker); if (line > 0 && document != null) { try { start = document.getLineOffset(line - 1); end = start; } catch (BadLocationException x) { } } } if (start > -1 && end > -1) { return new Position(start, end - start); } return null; }
Example 9
Source File: KillLineHandler.java From e4macs with Eclipse Public License 1.0 | 5 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 { 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 10
Source File: JsniAutoEditStrategy.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
/** * Set the indent of a new line based on the command provided in the supplied * document. * * @param document - the document being parsed * @param command - the command being performed */ protected void smartIndentAfterNewLine(IDocument document, DocumentCommand command) { int docLength = document.getLength(); if (command.offset == -1 || docLength == 0) { return; } try { int p = (command.offset == docLength ? command.offset - 1 : command.offset); int line = document.getLineOfOffset(p); StringBuffer buf = new StringBuffer(command.text); if (command.offset < docLength && document.getChar(command.offset) == '}') { int indLine = findMatchingOpenBracket(document, line, command.offset, 0); if (indLine == -1) { indLine = line; } buf.append(getIndentOfLine(document, indLine)); } else { int start = document.getLineOffset(line); int whiteend = findEndOfWhiteSpace(document, start, command.offset); buf.append(document.get(start, whiteend - start)); if (getBracketCount(document, start, command.offset, true) > 0) { buf.append(getIndentToken()); } } command.text = buf.toString(); } catch (BadLocationException e) { GWTPluginLog.logError(e); } }
Example 11
Source File: ErrorDescription.java From Pydev with Eclipse Public License 1.0 | 5 votes |
public int getEndLine(IDocument doc) { try { return doc.getLineOffset(errorEnd); } catch (BadLocationException e) { } return errorLine; }
Example 12
Source File: EditorUtil.java From tlaplus with MIT License | 5 votes |
/** * Like getLocationAt, except it adds x to the endCol. * * @param document * @param offset * @param length * @param x * @return */ public static Location getLocationAt(IDocument document, int offset, int length, int x) { // I don't think document or selection can be null, but... if (document == null) { return null; } Location loc = null; try { // Compute the lines in Java coordinates and the columns // in human coordinates. int startOffset = offset; int startLine = document.getLineOfOffset(startOffset); int startCol = startOffset - document.getLineOffset(startLine) + 1; int endOffset = startOffset + length; int endLine = document.getLineOfOffset(endOffset); int endCol = endOffset - document.getLineOffset(endLine); // Because endCol points to the character to the right of // the selection, it now is in human coordinates for the // last character of the selection--except if the selection // has length 0. if (length == 0) { endCol++; } loc = new Location(startLine + 1, startCol, endLine + 1, endCol + x); } catch (BadLocationException e) { return null; // e.printStackTrace(); } return loc; }
Example 13
Source File: TypeScriptAutoIndentStrategy.java From typescript.java with MIT License | 5 votes |
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$ } }
Example 14
Source File: ImplementationsHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private int getOffset(TextDocumentPositionParams param, ITypeRoot typeRoot) { int offset = 0; try { IDocument document = JsonRpcHelpers.toDocument(typeRoot.getBuffer()); offset = document.getLineOffset(param.getPosition().getLine()) + param.getPosition().getCharacter(); } catch (JavaModelException | BadLocationException e) { JavaLanguageServerPlugin.logException(e.getMessage(), e); } return offset; }
Example 15
Source File: JavaAutoIndentStrategy.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
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); } }
Example 16
Source File: DefineFoldingRegionAction.java From tlaplus with MIT License | 5 votes |
public void run() { ITextEditor editor = getTextEditor(); ISelection selection = editor.getSelectionProvider().getSelection(); if (selection instanceof ITextSelection) { ITextSelection textSelection = (ITextSelection) selection; if (textSelection.getLength() != 0) { IAnnotationModel model = getAnnotationModel(editor); if (model != null) { int start = textSelection.getStartLine(); int end = textSelection.getEndLine(); try { IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); int offset = document.getLineOffset(start); int endOffset = document.getLineOffset(end + 1); Position position = new Position(offset, endOffset - offset); model.addAnnotation(new ProjectionAnnotation(), position); } catch (BadLocationException x) { // ignore } } } } }
Example 17
Source File: RichStringAwareSourceViewer.java From xtext-xtend with Eclipse Public License 2.0 | 5 votes |
private IRegion copiedGetTextBlockFromSelection(ITextSelection selection) { try { IDocument document= getDocument(); int start= document.getLineOffset(selection.getStartLine()); int endLine= selection.getEndLine(); IRegion endLineInfo= document.getLineInformation(endLine); int end= endLineInfo.getOffset() + endLineInfo.getLength(); return new Region(start, end - start); } catch (BadLocationException x) { } return null; }
Example 18
Source File: ReportXMLSourceEditorFormPage.java From birt with Eclipse Public License 1.0 | 4 votes |
public boolean selectReveal( Object marker ) { int start = MarkerUtilities.getCharStart( (IMarker) marker ); int end = MarkerUtilities.getCharEnd( (IMarker) marker ); boolean selectLine = start < 0 || end < 0; // look up the current range of the marker when the document has been // edited IAnnotationModel model = reportXMLEditor.getDocumentProvider( ) .getAnnotationModel( reportXMLEditor.getEditorInput( ) ); if ( model instanceof AbstractMarkerAnnotationModel ) { AbstractMarkerAnnotationModel markerModel = (AbstractMarkerAnnotationModel) model; Position pos = markerModel.getMarkerPosition( (IMarker) marker ); if ( pos != null ) { if ( !pos.isDeleted( ) ) { // use position instead of marker values start = pos.getOffset( ); end = pos.getOffset( ) + pos.getLength( ); } else { return false; } } } IDocument document = reportXMLEditor.getDocumentProvider( ) .getDocument( reportXMLEditor.getEditorInput( ) ); if ( selectLine ) { int line; try { if ( start >= 0 ) line = document.getLineOfOffset( start ); else { line = MarkerUtilities.getLineNumber( (IMarker) marker ); // Marker line numbers are 1-based if ( line >= 1 ) { line--; } start = document.getLineOffset( line ); } end = start + document.getLineLength( line ) - 1; } catch ( BadLocationException e ) { return false; } } int length = document.getLength( ); if ( end - 1 < length && start < length ) reportXMLEditor.selectAndReveal( start, end - start ); return true; }
Example 19
Source File: TexAutoIndentStrategy.java From texlipse with Eclipse Public License 1.0 | 4 votes |
/** * 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 20
Source File: JDTUtils.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
public static IJavaElement[] findElementsAtSelection(ITypeRoot unit, int line, int column, PreferenceManager preferenceManager, IProgressMonitor monitor) throws JavaModelException { if (unit == null || monitor.isCanceled()) { return null; } int offset = JsonRpcHelpers.toOffset(unit.getBuffer(), line, column); if (offset > -1) { return unit.codeSelect(offset, 0); } if (unit instanceof IClassFile) { IClassFile classFile = (IClassFile) unit; ContentProviderManager contentProvider = JavaLanguageServerPlugin.getContentProviderManager(); String contents = contentProvider.getSource(classFile, monitor); if (contents != null) { IDocument document = new Document(contents); try { offset = document.getLineOffset(line) + column; if (offset > -1) { String name = parse(contents, offset); if (name == null) { return null; } SearchPattern pattern = SearchPattern.createPattern(name, IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_FULL_MATCH); IJavaSearchScope scope = createSearchScope(unit.getJavaProject(), preferenceManager); List<IJavaElement> elements = new ArrayList<>(); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) { if (match.getElement() instanceof IJavaElement) { elements.add((IJavaElement) match.getElement()); } } }; SearchEngine searchEngine = new SearchEngine(); searchEngine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope, requestor, null); return elements.toArray(new IJavaElement[0]); } } catch (BadLocationException | CoreException e) { JavaLanguageServerPlugin.logException(e.getMessage(), e); } } } return null; }