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

The following examples show how to use org.netbeans.editor.BaseDocument#runAtomicAsUser() . 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: ClassnameCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void defaultAction(JTextComponent component) {
    final BaseDocument doc = (BaseDocument) component.getDocument();
    doc.runAtomicAsUser(new Runnable() {

        @Override
        public void run() {
            try {
                doc.remove(caret, correction);
                doc.insertString(caret, text, null);
            } catch (BadLocationException ex) {
                // shouldn't happen
            }
        }
    });
    //This statement will close the code completion box:
    Completion.get().hideAll();

}
 
Example 2
Source File: KeywordCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void defaultAction(JTextComponent component) {
    final BaseDocument doc = (BaseDocument) component.getDocument();
    doc.runAtomicAsUser(new Runnable() {

        @Override
        public void run() {
            try {
                if (caret > doc.getLength()) {
                    doc.insertString(caret - 1, text.substring(correction), null);
                } else {
                    doc.insertString(caret, text.substring(correction), null);
                }
            } catch (BadLocationException ex) {
                // shouldn't happen
            }
        }
    });
    //This statement will close the code completion box:
    Completion.get().hideAll();

}
 
Example 3
Source File: InsertSemicolonAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    if (!target.isEditable() || !target.isEnabled()) {
        target.getToolkit().beep();
        return;
    }
    final BaseDocument doc = (BaseDocument) target.getDocument();
    final Indent indenter = Indent.get(doc);
    final class R implements Runnable {
        public @Override void run() {
            try {
                Caret caret = target.getCaret();
                int dotpos = caret.getDot();
                int eoloffset = Utilities.getRowEnd(target, dotpos);
                doc.insertString(eoloffset, "" + what, null); //NOI18N
                if (withNewline) {
                    //This is code from the editor module, but it is
                    //a pretty strange way to do this:
                    doc.insertString(dotpos, "-", null); //NOI18N
                    doc.remove(dotpos, 1);
                    int eolDot = Utilities.getRowEnd(target, caret.getDot());
                    int newDotPos = indenter.indentNewLine(eolDot);
                    caret.setDot(newDotPos);
                }
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    indenter.lock();
    try {
        doc.runAtomicAsUser(new R());
    } finally {
        indenter.unlock();
    }
}
 
Example 4
Source File: InsertSemicolonAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    if (target.isEditable() && target.isEnabled()) {
        final BaseDocument doc = (BaseDocument) target.getDocument();
        final Indent indenter = Indent.get(doc);
        final class R implements Runnable {

            @Override
            public void run() {
                try {
                    Caret caret = target.getCaret();
                    int caretPosition = caret.getDot();
                    int eolOffset = Utilities.getRowEnd(target, caretPosition);
                    doc.insertString(eolOffset, SEMICOLON, null);
                    newLineProcessor.processNewLine(eolOffset, caret, indenter);
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
        indenter.lock();
        try {
            doc.runAtomicAsUser(new R());
        } finally {
            indenter.unlock();
        }
    }
}
 
Example 5
Source File: PhpTypedTextInterceptor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void afterInsert(final Context context) throws BadLocationException {
    final BaseDocument doc = (BaseDocument) context.getDocument();
    doc.runAtomicAsUser(new Runnable() {

        @Override
        public void run() {
            try {
                afterInsertUnderWriteLock(context);
            } catch (BadLocationException ex) {
                LOGGER.log(Level.FINE, null, ex);
            }
        }
    });
}
 
Example 6
Source File: InsertSemicolonAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    if (target.isEditable() && target.isEnabled()) {
        final BaseDocument doc = (BaseDocument) target.getDocument();
        final Indent indenter = Indent.get(doc);
        final class R implements Runnable {

            @Override
            public void run() {
                try {
                    Caret caret = target.getCaret();
                    int caretPosition = caret.getDot();
                    int eolOffset = LineDocumentUtils.getLineEnd(doc, caretPosition);
                    doc.insertString(eolOffset, SEMICOLON, null);
                    newLineProcessor.processNewLine(eolOffset, caret, indenter);
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
        indenter.lock();
        try {
            doc.runAtomicAsUser(new R());
        } finally {
            indenter.unlock();
        }
    }
}
 
Example 7
Source File: TwigTypedTextInterceptor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void afterInsert(Context context) throws BadLocationException {
    if (!isTwig) {
        return;
    }
    BaseDocument doc = (BaseDocument) context.getDocument();
    doc.runAtomicAsUser(() -> {
        try {
            afterInsertUnderWriteLock(context);
        } catch (BadLocationException ex) {
            LOGGER.log(Level.FINE, null, ex);
        }
    });
}
 
Example 8
Source File: CreateRulePanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Changes the class and id attributes of the active html source element.
 */
private void modifySourceElement() throws DataObjectNotFoundException, IOException {
    final BaseDocument doc = (BaseDocument) getDocument(activeElement.getFile());
    final AtomicBoolean success = new AtomicBoolean();

    DataObject dataObject = DataObject.find(activeElement.getFile());
    boolean modified = dataObject.getLookup().lookup(SaveCookie.class) != null;

    pos = Integer.MAX_VALUE;
    diff = -1;
    doc.runAtomicAsUser(new Runnable() {
        @Override
        public void run() {
            try {
                if (selectedClazz != null) {
                    updateAttribute(doc, getSelectedElementClass(), selectedClazz.getItemName(), "class");
                }
                if (selectedId != null) {
                    updateAttribute(doc, getSelectedElementId(), selectedId.getItemName(), "id");
                }

                success.set(true); //better not to do the save from within the atomic modification task
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });

    //possibly save the document if not opened in editor
    if (success.get()) {
        if (!modified) { //wasn't modified before applying the changes, save...
            SaveCookie saveCookie = dataObject.getLookup().lookup(SaveCookie.class);
            if (saveCookie != null) { //the "changes" may not modify the document
                saveCookie.save();
            }
        }
    }
}
 
Example 9
Source File: SQLCompletionEnv.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void substituteText(JTextComponent component, final int offset, final String text) {
    final int caretOffset = component.getSelectionEnd();
    final BaseDocument baseDoc = (BaseDocument) component.getDocument();
    baseDoc.runAtomicAsUser(new Runnable() {
        public void run() {
            int documentOffset = statementOffset + offset;
            try {
                baseDoc.remove(documentOffset, caretOffset - documentOffset);
                baseDoc.insertString(documentOffset, text, null);
            } catch (BadLocationException ex) {
                // No can do, document may have changed.
            }
        }
    });
}
 
Example 10
Source File: AddAttributeToSourceFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void implement() throws Exception {
    final StringBuilder insertText = new StringBuilder();
    insertText.append(' '); //NOI18N
    Iterator<Attribute> i = attrs.iterator();
    while(i.hasNext()) {
        Attribute a = i.next();
        insertText.append(a.getName());
        insertText.append("=\"\""); //NOI18N
        if(i.hasNext()) {
            insertText.append(' '); //NOI18N
        }
    }
    final BaseDocument document = (BaseDocument)snapshot.getSource().getDocument(true);
    document.runAtomicAsUser(new Runnable() {

        @Override
        public void run() {
            try {
                int insertOffset = openTag.from() + "<".length() + openTag.name().length();
                int documentInsertOffset = snapshot.getOriginalOffset(insertOffset);
                document.insertString(documentInsertOffset, insertText.toString(), null);
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
        
    });
    
    LexerUtils.rebuildTokenHierarchy(document);
}
 
Example 11
Source File: JspSourceTask.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void run(JspParserResult result, SchedulerEvent event) {
    if(cancelled) {
        cancelled = false;
        return ;
    }

    final Collection<JspSyntaxElement.Attribute> whereToCreateTheEmbeddings = new LinkedList<JspSyntaxElement.Attribute>();
    List<JspSyntaxElement> elements = result.elements();
    for(JspSyntaxElement e : elements) {
        Map<String, Set<String>> embs = EMBEDDINGS.get(e.kind());
        if(embs != null) {
            JspSyntaxElement.AttributedTagLikeElement element = (JspSyntaxElement.AttributedTagLikeElement)e;
            String elementName = element.name();
            Set<String> attrs = embs.get(elementName);
            if(attrs != null) {
                for(JspSyntaxElement.Attribute a : element.attributes()) {
                    if(attrs.contains(a.getName())) {
                        //create the embedding
                        whereToCreateTheEmbeddings.add(a);
                    }
                }
            }
        }
    }


    //create the embeddings
    final BaseDocument doc = (BaseDocument)result.getSnapshot().getSource().getDocument(false);
    if(doc != null) {
        doc.runAtomicAsUser(new Runnable() {

            @Override
            public void run() {

                //having the task cancel check inside the render task
                //should ensure that the offsets from the parser result
                //will never become unsynchronized with the document offset.
                //once the document is modified, this task if running is cancelled
                //and new parsing-task loop runs. Inside the render task the
                //document cannot be modified.
                if (cancelled) {
                    cancelled = false;
                    return;
                }

                TokenHierarchy<BaseDocument> th = TokenHierarchy.get(doc);
                TokenSequence<JspTokenId> ts = th.tokenSequence(JspTokenId.language());
                if(ts == null) {
                    return ;
                }
                for(JspSyntaxElement.Attribute attr : whereToCreateTheEmbeddings) {
                    int diff = ts.move(attr.getValueOffset());
                    if(diff == 0) {
                        if(ts.moveNext()) {
                            Token<JspTokenId> t = ts.token();
                            if(t.id() == JspTokenId.ATTR_VALUE) {
                                //create the embedding
                                ts.createEmbedding(JavaTokenId.language(), 1, 1);
                            }
                        }
                    }
                }

            }

        });
    }
}
 
Example 12
Source File: HtmlTypedTextInterceptor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static boolean changeQuotesType(final Context context) {
    if (!HtmlPreferences.autocompleteQuotesAfterEqualSign()) {
        return false;
    }
    final AtomicBoolean result = new AtomicBoolean();
    final BaseDocument doc = (BaseDocument) context.getDocument();
    doc.runAtomicAsUser(new Runnable() {

        @Override
        public void run() {
            int dotPos = context.getOffset();
            char expected = context.getText().charAt(0);
            TokenSequence<HTMLTokenId> ts = LexUtilities.getTokenSequence(doc, dotPos, HTMLTokenId.language());
            if (ts == null) {
                return; //no html ts at the caret position
            }
            ts.move(dotPos);
            if (!ts.moveNext()) {
                return; //no token
            }

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

            int dotPosBeforeTypedChar = dotPos - 1;
            String text = token.text().toString();

            String pattern = expected == '\'' ? "\"\"" : "''";
            if (text.contentEquals(pattern)) { // NOI18N
                try {
                    doc.remove(dotPosBeforeTypedChar, 2); //remove the existing quote pair
                    doc.insertString(dotPosBeforeTypedChar, new StringBuilder().append(expected).append(expected).toString(), null); //add new pair
                    context.getComponent().setCaretPosition(dotPosBeforeTypedChar + 1); //set caret between the quotes
                    result.set(true); //mark we've already handled the key event
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }

            //remember that user changed the default type so next time we'll autocomplete the wanted one
            if (adjust_quote_type_after_eq) {
                default_quote_char_after_eq = expected;
            }
        }

    });
    return result.get();
}