Java Code Examples for org.netbeans.editor.BaseDocument#readUnlock()

The following examples show how to use org.netbeans.editor.BaseDocument#readUnlock() . 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: HyperlinkOperation.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void performHyperlinking(int position, HyperlinkType type) {
    final BaseDocument doc = (BaseDocument) component.getDocument();
    doc.readLock();
    try {
        HyperlinkProviderExt provider = findProvider(position, type);
        if (provider != null) {
            int[] offsets = provider.getHyperlinkSpan(doc, position, type);
            if (offsets != null) {
                makeHyperlink(type, provider, offsets[0], offsets[1], position);
            }
        } else {
            unHyperlink(true);
        }
    } finally {
        doc.readUnlock();
    }

}
 
Example 2
Source File: RubyEmbeddingProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private List<Embedding> translate(Snapshot snapshot) {
    BaseDocument d = (BaseDocument) snapshot.getSource().getDocument(false);
    if (d == null) {
        return Collections.emptyList();
    }

    List<Embedding> embeddings = new ArrayList<Embedding>();

    try {
        d.readLock();
        TokenHierarchy<Document> tokenHierarchy = TokenHierarchy.get((Document) d);
        TokenSequence<YamlTokenId> tokenSequence = tokenHierarchy.tokenSequence(YamlTokenId.language()); //get top level token sequence

        if (tokenSequence != null) {
            translate(snapshot, tokenHierarchy, tokenSequence, embeddings);
        }
    } finally {
        d.readUnlock();
    }
    return embeddings;
}
 
Example 3
Source File: BaseHighlightingTask.java    From nb-springboot with Apache License 2.0 6 votes vote down vote up
@Override
public void run(CfgPropsParser.CfgPropsParserResult cfgResult, SchedulerEvent se) {
    canceled = false;
    final Preferences prefs = NbPreferences.forModule(PrefConstants.class);
    final int sevLevel = prefs.getInt(getHighlightPrefName(), getHighlightDefaultValue());
    List<ErrorDescription> errors = new ArrayList<>();
    final BaseDocument document = (BaseDocument) cfgResult.getSnapshot().getSource().getDocument(false);
    if (document != null) {
        // skip error calculation if preference set to "None"
        if (sevLevel > 0) {
            Severity severity = decodeSeverity(sevLevel);
            document.readLock();
            internalRun(cfgResult, se, document, errors, severity);
            document.readUnlock();
        }
        HintsController.setErrors(document, getErrorLayerName(), errors);
    }
}
 
Example 4
Source File: PHP73UnhandledError.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void checkFunctionCallTrailingCommas() {
    if (!nodes.isEmpty()) {
        BaseDocument document = GsfUtilities.getDocument(fileObject, true);
        if (document == null) {
            return;
        }
        document.readLock();
        try {
            TokenSequence<PHPTokenId> ts = LexUtilities.getPHPTokenSequence(document, 0);
            if (ts == null) {
                return;
            }
            checkFunctionCallTrailingCommas(ts);
        } finally {
            document.readUnlock();
            nodes.clear();
        }
    }
}
 
Example 5
Source File: PHP73UnhandledError.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void checkFlexibleHeredocAndNowdoc() {
    if (CancelSupport.getDefault().isCancelled()) {
        return;
    }

    BaseDocument document = GsfUtilities.getDocument(fileObject, true);
    if (document == null) {
        return;
    }
    document.readLock();
    try {
        TokenSequence<PHPTokenId> ts = LexUtilities.getPHPTokenSequence(document, document.getLength());
        if (ts == null) {
            return;
        }
        ts.move(document.getLength());
        checkHeredocNowdocIndentationAndNewline(ts);
    } finally {
        document.readUnlock();
    }
}
 
