Java Code Examples for org.openide.text.NbDocument#findLineNumber()

The following examples show how to use org.openide.text.NbDocument#findLineNumber() . 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: SpringXMLConfigEditorUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean openFileAtOffset(DataObject dataObject, int offset) throws IOException {
    EditorCookie ec = dataObject.getCookie(EditorCookie.class);
    LineCookie lc = dataObject.getCookie(LineCookie.class);
    if (ec != null && lc != null) {
        StyledDocument doc = ec.openDocument();
        if (doc != null) {
            int lineNumber = NbDocument.findLineNumber(doc, offset);
            if (lineNumber != -1) {
                Line line = lc.getLineSet().getCurrent(lineNumber);
                if (line != null) {
                    int lineOffset = NbDocument.findLineOffset(doc, lineNumber);
                    int column = offset - lineOffset;
                    line.show(ShowOpenType.OPEN, ShowVisibilityType.FOCUS, column);
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 2
Source File: EditorContextDispatcher.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Get the line of the caret in the most recent editor.
 * This returns the current line in the current editor if there's one,
 * or a line of the caret in the editor, that was most recently active.
 * @return the line or <code>null</code> when there was no recent active editor.
 */
public Line getMostRecentLine() {
    EditorCookie e = getMostRecentEditorCookie ();
    if (e == null) return null;
    JEditorPane ep = getMostRecentEditor ();
    if (ep == null) return null;
    StyledDocument d = e.getDocument ();
    if (d == null) return null;
    Caret caret = ep.getCaret ();
    if (caret == null) return null;
    int lineNumber = NbDocument.findLineNumber(d, caret.getDot());
    Line.Set lineSet = e.getLineSet();
    try {
        return lineSet.getCurrent(lineNumber);
    } catch (IndexOutOfBoundsException ex) {
        return null;
    }
}
 
Example 3
Source File: EditorContextDispatcher.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Get the line number of the caret in the most recent editor.
 * This returns the current line number in the current editor if there's one,
 * or a line number of the caret in the editor, that was most recently active.
 * @return the line number or <code>-1</code> when there was no recent active editor.
 */
public int getMostRecentLineNumber() {
    EditorCookie e = getMostRecentEditorCookie ();
    if (e == null) return -1;
    JEditorPane ep = getMostRecentEditor ();
    if (ep == null) return -1;
    StyledDocument d = e.getDocument ();
    if (d == null) return -1;
    Caret caret = ep.getCaret ();
    if (caret == null) return -1;
    int ln = NbDocument.findLineNumber (
        d,
        caret.getDot ()
    );
    return ln + 1;
}
 
Example 4
Source File: EditorContextDispatcher.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Get the line number of the caret in the current editor.
 * @return the line number or <code>-1</code> when there is no current editor.
 */
public int getCurrentLineNumber() {
    EditorCookie e = getCurrentEditorCookie ();
    if (e == null) return -1;
    JEditorPane ep = getCurrentEditor ();
    if (ep == null) return -1;
    StyledDocument d = e.getDocument ();
    if (d == null) return -1;
    Caret caret = ep.getCaret ();
    if (caret == null) return -1;
    int ln = NbDocument.findLineNumber (
        d,
        caret.getDot ()
    );
    return ln + 1;
}
 
Example 5
Source File: HighlightImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public String getHighlightTestData() {
    int lineStart = NbDocument.findLineNumber((StyledDocument) doc, start);
    int columnStart = NbDocument.findLineColumn((StyledDocument) doc, start);
    int lineEnd = NbDocument.findLineNumber((StyledDocument) doc, end);
    int columnEnd = NbDocument.findLineColumn((StyledDocument) doc, end);
    
    return coloringsToString() + ", " + lineStart + ":" + columnStart + "-" + lineEnd + ":" + columnEnd;
}
 
Example 6
Source File: ToolTipAnnotation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String getIdentifier(final StyledDocument doc, final JEditorPane ep, final int offset) {
    String t = null;
    if (ep.getCaret() != null) { // #255228
        if ((ep.getSelectionStart() <= offset) && (offset <= ep.getSelectionEnd())) {
            t = ep.getSelectedText();
        }
        if (t != null) {
            return t;
        }
    }
    int line = NbDocument.findLineNumber(doc, offset);
    int col = NbDocument.findLineColumn(doc, offset);
    Element lineElem = NbDocument.findLineRootElement(doc).getElement(line);
    try {
        if (lineElem == null) {
            return null;
        }
        int lineStartOffset = lineElem.getStartOffset();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        if (col + 1 >= lineLen) {
            // do not evaluate when mouse hover behind the end of line (112662)
            return null;
        }
        t = doc.getText(lineStartOffset, lineLen);
        return getExpressionToEvaluate(t, col);
    } catch (BadLocationException e) {
        return null;
    }
}
 
Example 7
Source File: EditorOperator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Returns current line number.
 * @return number of line where the caret stays (first line == 1)
 */
public int getLineNumber() {
    StyledDocument doc = (StyledDocument) txtEditorPane().getDocument();
    int offset = txtEditorPane().getCaretPosition();
    return NbDocument.findLineNumber(doc, offset) + 1;
}
 
Example 8
Source File: EditList.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public int firstLine(BaseDocument doc) {
    OffsetRange range = getRange();
    
    return NbDocument.findLineNumber((StyledDocument)doc, range.getStart());
}
 
Example 9
Source File: GsfHintsProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Position[] getLine0(Error d, final Document doc, int startOffset, int endOffset) {
    StyledDocument sdoc = (StyledDocument) doc;
    int lineNumber = NbDocument.findLineNumber(sdoc, startOffset);
    int lineOffset = NbDocument.findLineOffset(sdoc, lineNumber);
    String text = DataLoadersBridge.getDefault().getLine(doc, lineNumber);
    if (text == null) {
        return new Position[2];
    }
    
    if (d.isLineError()) {
        int column = 0;
        int length = text.length();
        
        while (column < text.length() && Character.isWhitespace(text.charAt(column))) {
            column++;
        }
        
        while (length > 0 && Character.isWhitespace(text.charAt(length - 1))) {
            length--;
        }
        
        startOffset = lineOffset + column;
        endOffset = lineOffset + length;
        if (startOffset > endOffset) {
            // Space only on the line
            startOffset = lineOffset;
        }
    }
    
    if (LOG.isLoggable(Level.FINE)) {
        LOG.log(Level.FINE, "startOffset = " + startOffset );
        LOG.log(Level.FINE, "endOffset = " + endOffset );
    }
    
    final int startOffsetFinal = startOffset;
    final int endOffsetFinal = endOffset;
    final Position[] result = new Position[2];
    
    int len = doc.getLength();

    if (startOffsetFinal > len || endOffsetFinal > len) {
        if (!cancel.isCancelled() && LOG.isLoggable(Level.WARNING)) {
            LOG.log(Level.WARNING, "document changed, but not canceled?" );
            LOG.log(Level.WARNING, "len = " + len );
            LOG.log(Level.WARNING, "startOffset = " + startOffsetFinal );
            LOG.log(Level.WARNING, "endOffset = " + endOffsetFinal );
        }
        cancel();

        return result;
    }

    try {
        result[0] = NbDocument.createPosition(doc, startOffsetFinal, Bias.Forward);
        result[1] = NbDocument.createPosition(doc, endOffsetFinal, Bias.Backward);
    } catch (BadLocationException e) {
        LOG.log(Level.WARNING, null, e);
    }
    
    return result;
}
 
Example 10
Source File: PreviewHintFix.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public ChangeInfo implement() throws Exception {
    EditList edits = fix.getEditList();

    Document oldDoc = info.getSnapshot().getSource().getDocument(true);
    //OffsetRange range = edits.getRange();
    OffsetRange range = new OffsetRange(0, oldDoc.getLength());
    String oldSource = oldDoc.getText(range.getStart(), range.getEnd());

    String mimeType = (String) oldDoc.getProperty("mimeType"); //NOI18N
    BaseDocument newDoc = new BaseDocument(false, mimeType);

    Language language = (Language) oldDoc.getProperty(Language.class);
    newDoc.putProperty(Language.class, language);
    newDoc.insertString(0, oldSource, null);
    edits.applyToDocument(newDoc);
    String newSource = newDoc.getText(0, newDoc.getLength());

    String oldTitle = NbBundle.getMessage(PreviewHintFix.class, "CurrentSource");
    String newTitle = NbBundle.getMessage(PreviewHintFix.class, "FixedSource");

    final DiffController diffView = DiffController.create(
            new DiffSource(oldSource, oldTitle),
            new DiffSource(newSource, newTitle));


    JComponent jc = diffView.getJComponent();

    jc.setPreferredSize(new Dimension(800, 600));

    // Warp view to a particular diff?
    // I can't just always jump to difference number 0, because when a hint
    // has changed only the whitespace (such as the fix which moves =begin entries to column 0)
    // there are no diffs, even though I want to jump to the relevant line.
    final int index = 0;
    final int firstLine = diffView.getDifferenceCount() == 0 ? NbDocument.findLineNumber((StyledDocument) oldDoc, edits.getRange().
            getStart()) : -1;
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            if (firstLine != -1) {
                diffView.setLocation(DiffController.DiffPane.Base,
                        DiffController.LocationType.LineNumber, firstLine);
            } else if (diffView.getDifferenceCount() > 0) {
                diffView.setLocation(DiffController.DiffPane.Base,
                        DiffController.LocationType.DifferenceIndex, index);
            }
        }
    });

    JButton apply = new JButton(NbBundle.getMessage(PreviewHintFix.class, "Apply"));
    JButton ok = new JButton(NbBundle.getMessage(PreviewHintFix.class, "Ok"));
    JButton cancel = new JButton(NbBundle.getMessage(PreviewHintFix.class, "Cancel"));
    String dialogTitle = NbBundle.getMessage(PreviewHintFix.class, "PreviewTitle",
            fix.getDescription());

    DialogDescriptor descriptor =
            new DialogDescriptor(jc, dialogTitle, true,
            new Object[]{apply, ok, cancel}, ok, DialogDescriptor.DEFAULT_ALIGN, null, null,
            true);
    Dialog dlg = null;

    try {
        dlg = DialogDisplayer.getDefault().createDialog(descriptor);
        dlg.setVisible(true);
        if (descriptor.getValue() == apply) {
            fix.implement();
        }
    } finally {
        if (dlg != null) {
            dlg.dispose();
        }
    }

    return null;
}
 
Example 11
Source File: IndentFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void reindent () throws BadLocationException {
    //S ystem.out.println("SCHLIEMAN reformat !\n  " + context.document() + "\n  " + context.isIndent() + "\n  " + context.startOffset () + "\n  " + context.endOffset());
    StyledDocument document = (StyledDocument) context.document ();
    try {
        MimePath mimePath = MimePath.parse (context.mimePath ());
        String mimeType = mimePath.getMimeType (mimePath.size () - 1);
        Language l = LanguagesManager.getDefault ().getLanguage (mimeType);
        Object indentValue = getIndentProperties (l);
        if (indentValue == null) return;
        
        if (indentValue instanceof Feature) {
            Feature m = (Feature) indentValue;
            m.getValue (Context.create (document, context.startOffset ()));
            return;
        }
        Object[] params = (Object[]) indentValue;
        
        TokenHierarchy tokenHierarchy = TokenHierarchy.get (document);
        LanguagePath languagePath = LanguagePath.get (org.netbeans.api.lexer.Language.find (mimePath.getMimeType (0)));
        for (int i = 1; i < mimePath.size(); i++)
            languagePath = languagePath.embedded (org.netbeans.api.lexer.Language.find (mimePath.getMimeType (i)));
        List<TokenSequence> tokenSequences = tokenHierarchy.tokenSequenceList (languagePath, context.startOffset (), context.endOffset ());
        
        Set<Integer> whitespaces = l.getAnalyser().getSkipTokenTypes ();
        
        Iterator<Region> it = context.indentRegions ().iterator ();
        while (it.hasNext ()) {
            Region region = it.next ();
            Map<Position,Integer> indentMap = new HashMap<Position,Integer> ();
            int ln = NbDocument.findLineNumber (document, region.getStartOffset ());
            int endLineNumber = NbDocument.findLineNumber (document, region.getEndOffset ());
            if (!Utils.getTokenSequence (document, context.lineStartOffset (region.getStartOffset ())).language ().mimeType ().equals (mimeType)) 
                ln++;
            int indent = 0;
            if (ln > 0) {
                int offset = NbDocument.findLineOffset (document, ln - 1);
                indent = context.lineIndent (offset);
                if (!Utils.getTokenSequence (document, offset).language ().mimeType ().equals (mimeType))
                    indent += IndentUtils.indentLevelSize (document); 
            }
            while (ln <= endLineNumber) {
                if (ln == endLineNumber && 
                    isEmpty (ln, document, whitespaces) &&
                    !Utils.getTokenSequence (document, region.getEndOffset ()).language ().mimeType ().equals (mimeType)
                ) break;
                indent = indent (context, document, params, ln++, indent, indentMap, whitespaces);
            }

            Iterator<Position> it2 = indentMap.keySet ().iterator ();
            while (it2.hasNext ()) {
                Position position = it2.next ();
                context.modifyIndent (position.getOffset (), indentMap.get (position));
            }
        }
    } catch (LanguageDefinitionNotFoundException ldnfe) {
        //no language found - this might happen when some of the embedded languages are not schliemann based,
        //so just ignore and do nothing - no indent
    } catch (Exception ex) {
        ErrorManager.getDefault ().notify (ex);
    }
}
 
Example 12
Source File: OccurrencesMarkProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public int[] getAssignedLines() {
    int line = NbDocument.findLineNumber((StyledDocument) doc, startOffset.getOffset());
    
    return new int[] {line, line};
}
 
Example 13
Source File: MiscEditorUtil.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Test whether the line is in JavaScript source.
 * @param line The line to test
 * @return <code>true</code> when the line is in JavaScript source, <code>false</code> otherwise.
 */
public static boolean isInJavaScript(Line line) {
    LOG.log(Level.FINER, "\nisInJavaScript({0}):", line);
    FileObject fo = line.getLookup().lookup(FileObject.class);
    if (isJavascriptSource(fo)) {
        LOG.fine("is JavaScript source file => true");
        return true;
    }
    EditorCookie editorCookie = line.getLookup().lookup(EditorCookie.class);
    StyledDocument document = editorCookie.getDocument();
    Boolean isJS = null;
    ((AbstractDocument) document).readLock();
    try {
        TokenHierarchy<Document> th = TokenHierarchy.get((Document) document);
        int ln = line.getLineNumber();
        int offset = NbDocument.findLineOffset(document, ln);
        int maxOffset = document.getLength() - 1;
        int maxLine = NbDocument.findLineNumber(document, maxOffset);
        int offset2;
        if (ln + 1 > maxLine) {
            offset2 = maxOffset;
        } else {
            offset2 = NbDocument.findLineOffset(document, ln+1) - 1;
        }
        // The line has offsets <offset, offset2>
        Set<LanguagePath> languagePaths = th.languagePaths();
        for (LanguagePath lp : languagePaths) {
            List<TokenSequence<?>> tsl = th.tokenSequenceList(lp, offset, offset2);
            for (TokenSequence ts : tsl) {
                if (ts.moveNext()) {
                    /*int to = ts.offset();
                    if (LOG.isLoggable(Level.FINER)) {
                        LOG.finer("Token offset = "+to+", offsets = <"+offset+", "+offset2+">, mimeType = "+ts.language().mimeType());
                    }
                    if (!(offset <= to && to < offset2)) {
                        continue;
                    }*/
                    TokenSequence ets;
                    ets = ts.embedded();
                    if (ets != null) {
                        ts = ets;
                    }
                    String mimeType = ts.language().mimeType();
                    LOG.log(Level.FINER, "Have language {0}", mimeType);
                    if (isJS == null && JAVASCRIPT_MIME_TYPE.equals(mimeType)) {
                        isJS = true;
                        if (!LOG.isLoggable(Level.FINER)) {
                            break;
                        }
                    }
                }
            }
        }
    } finally {
        ((AbstractDocument) document).readUnlock();
    }
    LOG.log(Level.FINER, "isJS = {0}", isJS);
    return isJS != null && isJS;
}
 
Example 14
Source File: WatchPanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static String getSelectedIdentifier (
    StyledDocument doc,
    JEditorPane ep,
    int offset
) {
    String t = null;
    if (ep.getSelectionStart () <= offset && offset <= ep.getSelectionEnd ()) {
        t = ep.getSelectedText ();
    }
    if (t != null) {
        return t;
    }

    int line = NbDocument.findLineNumber (
        doc,
        offset
    );
    int col = NbDocument.findLineColumn (
        doc,
        offset
    );
    try {
        javax.swing.text.Element lineElem =
            org.openide.text.NbDocument.findLineRootElement (doc).
            getElement (line);

        if (lineElem == null) {
            return null;
        }
        int lineStartOffset = lineElem.getStartOffset ();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        t = doc.getText (lineStartOffset, lineLen);
        int identStart = col;
        while (identStart > 0 &&
            (Character.isJavaIdentifierPart (
                t.charAt (identStart - 1)
            ) ||
            (t.charAt (identStart - 1) == '.'))) {
            identStart--;
        }
        int identEnd = col;
        while (identEnd < lineLen &&
               Character.isJavaIdentifierPart(t.charAt(identEnd))
        ) {
            identEnd++;
        }

        if (identStart == identEnd) {
            return null;
        }
        return t.substring (identStart, identEnd);
    } catch (javax.swing.text.BadLocationException e) {
        return null;
    }
}
 
Example 15
Source File: OccurrencesMarkProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public int[] getAssignedLines() {
    int line = NbDocument.findLineNumber((StyledDocument) doc, startOffset.getOffset());
    
    return new int[] {line, line};
}
 
Example 16
Source File: ToolTipAnnotation.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static String getIdentifier (
    JPDADebugger debugger,
    StyledDocument doc,
    JEditorPane ep,
    int offset,
    boolean[] isFunctionPtr
) {
    // do always evaluation if the tooltip is invoked on a text selection
    String t = null;
    if ( (ep.getSelectionStart () <= offset) &&
         (offset <= ep.getSelectionEnd ())
    ) {
        t = ep.getSelectedText ();
    }
    if (t != null) {
        return t;
    }
    int line = NbDocument.findLineNumber (
        doc,
        offset
    );
    int col = NbDocument.findLineColumn (
        doc,
        offset
    );
    try {
        Element lineElem =
            NbDocument.findLineRootElement (doc).
            getElement (line);

        if (lineElem == null) {
            return null;
        }
        int lineStartOffset = lineElem.getStartOffset ();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        t = doc.getText (lineStartOffset, lineLen);
        int identStart = col;
        while (identStart > 0 &&
            (Character.isJavaIdentifierPart (
                t.charAt (identStart - 1)
            ) ||
            (t.charAt (identStart - 1) == '.'))) {
            identStart--;
        }
        int identEnd = col;
        while (identEnd < lineLen &&
               Character.isJavaIdentifierPart(t.charAt(identEnd))
        ) {
            identEnd++;
        }

        if (identStart == identEnd) {
            return null;
        }

        String ident = t.substring (identStart, identEnd);
        //if (JS_KEYWORDS.contains(ident)) {
            // JS keyword => Do not show anything
        //    return null;
        //}

        while (identEnd < lineLen &&
               Character.isWhitespace(t.charAt(identEnd))
        ) {
            identEnd++;
        }
        if (identEnd < lineLen && t.charAt(identEnd) == '(') {
            // We're at a function call
            isFunctionPtr[0] = true;
        }
        return ident;
    } catch (BadLocationException e) {
        return null;
    }
}
 
Example 17
Source File: ToolTipAnnotation.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static String getIdentifier (
    StyledDocument doc, 
    JEditorPane ep, 
    int offset
) {
    String t = null;
    if ( (ep.getSelectionStart () <= offset) &&
         (offset <= ep.getSelectionEnd ())
    )   t = ep.getSelectedText ();
    if (t != null) return t;
    
    int line = NbDocument.findLineNumber (
        doc,
        offset
    );
    int col = NbDocument.findLineColumn (
        doc,
        offset
    );
    try {
        Element lineElem = 
            NbDocument.findLineRootElement (doc).
            getElement (line);

        if (lineElem == null) return null;
        int lineStartOffset = lineElem.getStartOffset ();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        t = doc.getText (lineStartOffset, lineLen);
        lineLen = t.length ();
        int identStart = col;
        while ( (identStart > 0) && 
                (t.charAt (identStart - 1) != '"')
        ) {
            identStart--;
        }
        int identEnd = Math.max (col, 1);
        while ( (identEnd < lineLen) && 
                (t.charAt (identEnd - 1) != '"')
        ) {
            identEnd++;
        }

        if (identStart == identEnd) return null;
        return t.substring (identStart, identEnd - 1);
    } catch (BadLocationException e) {
        return null;
    }
}
 
Example 18
Source File: ToolTipAnnotation.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static String getIdentifier (
    JPDADebugger debugger,
    StyledDocument doc,
    JEditorPane ep,
    int offset,
    boolean[] isMethodPtr,
    String[] fieldOfPtr
) {
    // do always evaluation if the tooltip is invoked on a text selection
    String t = null;
    if ( (ep.getSelectionStart () <= offset) &&
         (offset <= ep.getSelectionEnd ())
    ) {
        t = ep.getSelectedText ();
    }
    if (t != null) {
        return t;
    }
    int line = NbDocument.findLineNumber (
        doc,
        offset
    );
    int col = NbDocument.findLineColumn (
        doc,
        offset
    );
    try {
        Element lineElem =
            NbDocument.findLineRootElement (doc).
            getElement (line);

        if (lineElem == null) {
            return null;
        }
        int lineStartOffset = lineElem.getStartOffset ();
        int lineLen = lineElem.getEndOffset() - lineStartOffset;
        t = doc.getText (lineStartOffset, lineLen);
        int identStart = col;
        while (identStart > 0 &&
            (Character.isJavaIdentifierPart (
                t.charAt (identStart - 1)
            ) ||
            (t.charAt (identStart - 1) == '.'))) {
            identStart--;
        }
        int identEnd = col;
        while (identEnd < lineLen &&
               Character.isJavaIdentifierPart(t.charAt(identEnd))
        ) {
            identEnd++;
        }

        if (identStart == identEnd) {
            return null;
        }

        String ident = t.substring (identStart, identEnd);
        if (JAVA_KEYWORDS.contains(ident)) {
            // Java keyword => Do not show anything
            return null;
        }
        int newOffset = NbDocument.findLineOffset(doc, line) + identStart + 1;
        final boolean[] isFieldStatic = new boolean[] { false };
        if (!isValidTooltipLocation(debugger, doc, newOffset, ident, fieldOfPtr, isFieldStatic)) {
            return null;
        }

        while (identEnd < lineLen &&
               Character.isWhitespace(t.charAt(identEnd))
        ) {
            identEnd++;
        }
        if (identEnd < lineLen && t.charAt(identEnd) == '(') {
            // We're at a method call
            isMethodPtr[0] = true;
        }
        
        return ident;
    } catch (BadLocationException e) {
        return null;
    }
}
 
Example 19
Source File: EditorContextImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String getSelectedMethodName_() {
        JEditorPane ep = contextDispatcher.getCurrentEditor ();
        if (ep == null) {
            return "";
        }
        StyledDocument doc = (StyledDocument) ep.getDocument ();
        if (doc == null) {
            return "";
        }
        int offset = ep.getCaret ().getDot ();
        String t;
//        if ( (ep.getSelectionStart () <= offset) &&
//             (offset <= ep.getSelectionEnd ())
//        )   t = ep.getSelectedText ();
//        if (t != null) return t;

        int line = NbDocument.findLineNumber (
            doc,
            offset
        );
        int col = NbDocument.findLineColumn (
            doc,
            offset
        );
        try {
            javax.swing.text.Element lineElem =
                org.openide.text.NbDocument.findLineRootElement (doc).
                getElement (line);

            if (lineElem == null) {
                return "";
            }
            int lineStartOffset = lineElem.getStartOffset ();
            int lineLen = lineElem.getEndOffset () - lineStartOffset;
            // t contains current line in editor
            t = doc.getText (lineStartOffset, lineLen);

            int identStart = col;
            while ( identStart > 0 &&
                    Character.isJavaIdentifierPart (
                        t.charAt (identStart - 1)
                    )
            ) {
                identStart--;
            }

            int identEnd = col;
            while (identEnd < lineLen &&
                   Character.isJavaIdentifierPart (t.charAt (identEnd))
            ) {
                identEnd++;
            }
            int i = t.indexOf ('(', identEnd);
            if (i < 0) {
                return "";
            }
            if (t.substring (identEnd, i).trim ().length () > 0) {
                return "";
            }

            if (identStart == identEnd) {
                return "";
            }
            return t.substring (identStart, identEnd);
        } catch (javax.swing.text.BadLocationException ex) {
            return "";
        }
    }
 
Example 20
Source File: EditorContextDispatcher.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Get a list of MIME types of languages found on a line.
 * @param line The line to search for the MIME types.
 * @return A set of MIME types.
 * @since 2.50
 */
public Set<String> getMIMETypesOnLine(Line line) {
    EditorCookie editorCookie = line.getLookup().lookup(EditorCookie.class);
    if (editorCookie == null) {
        DataObject dobj = line.getLookup().lookup(DataObject.class);
        if (dobj != null) {
            editorCookie = dobj.getLookup().lookup(EditorCookie.class);
        }
        if (editorCookie == null) {
            return Collections.emptySet();
        }
    }
    StyledDocument document = editorCookie.getDocument();
    if (document == null) {
        return Collections.emptySet();
    }
    Set<String> mimeTypes = null;
    ((AbstractDocument) document).readLock();
    try {
        TokenHierarchy<Document> th = TokenHierarchy.get((Document) document);
        int ln = line.getLineNumber();
        int offset = NbDocument.findLineOffset(document, ln);
        int maxOffset = document.getLength() - 1;
        int maxLine = NbDocument.findLineNumber(document, maxOffset);
        int offset2;
        if (ln + 1 > maxLine) {
            offset2 = maxOffset;
        } else {
            offset2 = NbDocument.findLineOffset(document, ln+1) - 1;
        }
        // The line has offsets <offset, offset2>
        Set<LanguagePath> languagePaths = th.languagePaths();
        for (LanguagePath lp : languagePaths) {
            List<TokenSequence<?>> tsl = th.tokenSequenceList(lp, offset, offset2);
            for (TokenSequence ts : tsl) {
                if (ts.moveNext()) {
                    //int to = ts.offset();
                    //if (!(offset <= to && to < offset2)) {
                    //    continue;
                    //}
                    String mimeType = ts.language().mimeType();
                    if (mimeType != null) {
                        if (mimeTypes == null) {
                            mimeTypes = Collections.singleton(mimeType);
                        } else {
                            if (mimeTypes.size() == 1) {
                                mimeTypes = new HashSet<String>(mimeTypes);
                            }
                            mimeTypes.add(mimeType);
                        }
                    }
                }
            }
        }
    } finally {
        ((AbstractDocument) document).readUnlock();
    }
    return (mimeTypes != null) ? mimeTypes : Collections.<String>emptySet();
    
}