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

The following examples show how to use org.netbeans.editor.BaseDocument#getProperty() . 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: LexUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static TokenSequence<?extends PHPTokenId> getPositionedSequence(BaseDocument doc, int offset) {
    TokenSequence<?extends PHPTokenId> ts = getPHPTokenSequence(doc, offset);

    if (ts != null) {
        try {
            ts.move(offset);
        } catch (AssertionError e) {
            DataObject dobj = (DataObject) doc.getProperty(Document.StreamDescriptionProperty);

            if (dobj != null) {
                Exceptions.attachMessage(e, FileUtil.getFileDisplayName(dobj.getPrimaryFile()));
            }

            throw e;
        }

        if (!ts.moveNext() && !ts.movePrevious()) {
            return null;
        }

        return ts;
    }

    return null;
}
 
Example 2
Source File: ToolTipUI.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    EditorUI eui = Utilities.getEditorUI(editorPane);
    Point location = et.getLocation();
    location = eui.getStickyWindowSupport().convertPoint(location);
    eui.getToolTipSupport().setToolTipVisible(false);
    DebuggerManager dbMgr = DebuggerManager.getDebuggerManager();
    BaseDocument document = Utilities.getDocument(editorPane);
    DataObject dobj = (DataObject) document.getProperty(Document.StreamDescriptionProperty);
    FileObject fo = dobj.getPrimaryFile();
    Watch.Pin pin = new EditorPin(fo, pinnable.line, location);
    final Watch w = dbMgr.createPinnedWatch(pinnable.expression, pin);
    SwingUtilities.invokeLater(() -> {
        try {
            PinWatchUISupport.getDefault().pin(w, pinnable.valueProviderId);
        } catch (IllegalArgumentException ex) {
            Exceptions.printStackTrace(ex);
        }
    });
}
 
Example 3
Source File: InstantRefactoringPerformer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private UndoableEditDelegate(UndoableEdit ed, BaseDocument doc, InstantRefactoringPerformer performer) {
    DataObject dob = (DataObject) doc.getProperty(BaseDocument.StreamDescriptionProperty);
    this.ces = dob.getLookup().lookup(CloneableEditorSupport.class);
    this.inner = new CompoundEdit();
    this.inner.addEdit(ed);
    this.delegate = ed;
    this.performer = performer;
}
 
Example 4
Source File: FormatContext.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Integer getSuggestedIndentation(int offset) {
    BaseDocument doc = getDocument();
    Map<Integer, Integer> suggestedLineIndents = (Map<Integer, Integer>) doc.getProperty("AbstractIndenter.lineIndents");
    if (suggestedLineIndents != null) {
        try {
            int lineIndex = LineDocumentUtils.getLineIndex(doc, offset + offsetDiff);
            Integer indent = suggestedLineIndents.get(lineIndex);
            return indent != null ? indent : null;
        } catch (BadLocationException ex) {
            LOGGER.log(Level.INFO, null, ex);
        }
    }
    return null;
}
 
Example 5
Source File: LexUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static TokenSequence<GroovyTokenId> getPositionedSequence(BaseDocument doc, int offset, boolean lookBack) {
    TokenSequence<GroovyTokenId> ts = getGroovyTokenSequence(doc, offset);

    if (ts != null) {
        try {
            ts.move(offset);
        } catch (AssertionError e) {
            DataObject dobj = (DataObject) doc.getProperty(Document.StreamDescriptionProperty);

            if (dobj != null) {
                Exceptions.attachMessage(e, FileUtil.getFileDisplayName(dobj.getPrimaryFile()));
            }

            throw e;
        }

        if (!lookBack && !ts.moveNext()) {
            return null;
        } else if (lookBack && !ts.moveNext() && !ts.movePrevious()) {
            return null;
        }

        return ts;
    }

    return null;
}
 
Example 6
Source File: LexUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Token<GroovyTokenId> getToken(BaseDocument doc, int offset) {
    TokenSequence<GroovyTokenId> ts = getGroovyTokenSequence(doc, offset);

    if (ts != null) {
        try {
            ts.move(offset);
        } catch (AssertionError e) {
            DataObject dobj = (DataObject) doc.getProperty(Document.StreamDescriptionProperty);

            if (dobj != null) {
                Exceptions.attachMessage(e, FileUtil.getFileDisplayName(dobj.getPrimaryFile()));
            }

            throw e;
        }

        if (!ts.moveNext() && !ts.movePrevious()) {
            return null;
        }

        Token<GroovyTokenId> token = ts.token();

        return token;
    }

    return null;
}
 