Example 6
Source File: CompletionContext.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean copyDocument(final BaseDocument src, final BaseDocument dest) {
        final boolean[] retVal = new boolean[]{true};

        src.readLock();
        try{
            dest.runAtomic(new Runnable() {

                @Override
                public void run() {
                    try {
                        String docText = src.getText(0, src.getLength());
                        dest.insertString(0, docText, null);
//                        dest.putProperty(Language.class, src.getProperty(Language.class));
                    } catch(BadLocationException ble) {
                        Exceptions.printStackTrace(ble);
                        retVal[0] = false;
                    }
                }
            });
        } finally {
            src.readUnlock();
        }

        return retVal[0];
    }
 
Example 7
Source File: IntroduceSuggestion.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static int getOffsetAfterBlockCloseCurly(BaseDocument doc, int offset) throws BadLocationException {
    int retval = offset;
    doc.readLock();
    try {
        TokenSequence<? extends PHPTokenId> ts = LexUtilities.getPHPTokenSequence(doc, retval);
        if (ts != null) {
            ts.move(retval);
            int curlyMatch = 0;
            while (ts.moveNext()) {
                Token t = ts.token();
                if (t.id() == PHPTokenId.PHP_CURLY_OPEN || t.id() == PHPTokenId.PHP_CURLY_CLOSE) {
                    if (t.id() == PHPTokenId.PHP_CURLY_OPEN) {
                        curlyMatch++;
                    } else if (t.id() == PHPTokenId.PHP_CURLY_CLOSE) {
                        curlyMatch--;
                    }
                    if (curlyMatch == 0) {
                        ts.moveNext();
                        retval = ts.offset();
                        break;
                    }
                }
            }
        }
    } finally {
        doc.readUnlock();
    }
    return retval;
}
 
Example 8
Source File: TwigBracesMatcher.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public int[] findMatches() throws InterruptedException, BadLocationException {
    int[] result = null;
    BaseDocument document = (BaseDocument) context.getDocument();
    document.readLock();
    try {
        result = findMatchesUnderLock();
    } finally {
        document.readUnlock();
    }
    return result;
}
 
Example 9
Source File: TwigBracesMatcher.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public int[] findOrigin() throws InterruptedException, BadLocationException {
    int[] result = null;
    BaseDocument document = (BaseDocument) context.getDocument();
    document.readLock();
    try {
        result = findOriginUnderLock();
    } finally {
        document.readUnlock();
    }
    return result;
}
 
Example 10
Source File: LatteBracesMatcher.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public int[] findMatches() throws InterruptedException, BadLocationException {
    int[] result = null;
    BaseDocument document = (BaseDocument) context.getDocument();
    document.readLock();
    try {
        result = findMatchesUnderLock();
    } finally {
        document.readUnlock();
    }
    return result;
}
 
Example 11
Source File: LatteBracesMatcher.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public int[] findOrigin() throws InterruptedException, BadLocationException {
    int[] result = null;
    BaseDocument document = (BaseDocument) context.getDocument();
    document.readLock();
    try {
        result = findOriginUnderLock();
    } finally {
        document.readUnlock();
    }
    return result;
}
 
Example 12
Source File: ExtSyntaxSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Get the chain of the tokens for the given block of text.
   * The returned chain of token-items reflects the tokens
   * as they occur in the text and therefore the first token
   * can start at the slightly lower position than the requested one.
   * The chain itself can be extended automatically when
   * reaching the first chain item and calling <tt>getPrevious()</tt>
   * on it. Another chunk of the tokens will be parsed and
   * the head of the chain will be extended. However this happens
   * only in case there was no modification performed to the document
   * between the creation of the chain and this moment. Otherwise
   * this call throws <tt>IllegalStateException</tt>.
   * 
   * @param startOffset starting position of the block
   * @param endOffset ending position of the block
   * @return the first item of the token-item chain or null if there are
   *  no tokens in the given area or the area is so small that it lays
   *  inside one token. To prevent this provide the area that spans a new-line.
   */
   public TokenItem getTokenChain(int startOffset, int endOffset)
   throws BadLocationException {

       if (startOffset < 0) {
    throw new IllegalArgumentException("startOffset=" + startOffset + " < 0"); // NOI18N
}
if (startOffset > endOffset) {
    throw new IllegalArgumentException("startOffset=" + startOffset // NOI18N
	    + " > endOffset=" + endOffset); // NOI18N
}
       TokenItem chain = null;
       BaseDocument doc = getDocument();
       doc.readLock();
       try {
           int docLen = doc.getLength();
           endOffset = Math.min(endOffset, docLen);
           if( startOffset < docLen ) {
               TokenItemTP tp = new TokenItemTP();            
               tp.targetOffset = endOffset;
               tokenizeText(tp, startOffset, endOffset, false);
               chain = tp.getTokenChain();
           }
       } finally {
           doc.readUnlock();
       }

       return chain;
   }
 
