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

The following examples show how to use org.openide.text.NbDocument#findLineOffset() . 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: EditorContextImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** return the offset of the first non-whitespace character on the line,
           or -1 when the line does not exist
 */
private static int findLineOffset(StyledDocument doc, int lineNumber) {
    int offset;
    try {
        offset = NbDocument.findLineOffset (doc, lineNumber - 1);
        int offset2 = NbDocument.findLineOffset (doc, lineNumber);
        try {
            String lineStr = doc.getText(offset, offset2 - offset);
            for (int i = 0; i < lineStr.length(); i++) {
                if (!Character.isWhitespace(lineStr.charAt(i))) {
                    offset += i;
                    break;
                }
            }
        } catch (BadLocationException ex) {
            // ignore
        }
    } catch (IndexOutOfBoundsException ioobex) {
        return -1;
    }
    return offset;
}
 
Example 3
Source File: AnnotationBar.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Locates AnnotateLine associated with given line. The
 * line is translated to Element that is used as map lookup key.
 * The map is initially filled up with Elements sampled on
 * annotate() method.
 *
 * <p>Key trick is that Element's identity is maintained
 * until line removal (and is restored on undo).
 *
 * @param line
 * @return found AnnotateLine or <code>null</code>
 */
private AnnotateLine getAnnotateLine(int line) {
    StyledDocument sd = (StyledDocument) doc;
    int lineOffset = NbDocument.findLineOffset(sd, line);
    Element element = sd.getParagraphElement(lineOffset);
    AnnotateLine al = elementAnnotations.get(element);

    if (al != null) {
        int startOffset = element.getStartOffset();
        int endOffset = element.getEndOffset();
        try {
            int len = endOffset - startOffset;
            String text = doc.getText(startOffset, len -1);
            String content = al.getContent();
            if (text.equals(content)) {
                return al;
            }
        } catch (BadLocationException e) {
            Mercurial.LOG.log(Level.INFO, "HG.AB: can not locate line annotation.");  // NOI18N
        }
    }

    return null;
}
 
Example 4
Source File: AnnotationBar.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Locates AnnotateLine associated with given line. The
 * line is translated to Element that is used as map lookup key.
 * The map is initially filled up with Elements sampled on
 * annotate() method.
 *
 * <p>Key trick is that Element's identity is maintained
 * until line removal (and is restored on undo).
 *
 * @param line
 * @return found AnnotateLine or <code>null</code>
 */
private VcsAnnotation getAnnotateLine(int line) {
    StyledDocument sd = (StyledDocument) doc;
    int lineOffset = NbDocument.findLineOffset(sd, line);
    Element element = sd.getParagraphElement(lineOffset);
    VcsAnnotation al = elementAnnotations.get(element);

    if (al != null) {
        int startOffset = element.getStartOffset();
        int endOffset = element.getEndOffset();
        try {
            int len = endOffset - startOffset;
            String text = doc.getText(startOffset, len -1);
            String content = al.getDocumentText();
            if (text.equals(content)) {
                return al;
            }
        } catch (BadLocationException e) {
            ErrorManager err = ErrorManager.getDefault();
            err.annotate(e, "CVS.AB: can not locate line annotation."); // NOI18N
            err.notify(ErrorManager.INFORMATIONAL, e);
        }
    }

    return null;
}
 
Example 5
Source File: IndentFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean isEmpty (
    int                     ln,
    StyledDocument          document,
    Set<Integer>            whitespaces
) throws BadLocationException {
    int start = NbDocument.findLineOffset (document, ln);
    int end = document.getLength ();
    try {
        end = NbDocument.findLineOffset (document, ln + 1) - 1;
    } catch (IndexOutOfBoundsException ex) {
    }
    TokenSequence ts = Utils.getTokenSequence (document, start);
    if (ts.token () == null) return true;
    while (whitespaces.contains (ts.token ().id ().ordinal ())) {
        if (!ts.moveNext ()) return true;
        if (ts.offset () > end) return true;
    }
    return false;
}
 
Example 6
Source File: EditorTokenInput.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public String toString () {
        int offset = next (1) == null ?
            doc.getLength () : next (1).getOffset ();
        int lineNumber = NbDocument.findLineNumber (doc, offset);
        return (String) doc.getProperty ("title") + ":" + 
            (lineNumber + 1) + "," + 
            (offset - NbDocument.findLineOffset (doc, lineNumber) + 1);
//        StringBuffer sb = new StringBuffer ();
//        TokenItem t = next;
//        int i = 0;
//        while (i < 10) {
//            if (t == null) break;
//            EditorToken et = (EditorToken) t.getTokenID ();
//            sb.append (Token.create (
//                et.getMimeType (),
//                et.getType (),
//                t.getImage (),
//                null
//            ));
//            t = t.getNext ();
//            i++;
//        }
//        return sb.toString ();
    }
 