Example 7
Source File: JspIndenterTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected BaseDocument getDocument(FileObject fo) {
    try {
        //this create an instance of JspKit which initializes the coloring data but lazily, not parsed yet here
        EditorCookie ec = DataLoadersBridge.getDefault().getCookie(fo, EditorCookie.class);
        BaseDocument bdoc = (BaseDocument) ec.openDocument();

        //force parse and wait
        TagLibParseSupport pc = (TagLibParseSupport) DataLoadersBridge.getDefault().getCookie(fo, TagLibParseCookie.class);
        pc.getCachedParseResult(false, false, true);
        //get the parser coloring data
        JspColoringData data = pc.getJSPColoringData();

        //set correct values to the document's input attributes
        InputAttributes inputAttributes = (InputAttributes) bdoc.getProperty(InputAttributes.class);
        JspParseData jspParseData = (JspParseData) inputAttributes.getValue(LanguagePath.get(JspTokenId.language()), JspParseData.class);
        jspParseData.updateParseData(data.getPrefixMapper(), data.isELIgnored(), data.isXMLSyntax());
        //mark as initialized
        jspParseData.initialized();

        //any token hierarchy taken from this document should see the correct lexing - based on parsing results
        return bdoc;
    } catch (IOException ex) {
        fail(ex.toString());
        return null;
    }
}
 
Example 8
Source File: BeforeSaveTasks.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static synchronized BeforeSaveTasks get(BaseDocument doc) {
    BeforeSaveTasks beforeSaveTasks = (BeforeSaveTasks) doc.getProperty(BeforeSaveTasks.class);
    if (beforeSaveTasks == null) {
        beforeSaveTasks = new BeforeSaveTasks(doc);
        doc.putProperty(BeforeSaveTasks.class, beforeSaveTasks);
    }
    return beforeSaveTasks;
}
 
Example 9
Source File: BeforeSaveTasks.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private BeforeSaveTasks(BaseDocument doc) {
    this.doc = doc;
    Runnable beforeSaveRunnable = (Runnable)
            doc.getProperty("beforeSaveRunnable"); // Name of prop in sync with CloneableEditorSupport NOI18N
    if (beforeSaveRunnable != null) {
        throw new IllegalStateException("\"beforeSaveRunnable\" property of document " + doc + // NOI18N
                " is already occupied by " + beforeSaveRunnable); // NOI18N
    }
    beforeSaveRunnable = new Runnable() {
        public @Override void run() {
            runTasks();
        }
    };
    doc.putProperty("beforeSaveRunnable", beforeSaveRunnable); // NOI18N
}
 
Example 10
Source File: BeforeSaveTasksTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testOnSaveTasks() {
    MockServices.setServices(MockMimeLookup.class);
    MockMimeLookup.setInstances(MimePath.parse(MIME_TYPE),
            new TestOnSaveTask1.TestFactory1(),
            new TestOnSaveTask2.TestFactory2()
    );
    BaseDocument doc = new BaseDocument(false, MIME_TYPE);
    BeforeSaveTasks.get(doc);
    Runnable beforeSaveRunnable = (Runnable) doc.getProperty("beforeSaveRunnable");
    beforeSaveRunnable.run();
    assertNotNull("TestOnSaveTask2 not created", TestOnSaveTask2.TestFactory2.lastCreatedTask);
    assertTrue("TestOnSaveTask2 not run", TestOnSaveTask2.TestFactory2.lastCreatedTask.taskPerformed);
}
 
Example 11
Source File: LexUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static <T extends TokenId>  TokenSequence<T> getPositionedSequence(BaseDocument doc, int offset, boolean lookBack, Language<T> language) {
    TokenSequence<T> ts = getTokenSequence(doc, offset, language);

    if (ts != null) {
        try {
            ts.move(offset);
        } catch (AssertionError e) {
            DataObject dobj = (DataObject)doc.getProperty(Document.StreamDescriptionProperty);

            if (dobj != null) {
                Exceptions.attachMessage(e, FileUtil.getFileDisplayName(dobj.getPrimaryFile()));
            }

            throw e;
        }

        if (!lookBack && !ts.moveNext()) {
            return null;
        } else if (lookBack && !ts.moveNext() && !ts.movePrevious()) {
            return null;
        }

        return ts;
    }

    return null;
}
 