Example 13
Source File: ModifiersCheckHintError.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static int getStartOffset(final BaseDocument doc, final int elementOffset) {
    int retval = 0;
    doc.readLock();
    try {
        TokenSequence<? extends PHPTokenId> ts = LexUtilities.getPHPTokenSequence(doc, elementOffset);
        if (ts != null) {
            ts.move(elementOffset);
            TokenId lastTokenId = null;
            while (ts.movePrevious()) {
                Token t = ts.token();
                if (t.id() != PHPTokenId.PHP_PUBLIC && t.id() != PHPTokenId.PHP_PROTECTED && t.id() != PHPTokenId.PHP_PRIVATE
                        && t.id() != PHPTokenId.PHP_STATIC && t.id() != PHPTokenId.PHP_FINAL && t.id() != PHPTokenId.PHP_ABSTRACT
                        && t.id() != PHPTokenId.PHP_FUNCTION && t.id() != PHPTokenId.WHITESPACE && t.id() != PHPTokenId.PHP_CLASS
                        && t.id() != PHPTokenId.PHP_CONST) {
                    ts.moveNext();
                    if (lastTokenId == PHPTokenId.WHITESPACE) {
                        ts.moveNext();
                    }
                    retval = ts.offset();
                    break;
                }
                lastTokenId = t.id();
            }
        }
    } finally {
        doc.readUnlock();
    }
    return retval;
}
 
Example 14
Source File: PHP72UnhandledError.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void checkGroupUseTrailingCommas() {
    if (!lastUseStatementParts.isEmpty()) {
        BaseDocument document = GsfUtilities.getDocument(fileObject, true);
        if (document == null) {
            return;
        }
        document.readLock();
        try {
            TokenSequence<PHPTokenId> ts = LexUtilities.getPHPTokenSequence(document, 0);
            if (ts == null) {
                return;
            }
            lastUseStatementParts.forEach((lastUseStatementPart) -> {
                if (CancelSupport.getDefault().isCancelled()) {
                    return;
                }
                ts.move(lastUseStatementPart.getEndOffset());
                if (ts.moveNext()) {
                    Token<? extends PHPTokenId> token = LexUtilities.findNext(ts, Arrays.asList(PHPTokenId.WHITESPACE));
                    if (token == null) {
                        return;
                    }
                    if (token.id() == PHPTokenId.PHP_TOKEN && TokenUtilities.textEquals(token.text(), ",")) { // NOI18N
                        createError(lastUseStatementPart);
                    }
                }
            });
        } finally {
            document.readUnlock();
            lastUseStatementParts.clear();
        }
    }
}
 