Example 7
Source File: HintsControllerImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static int[] computeLineSpan(Document doc, int lineNumber) throws BadLocationException {
    lineNumber = Math.min(lineNumber, NbDocument.findLineRootElement((StyledDocument) doc).getElementCount());
    
    int lineStartOffset = NbDocument.findLineOffset((StyledDocument) doc, Math.max(0, lineNumber - 1));
    int lineEndOffset;
    
    if (doc instanceof BaseDocument) {
        lineEndOffset = Utilities.getRowEnd((BaseDocument) doc, lineStartOffset);
    } else {
        //XXX: performance:
        String lineText = doc.getText(lineStartOffset, doc.getLength() - lineStartOffset);
        
        lineText = lineText.indexOf('\n') != (-1) ? lineText.substring(0, lineText.indexOf('\n')) : lineText;
        lineEndOffset = lineStartOffset + lineText.length();
    }
    
    int[] span = new int[] {lineStartOffset, lineEndOffset};
    
    computeLineSpan(doc, span);
    
    return span;
}
 
Example 8
Source File: ImportDebugger.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static String getText (Line l) throws Exception {
    EditorCookie ec = (EditorCookie) l.getDataObject ().
        getCookie (EditorCookie.class);
    StyledDocument doc = ec.openDocument ();
    if (doc == null) return "";
    int off = NbDocument.findLineOffset (doc, l.getLineNumber ());
    int len = NbDocument.findLineOffset (doc, l.getLineNumber () + 1) - 
        off - 1;
    return doc.getText (off, len);
}
 
Example 9
Source File: ImportDebugger.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static String getText (Line l) throws Exception {
    EditorCookie ec = (EditorCookie) l.getDataObject ().
        getCookie (EditorCookie.class);
    StyledDocument doc = ec.openDocument ();
    if (doc == null) return "";
    int off = NbDocument.findLineOffset (doc, l.getLineNumber ());
    int len = NbDocument.findLineOffset (doc, l.getLineNumber () + 1) - 
        off - 1;
    return doc.getText (off, len);
}
 
Example 10
Source File: HighlightImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static HighlightImpl parse(StyledDocument doc, String line) throws ParseException, BadLocationException {
    MessageFormat f = new MessageFormat("[{0}], {1,number,integer}:{2,number,integer}-{3,number,integer}:{4,number,integer}");
    Object[] args = f.parse(line);
    
    String attributesString = (String) args[0];
    int    lineStart  = ((Long) args[1]).intValue();
    int    columnStart  = ((Long) args[2]).intValue();
    int    lineEnd  = ((Long) args[3]).intValue();
    int    columnEnd  = ((Long) args[4]).intValue();
    
    String[] attrElements = attributesString.split(",");
    List<ColoringAttributes> attributes = new ArrayList<ColoringAttributes>();
    
    for (String a : attrElements) {
        a = a.trim();
        
        attributes.add(ColoringAttributes.valueOf(a));
    }
    
    if (attributes.contains(null))
        throw new NullPointerException();
    
    int offsetStart = NbDocument.findLineOffset(doc, lineStart) + columnStart;
    int offsetEnd = NbDocument.findLineOffset(doc, lineEnd) + columnEnd;
    
    return new HighlightImpl(doc, offsetStart, offsetEnd, attributes);
}
 
Example 11
Source File: ToolTipAnnotation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void evaluate(Line.Part part) {
    Line line = part.getLine();
    if (line == null) {
        return;
    }
    DataObject dataObject = DataEditorSupport.findDataObject(line);
    if (!isPhpDataObject(dataObject)) {
        return;
    }
    EditorCookie editorCookie = (EditorCookie) dataObject.getLookup().lookup(EditorCookie.class);
    StyledDocument document = editorCookie.getDocument();
    if (document == null) {
        return;
    }
    final int offset = NbDocument.findLineOffset(document, part.getLine().getLineNumber()) + part.getColumn();
    JEditorPane ep = EditorContextDispatcher.getDefault().getCurrentEditor();
    String selectedText = getSelectedText(ep, offset);
    if (selectedText != null) {
        if (isPHPIdentifier(selectedText)) {
            sendPropertyGetCommand(selectedText);
        } else if (PhpOptions.getInstance().isDebuggerWatchesAndEval()) {
            sendEvalCommand(selectedText);
        }
    } else {
        final String identifier = ep != null ? getIdentifier(document, ep, offset) : null;
        if (identifier != null) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    sendPropertyGetCommand(identifier);
                }
            };
            RP.post(runnable);
        }
    }
    //TODO: review, replace the code depending on lexer.model - part I
}
 