Example 12
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 13
Source File: HighlightURLs.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static void ensureAttached(final BaseDocument doc) {
    if (doc.getProperty(REGISTERED_KEY) != null) {
        return;
    }

    final HighlightURLs h = new HighlightURLs(doc);
    
    doc.putProperty(REGISTERED_KEY, true);
    
    if (h.coloring == null) {
        LOG.log(Level.WARNING, "'url' coloring cannot be found");
        return;
    }

    doc.addDocumentListener(h);

    doc.render(new Runnable() {

        @Override
        public void run() {
            try {
                h.modifiedSpans.add(new Position[] {
                    doc.createPosition(0, Bias.Backward),
                    doc.createPosition(doc.getLength(), Bias.Forward)
                });
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });
    h.schedule();
}
 
Example 14
Source File: OpenTagCompletionProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Create CompletionModel from SpringBinaryIndexer.
 * @param context CompletionContext
 * @return list of created CompletionModel items
 */
@Override
public List<CompletionModel> getModels(CompletionContext context) {
    if (!context.getCompletionType().equals(CompletionContext.CompletionType.COMPLETION_TYPE_ELEMENT)) {
        return Collections.<CompletionModel>emptyList();
    }

    BaseDocument doc = context.getBaseDocument();
    String mime = (String) doc.getProperty(BaseDocument.MIME_TYPE_PROP);
    if (!SpringConstants.CONFIG_MIME_TYPE.equals(mime)) {
        return Collections.<CompletionModel>emptyList();
    }

    List<CompletionModel> models =  new ArrayList<CompletionModel>();
    FileObject primaryFile = context.getPrimaryFile();
    ClassPath cp = ClassPath.getClassPath(primaryFile, ClassPath.COMPILE);
    if (cp == null) {
        return Collections.<CompletionModel>emptyList();
    }
    FileObject resource = cp.findResource(SpringUtilities.SPRING_CLASS_NAME.replace('.', '/') + ".class"); //NOI18N
    if (resource != null) {
        FileObject ownerRoot = cp.findOwnerRoot(resource);
        String version = findVersion(ownerRoot);
        if (version == null) {
            LOGGER.log(Level.WARNING, "Unknown version of Spring jars: ownerRoot={0}", ownerRoot);
            return Collections.<CompletionModel>emptyList();
        }
        LOGGER.log(Level.FINE, "Spring jars version={0}", version); //NOI18N

        if (declaredNamespaces == null) {
            declaredNamespaces = context.getDeclaredNamespaces();
        }
        Map<String, FileObject> map = new SpringIndex(primaryFile).getAllSpringLibraryDescriptors();

        for (String namespace: map.keySet()) {
            if (!declaredNamespaces.containsValue(namespace)) {
                FileObject file = map.get(namespace);
                String fVersion = parseVersion(file);
                if (version.startsWith(fVersion)) {
                    ModelSource source = Utilities.getModelSource(file, true);
                    SchemaModel model = SchemaModelFactory.getDefault().getModel(source);
                    CompletionModel completionModel = new OpenTagCompletionModel(generatePrefix(namespace), model);
                    models.add(completionModel);
                }
            }
        }
        usedPrefixes.clear();
        return models;
    } else {
        return Collections.<CompletionModel>emptyList();
    }

}
 
Example 15
Source File: TransferData.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static TransferData readFromDocument(BaseDocument doc) {
    return (TransferData) doc.getProperty(TRANSFER_DATA_DOC_PROPERTY);
}
 
Example 16
Source File: TagBasedLexerFormatter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void enterPressed() throws BadLocationException{
    BaseDocument doc = (BaseDocument) context.document();
    
    if (isTopLevelLanguage(doc)) {
        doc.putProperty(TransferData.ORG_CARET_OFFSET_DOCPROPERTY, new Integer(context.caretOffset()));
    }

    Integer dotPos = (Integer) doc.getProperty(TransferData.ORG_CARET_OFFSET_DOCPROPERTY);
    //assert dotPos != null;
    if(dotPos == null) {
        dotPos = context.caretOffset();
    }
    
    int origDotPos = dotPos.intValue() - 1; // dotPos - "\n".length()
    
    if (indexWithinCurrentLanguage(doc, origDotPos - 1)) {
        if (isSmartEnter(doc, dotPos)) {
            handleSmartEnter(context);
        } else {
            int newIndent = 0;
            int lineNumber = Utilities.getLineOffset(doc, dotPos);
            boolean firstRow = false;
            
            if (Utilities.getRowStart(doc, origDotPos) == origDotPos){
                newIndent = getExistingIndent(doc, lineNumber);
                firstRow = true;
            } else if (lineNumber > 0){
                newIndent = getExistingIndent(doc, lineNumber - 1);
            }
            
            TokenHierarchy tokenHierarchy = TokenHierarchy.get(doc);
            TokenSequence[] tokenSequences = (TokenSequence[]) tokenHierarchy.tokenSequenceList(supportedLanguagePath(), 0, Integer.MAX_VALUE).toArray(new TokenSequence[0]);
            TextBounds[] tokenSequenceBounds = new TextBounds[tokenSequences.length];
            
            for (int i = 0; i < tokenSequenceBounds.length; i++) {
                tokenSequenceBounds[i] = findTokenSequenceBounds(doc, tokenSequences[i]);
            }

            JoinedTokenSequence tokenSequence = new JoinedTokenSequence(tokenSequences, tokenSequenceBounds);
            tokenSequence.moveStart(); tokenSequence.moveNext();

            int openingTagOffset = getTagEndingAtPosition(tokenSequence, origDotPos - 1);
            
            if (isOpeningTag(tokenSequence, openingTagOffset)){
                newIndent += doc.getShiftWidth();
            }

            context.modifyIndent(Utilities.getRowStart(doc, dotPos), newIndent);
            
            if (firstRow){
                context.setCaretOffset(context.caretOffset() - newIndent);
            }
        }
    }
}