Example 15
Source File: LanguageRegistry.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public List<Language> getEmbeddedLanguages(BaseDocument doc, int offset) {
        List<Language> result = new ArrayList<Language>();

        doc.readLock(); // Read-lock due to Token hierarchy use
        try {
            // TODO - I should only do this for languages which CAN have it
            /*
     at org.netbeans.lib.lexer.inc.IncTokenList.reinit(IncTokenList.java:113)
        at org.netbeans.lib.lexer.TokenHierarchyOperation.setActiveImpl(TokenHierarchyOperation.java:257)
        at org.netbeans.lib.lexer.TokenHierarchyOperation.isActiveImpl(TokenHierarchyOperation.java:308)
        at org.netbeans.lib.lexer.TokenHierarchyOperation.tokenSequence(TokenHierarchyOperation.java:344)
        at org.netbeans.lib.lexer.TokenHierarchyOperation.tokenSequence(TokenHierarchyOperation.java:338)
        at org.netbeans.api.lexer.TokenHierarchy.tokenSequence(TokenHierarchy.java:183)
        at org.netbeans.modules.csl.LanguageRegistry.getEmbeddedLanguages(LanguageRegistry.java:336)
        at org.netbeans.modules.gsfret.hints.infrastructure.SuggestionsTask.getHintsProviderLanguage(SuggestionsTask.java:70)
        at org.netbeans.modules.gsfret.hints.infrastructure.SuggestionsTask.run(SuggestionsTask.java:94)
        at org.netbeans.modules.gsfret.hints.infrastructure.SuggestionsTask.run(SuggestionsTask.java:63)
[catch] at org.netbeans.napi.gsfret.source.Source$CompilationJob.run(Source.java:1272)             * 
             */
            TokenSequence ts = TokenHierarchy.get(doc).tokenSequence();
            if (ts != null) {
                addLanguages(result, ts, offset);
            }
        } finally {
            doc.readUnlock();
        }

        String mimeType = (String) doc.getProperty("mimeType"); // NOI18N
        if (mimeType != null) {
            Language language = getLanguageByMimeType(mimeType);
            if (language != null && (result.size() == 0 || result.get(result.size()-1) != language))  {
                result.add(language);
            }
        }
        
        return result;
    }
 