Example 12
Source File: GoToJavaSourceProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean openAtLine(CompilationController controller, Document doc, String methodName, int line) {
    try {
        if (line > -1) {
            DataObject od = DataObject.find(controller.getFileObject());
            int offset = NbDocument.findLineOffset((StyledDocument) doc, line);
            ExecutableElement parentMethod = controller.getTreeUtilities().scopeFor(offset).getEnclosingMethod();
            if (parentMethod != null) {
                String offsetMethodName = parentMethod.getSimpleName().toString();
                if (methodName.equals(offsetMethodName)) {
                    LineCookie lc = od.getLookup().lookup(LineCookie.class);
                    if (lc != null) {
                        final Line l = lc.getLineSet().getCurrent(line - 1);

                        if (l != null) {
                            CommonUtils.runInEventDispatchThread(new Runnable() {
                                @Override
                                public void run() {
                                    l.show(Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS);
                                }
                            });
                            return true;
                        }
                    }
                }
            }
        }
    } catch (DataObjectNotFoundException e) {
        LOG.log(Level.WARNING, "Error accessing dataobject", e);
    }
    return false;
}
 
Example 13
Source File: HighlightImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static HighlightImpl parse(StyledDocument doc, String line) throws ParseException, BadLocationException {
    MessageFormat f = new MessageFormat("[{0}], {1,number,integer}:{2,number,integer}-{3,number,integer}:{4,number,integer}");
    Object[] args = f.parse(line);
    
    String attributesString = (String) args[0];
    int    lineStart  = ((Long) args[1]).intValue();
    int    columnStart  = ((Long) args[2]).intValue();
    int    lineEnd  = ((Long) args[3]).intValue();
    int    columnEnd  = ((Long) args[4]).intValue();
    
    String[] attrElements = attributesString.split(",");
    List<ColoringAttributes> attributes = new ArrayList<ColoringAttributes>();
    
    for (String a : attrElements) {
        a = a.trim();
        
        attributes.add(ColoringAttributes.valueOf(a));
    }
    
    if (attributes.contains(null))
        throw new NullPointerException();
    
    int offsetStart = NbDocument.findLineOffset(doc, lineStart) + columnStart;
    int offsetEnd = NbDocument.findLineOffset(doc, lineEnd) + columnEnd;
    
    return new HighlightImpl(doc, offsetStart, offsetEnd, attributes);
}
 
Example 14
Source File: JspParserErrorAnnotation.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void attachToLineSet(Set lines) {
        char string[];
        int start,end;
        Line.Part part;
        
        try {
            docline=lines.getCurrent(line-1);
        } catch (IndexOutOfBoundsException ex) {
            // the document has been changed and the line is deleted
            return;
        }
        
        String annTxt = docline.getText(); // text on the line
        if (annTxt == null) return; // document is already closed
        
        int offset = NbDocument.findLineOffset(document, docline.getLineNumber()) + column+1;  // offset, where the bug is reported
        start = 0;  // column, where the underlining starts on the line, where the bug should be attached. default first column
        string = annTxt.toCharArray();
        end = string.length - 1; // length of the underlining
        
        // when the error is reported outside the page, underline the first line
        if (offset < 1){
            textOnLine(docline);
            return;
        }
        TokenHierarchy tokenHierarchy = TokenHierarchy.get(document);
        TokenSequence tokenSequence = tokenHierarchy.tokenSequence();
        tokenSequence.move(offset - 1);
        if (!tokenSequence.moveNext() && !tokenSequence.movePrevious()) {
            //no token
            textOnLine(docline);
            return ;
        }
        start = NbDocument.findLineColumn(document, tokenSequence.token().offset(tokenHierarchy));
        offset = tokenSequence.token().offset(tokenHierarchy);
        
        // Find the start and the end of the appropriate tag or EL
        if (tokenSequence.token().id() != JspTokenId.EL){
            // the error is in the tag or directive
            // find the start of the tag, directive
            while (!(tokenSequence.token().id() == JspTokenId.SYMBOL
                    && tokenSequence.token().text().toString().charAt(0) == '<' //directive
                    || tokenSequence.token().id() == JspTokenId.TAG)  //or jsp tag
                    && tokenSequence.movePrevious()) {
                start = NbDocument.findLineColumn(document, tokenSequence.token().offset(tokenHierarchy));
                offset = tokenSequence.token().offset(tokenHierarchy);
            }
            
            // find the end of the tag or directive
            while ((tokenSequence.token().id() != JspTokenId.SYMBOL
                    || tokenSequence.token().text().toString().trim().length() > 0 
                    && tokenSequence.token().text().toString().charAt(tokenSequence.token().text().toString().trim().length()-1) != '>')
                    && tokenSequence.moveNext());
        } else {
            // The error is in EL - start and offset are set properly - we have one big EL token now in JspLexer
        }
        
        end = tokenSequence.token().offset(tokenHierarchy) + tokenSequence.token().length() - offset;
        
//            if (token != null)
//                end = token.getOffset() + token.getImage().trim().length() - offset;
//            else {
//                while (end >= 0 && end > start && string[end] != ' ') {
//                    end--;
//                }
//            }
        
        part=docline.createPart(start, end);//token.getImage().length());
        attach(part);
    }
 
Example 15
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 16
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 17
Source File: CSSUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Opens the specified file at the given position. The position is either
 * offset (when {@code lineNo} is -1) or line/column otherwise.
 * This method has been copied (with minor modifications) from UiUtils
 * class in csl.api module. This method is not CSS-specific. It was placed
 * into this file just because there was no better place.
 * 
 * @param fob file that should be opened.
 * @param lineNo line where the caret should be placed
 * (or -1 when the {@code columnNo} represents an offset).
 * @param columnNo column (or offset when {@code lineNo} is -1)
 * where the caret should be placed.
 * @return {@code true} when the file was opened successfully,
 * returns {@code false} otherwise.
 */
private static boolean openAt(FileObject fob, int lineNo, int columnNo) {
    try {
        DataObject dob = DataObject.find(fob);
        Lookup dobLookup = dob.getLookup();
        EditorCookie ec = dobLookup.lookup(EditorCookie.class);
        LineCookie lc = dobLookup.lookup(LineCookie.class);
        OpenCookie oc = dobLookup.lookup(OpenCookie.class);

        if ((ec != null) && (lc != null) && (columnNo != -1)) {
            StyledDocument doc;
            try {
                doc = ec.openDocument();
            } catch (UserQuestionException uqe) {
                String title = NbBundle.getMessage(
                        CSSUtils.class,
                        "CSSUtils.openQuestion"); // NOI18N
                Object value = DialogDisplayer.getDefault().notify(new NotifyDescriptor.Confirmation(
                        uqe.getLocalizedMessage(),
                        title,
                        NotifyDescriptor.YES_NO_OPTION));
                if (value != NotifyDescriptor.YES_OPTION) {
                    return false;
                }
                uqe.confirmed();
                doc = ec.openDocument();
            }

            if (doc != null) {
                boolean offset = (lineNo == -1);
                int line = offset ? NbDocument.findLineNumber(doc, columnNo) : lineNo;
                int column = offset ? columnNo - NbDocument.findLineOffset(doc, line) : columnNo;
                if (line != -1) {
                    Line l = lc.getLineSet().getCurrent(line);
                    if (l != null) {
                        l.show(Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS, column);
                        return true;
                    }
                }
            }
        }

        if (oc != null) {
            oc.open();
            return true;
        }
    } catch (IOException ioe) {
        Logger.getLogger(CSSUtils.class.getName()).log(Level.INFO, null, ioe);
    }

    return false;
}
 
Example 18
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 19
Source File: UiUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static boolean doOpen(FileObject fo, int offset) {
    try {
        DataObject od = DataObject.find(fo);
        EditorCookie ec = od.getLookup().lookup(EditorCookie.class);
        LineCookie lc = od.getLookup().lookup(LineCookie.class);
        
        if (ec != null && lc != null && offset != -1) {
            StyledDocument doc = null;
            try {
                doc = ec.openDocument();
            } catch (UserQuestionException uqe) {
                final Object value = DialogDisplayer.getDefault().notify(
                        new NotifyDescriptor.Confirmation(uqe.getLocalizedMessage(),
                        NbBundle.getMessage(UiUtils.class, "TXT_Question"),
                        NotifyDescriptor.YES_NO_OPTION));
                if (value != NotifyDescriptor.YES_OPTION) {
                    return false;
                }
                uqe.confirmed();
                doc = ec.openDocument();
            }
            if (doc != null) {
                int line = NbDocument.findLineNumber(doc, offset);
                int lineOffset = NbDocument.findLineOffset(doc, line);
                int column = offset - lineOffset;
                
                if (line != -1) {
                    Line l = lc.getLineSet().getCurrent(line);
                    
                    if (l != null) {
                        doShow( l, column);
                        return true;
                    }
                }
            }
        }
        
        OpenCookie oc = od.getLookup().lookup(OpenCookie.class);
        
        if (oc != null) {
            doOpen(oc);
            return true;
        }
    } catch (IOException e) {
        if (log.isLoggable(Level.INFO))
            log.log(Level.INFO, e.getMessage(), e);
    }
    
    return false;
}
 
Example 20
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;
    }
}