Example 16
Source File: LexUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Find the Groovy token sequence (in case it's embedded in something else at the top level. */
@SuppressWarnings("unchecked")
public static TokenSequence<GroovyTokenId> getGroovyTokenSequence(Document doc, int offset) {
    final BaseDocument baseDocument = (BaseDocument) doc;
    try {
        baseDocument.readLock();
        return getGroovyTokenSequence(TokenHierarchy.get(doc), offset);
    } finally {
        baseDocument.readUnlock();
    }
}
 
Example 17
Source File: WhereUsedElement.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static WhereUsedElement create(FileObject fileObject, Entry entry, ElementKind kind, boolean related) {
    Icon icon = UiUtils.getElementIcon(kind, Collections.<Modifier>emptyList());
    String name = entry.getName();
    OffsetRange range = entry.getDocumentRange();

    int start = range.getStart();
    int end = range.getEnd();
    
    int sta = start;
    int en = start; // ! Same line as start
    String content = null;
    
    BaseDocument bdoc = GsfUtilities.getDocument(fileObject, true);
    try {
        bdoc.readLock();

        // I should be able to just call tree.getInfo().getText() to get cached
        // copy - but since I'm playing fast and loose with compilationinfos
        // for for example find subclasses (using a singly dummy FileInfo) I need
        // to read it here instead
        content = bdoc.getText(0, bdoc.getLength());
        sta = Utilities.getRowFirstNonWhite(bdoc, start);

        if (sta == -1) {
            sta = Utilities.getRowStart(bdoc, start);
        }

        en = Utilities.getRowLastNonWhite(bdoc, start);

        if (en == -1) {
            en = Utilities.getRowEnd(bdoc, start);
        } else {
            // Last nonwhite - left side of the last char, not inclusive
            en++;
        }

        // Sometimes the node we get from the AST is for the whole block
        // (e.g. such as the whole class), not the argument node. This happens
        // for example in Find Subclasses out of the index. In this case
        if (end > en) {
            end = start + name.length();

            if (end > bdoc.getLength()) {
                end = bdoc.getLength();
            }
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        bdoc.readUnlock();
    }

    StringBuilder sb = new StringBuilder();
    if (end < sta) {
        // XXX Shouldn't happen, but I still have AST offset errors
        sta = end;
    }
    if (start < sta) {
        // XXX Shouldn't happen, but I still have AST offset errors
        start = sta;
    }
    if (en < end) {
        // XXX Shouldn't happen, but I still have AST offset errors
        en = end;
    }
    sb.append(encodeCharRefs(content.subSequence(sta, start).toString()));
    sb.append("<b>"); // NOI18N
    sb.append(content.subSequence(start, end));
    sb.append("</b>"); // NOI18N
    sb.append(encodeCharRefs(content.subSequence(end, en).toString()));
    if(!related) {
        sb.append(NbBundle.getMessage(WhereUsedElement.class, "MSG_Unrelated_Where_Used_Occurance")); //NOI18N
    }


    CloneableEditorSupport ces = GsfUtilities.findCloneableEditorSupport(fileObject);
    PositionRef ref1 = ces.createPositionRef(start, Bias.Forward);
    PositionRef ref2 = ces.createPositionRef(end, Bias.Forward);
    PositionBounds bounds = new PositionBounds(ref1, ref2);

    return new WhereUsedElement(bounds, sb.toString().trim(), 
            fileObject, name, new OffsetRange(start, end), icon);
}
 
Example 18
Source File: DockerfileCompletion.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private CodeCompletionResult completeImpl(@NonNull final CodeCompletionContext ctx) {
    final BaseDocument doc = (BaseDocument) ctx.getParserResult().getSnapshot().getSource().getDocument(false);
    if (doc == null) {
        return CodeCompletionResult.NONE;
    }
    doc.readLock();
    try {
        final int offset = ctx.getCaretOffset();
        String prefix = ctx.getPrefix();
        final int lineStart = LineDocumentUtils.getLineStart(doc, offset);
        int anchor = offset - (prefix == null ? 0 : prefix.length());
        if (anchor == lineStart) {
            //commands code completion
            return commands(prefix, anchor, false);
        }
        final TokenSequence<DockerfileTokenId> seq = TokenHierarchy.get(doc).tokenSequence(DockerfileTokenId.language());
        if (seq == null) {
            return CodeCompletionResult.NONE;
        }
        seq.move(Math.max(0,offset-1));
        if (!seq.moveNext() && !seq.movePrevious()) {
            return CodeCompletionResult.NONE;
        }
        final Token<DockerfileTokenId> current = seq.token();
        if (current != null && current.id() != DockerfileTokenId.WHITESPACE) {
            anchor = seq.offset();
            prefix = current.text().toString().substring(0,offset-anchor);
            seq.movePrevious();
        } else {
            anchor = offset;
            prefix = "";    //NOI18N
        }
        Token<DockerfileTokenId> prev;
        while ((prev = seq.token()) != null && prev.id() == DockerfileTokenId.WHITESPACE) {
            if (!seq.movePrevious()) {
                break;
            }
        }
        if (prev != null  &&
                prev.id() == DockerfileTokenId.ONBUILD &&
                LineDocumentUtils.getLineStart(doc,seq.offset()) ==  LineDocumentUtils.getLineStart(doc,anchor)) {
            //Commands after onbuild
            return commands(prefix, anchor, true);
        }
        return CodeCompletionResult.NONE;
    } finally {
        doc.readUnlock();
    }
}
 
Example 19
Source File: IntroduceSuggestion.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Get an offset after a use trait statement.
 * <b>NOTE:</b>This method should be used when a type doesn't have
 * constants. If the use trait statement is after fields or methods, the
 * offset after the open curry for type is returned.
 *
 * @param document the document
 * @param typeScope the type scope
 * @return The offset after the last use trait statement if traits are used,
 * otherwise the offset after the open curly for the type
 */
private static int getOffsetAfterUseTrait(BaseDocument document, TypeScope typeScope) {
    OffsetRange blockRange = typeScope.getBlockRange();
    int offset = blockRange.getEnd() - 1; // before close curly "}"
    Collection<ModelElement> elements = new HashSet<>();
    elements.addAll(typeScope.getDeclaredMethods());
    if (typeScope instanceof ClassScope) {
        elements.addAll(((ClassScope) typeScope).getDeclaredFields());
    } else if (typeScope instanceof TraitScope) {
        elements.addAll(((TraitScope) typeScope).getDeclaredFields());
    }
    for (ModelElement element : elements) {
        int newOffset = element.getOffset();
        if (newOffset < offset) {
            offset = newOffset;
        }
    }

    document.readLock();
    try {
        TokenSequence<? extends PHPTokenId> ts = LexUtilities.getPHPTokenSequence(document, offset);
        if (ts != null) {
            ts.move(offset);
            if (ts.movePrevious()) {
                // find the following cases : "use TraitA;", "use TraitA{}" and "TypeName {"
                List<PHPTokenId> lookfor = Arrays.asList(
                        PHPTokenId.PHP_SEMICOLON,
                        PHPTokenId.PHP_CURLY_CLOSE,
                        PHPTokenId.PHP_CURLY_OPEN
                );
                Token<? extends PHPTokenId> previousToken = LexUtilities.findPreviousToken(ts, lookfor);
                if (previousToken != null) {
                    return ts.offset() + previousToken.length();
                }
            }
        }
    } finally {
        document.readUnlock();
    }
    return offset;
}
 
Example 20
Source File: WhereUsedElement.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static WhereUsedElement create(FileObject fileObject, String name, OffsetRange range, ElementKind kind) {
    Icon icon = UiUtils.getElementIcon(kind, Collections.<Modifier>emptyList());

    int start = range.getStart();
    int end = range.getEnd();

    int sta = start;
    int en = start; // ! Same line as start
    String content = null;

    BaseDocument bdoc = GsfUtilities.getDocument(fileObject, true);
    StringBuilder displayText = new StringBuilder();
    try {
        bdoc.readLock();

        // I should be able to just call tree.getInfo().getText() to get cached
        // copy - but since I'm playing fast and loose with compilationinfos
        // for for example find subclasses (using a singly dummy FileInfo) I need
        // to read it here instead
        content = bdoc.getText(0, bdoc.getLength());
        sta = Utilities.getRowFirstNonWhite(bdoc, start);

        if (sta == -1) {
            sta = Utilities.getRowStart(bdoc, start);
        }

        en = Utilities.getRowLastNonWhite(bdoc, start);

        if (en == -1) {
            en = Utilities.getRowEnd(bdoc, start);
        } else {
            // Last nonwhite - left side of the last char, not inclusive
            en++;
        }

        // Sometimes the node we get from the AST is for the whole block
        // (e.g. such as the whole class), not the argument node. This happens
        // for example in Find Subclasses out of the index. In this case
        if (end > en) {
            end = start + name.length();

            if (end > bdoc.getLength()) {
                end = bdoc.getLength();
            }
        }
    } catch (Exception ex) {
        content = "n/a"; //NOI18N
        Exceptions.printStackTrace(ex);
    } finally {
        bdoc.readUnlock();
    }

    if (end < sta) {
        // XXX Shouldn't happen, but I still have AST offset errors
        sta = end;
    }
    if (start < sta) {
        // XXX Shouldn't happen, but I still have AST offset errors
        start = sta;
    }
    if (en < end) {
        // XXX Shouldn't happen, but I still have AST offset errors
        en = end;
    }
    
    displayText.append(encodeCharRefs(content.subSequence(sta, start).toString()));
    displayText.append("<b>"); // NOI18N
    displayText.append(content.subSequence(start, end));
    displayText.append("</b>"); // NOI18N
    displayText.append(encodeCharRefs(content.subSequence(end, en).toString()));
  
    CloneableEditorSupport ces = GsfUtilities.findCloneableEditorSupport(fileObject);
    PositionRef ref1 = ces.createPositionRef(start, Bias.Forward);
    PositionRef ref2 = ces.createPositionRef(end, Bias.Forward);
    PositionBounds bounds = new PositionBounds(ref1, ref2);

    return new WhereUsedElement(bounds, displayText.toString().trim(),
            fileObject, name, new OffsetRange(start, end), icon);
}