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

The following examples show how to use org.netbeans.editor.BaseDocument#runAtomic() . 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: 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 2
Source File: ToggleBlockCommentAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    final AtomicBoolean processedHere = new AtomicBoolean(false);
    if (target != null) {
        if (!target.isEditable() || !target.isEnabled() || !(target.getDocument() instanceof BaseDocument)) {
            target.getToolkit().beep();
            return;
        }
        final Positions positions = Positions.create(target);
        final BaseDocument doc = (BaseDocument) target.getDocument();
        doc.runAtomic(new Runnable() {

            @Override
            public void run() {
                performCustomAction(doc, positions, processedHere);
            }
        });
        if (!processedHere.get()) {
            performDefaultAction(evt, target);
        }
    }
}
 
Example 3
Source File: TwigDeletedTextInterceptor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public boolean beforeRemove(Context context) throws BadLocationException {
    if (isTwig) {
        char ch = context.getText().charAt(0);
        if (TypingHooksUtils.isOpeningDelimiterChar(ch)) {
            BaseDocument doc = (BaseDocument) context.getDocument();
            final AtomicBoolean removed = new AtomicBoolean();
            final AtomicReference<BadLocationException> ble = new AtomicReference<>();
            doc.runAtomic(() -> {
                BeforeRemover remover = BeforeRemoverFactory.create(ch);
                try {
                    removed.set(remover.beforeRemove(context));
                } catch (BadLocationException ex) {
                    ble.set(ex);
                }
            });
            if (ble.get() != null) {
                throw ble.get();
            }
            // if true, the further processing will be stopped
            return removed.get();
        }
    }
    return false;
}
 
Example 4
Source File: TplCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void reindent(JTextComponent component) {

        final BaseDocument doc = (BaseDocument) component.getDocument();
        final int dotPos = component.getCaretPosition();
        final Indent indent = Indent.get(doc);
        indent.lock();
        try {
            doc.runAtomic(new Runnable() {

                public void run() {
                    try {
                        int startOffset = Utilities.getRowStart(doc, dotPos);
                        int endOffset = Utilities.getRowEnd(doc, dotPos);
                        indent.reindent(startOffset, endOffset);
                    } catch (BadLocationException ex) {
                        //ignore
                        }
                }
            });
        } finally {
            indent.unlock();
        }

    }
 
Example 5
Source File: ToggleBlockCommentAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    final AtomicBoolean processedHere = new AtomicBoolean(false);
    if (target != null) {
        if (!target.isEditable() || !target.isEnabled() || !(target.getDocument() instanceof BaseDocument)) {
            target.getToolkit().beep();
            return;
        }
        final int caretOffset = Utilities.isSelectionShowing(target) ? target.getSelectionStart() : target.getCaretPosition();
        final BaseDocument doc = (BaseDocument) target.getDocument();
        doc.runAtomic(new Runnable() {

            @Override
            public void run() {
                performCustomAction(doc, caretOffset, processedHere);
            }
        });
        if (!processedHere.get()) {
            performDefaultAction(evt, target);
        }
    }
}
 
Example 6
Source File: FSCompletion.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void doSubstitute(final JTextComponent component, String toAdd, final int backOffset) {
    final BaseDocument doc = (BaseDocument) component.getDocument();
    final int caretOffset = component.getCaretPosition();
    final String value = getText() + (toAdd != null && (!toAdd.equals("/") || (toAdd.equals("/") && !getText().endsWith(toAdd))) ? toAdd : ""); //NOI18N
    // Update the text
    doc.runAtomic(new Runnable() {
        @Override
        public void run() {
            try {
                String pfx = doc.getText(anchor, caretOffset - anchor);
                doc.remove(caretOffset - pfx.length(), pfx.length());
                doc.insertString(caretOffset - pfx.length(), value, null);
                component.setCaretPosition(component.getCaretPosition() - backOffset);
            } catch (BadLocationException e) {
                Exceptions.printStackTrace(e);
            }
        }
    });
}
 
Example 7
Source File: JspCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void defaultAction(JTextComponent component) {
    super.defaultAction(component);

    if (component == null) {
        return;
    }

    //handle auto tag imports
    final BaseDocument doc = (BaseDocument) component.getDocument();
    doc.runAtomic(new Runnable() {

        public void run() {
            String mimeType = NbEditorUtilities.getFileObject(doc).getMIMEType();
            Lookup mimeLookup = MimeLookup.getLookup(MimePath.get(mimeType));
            Collection<? extends AutoTagImporterProvider> providers = mimeLookup.lookup(new Lookup.Template<AutoTagImporterProvider>(AutoTagImporterProvider.class)).allInstances();
            if (providers != null) {
                for (AutoTagImporterProvider provider : providers) {
                    provider.importLibrary(doc, tagInfo.getTagLibrary().getPrefixString(), tagInfo.getTagLibrary().getURI());
                }
            }
        }
    });

}
 
Example 8
Source File: JspCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void defaultAction(JTextComponent component) {
    super.defaultAction(component);
    final BaseDocument doc = (BaseDocument) component.getDocument();

    doc.runAtomic(new Runnable() {

        @Override
        public void run() {
            try {
                doc.insertString(Util.findPositionForJspDirective(doc),
                        "<%@ taglib prefix=\"" //NOI18N
                        + tagLibPrefix + "\" uri=\"" //NOI18N
                        + tagLibURI + "\" %>\n", null);     //NOI18N

            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });
}
 
Example 9
Source File: JspCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void reindent(JTextComponent component) {

        final BaseDocument doc = (BaseDocument) component.getDocument();
        final int dotPos = component.getCaretPosition();
        final Indent indent = Indent.get(doc);
        indent.lock();
        try {
            doc.runAtomic(new Runnable() {

                public void run() {
                    try {
                        int startOffset = Utilities.getRowStart(doc, dotPos);
                        int endOffset = Utilities.getRowEnd(doc, dotPos);
                        indent.reindent(startOffset, endOffset);
                    } catch (BadLocationException ex) {
                        //ignore
                        }
                }
            });
        } finally {
            indent.unlock();
        }

    }
 
Example 10
Source File: LoremIpsumGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static void insertLoremIpsumText(final BaseDocument document, final List<String> paragraphs, final String tag, final int offset) {
    final Reformat reformat = Reformat.get(document);
    reformat.lock();
    try {
        document.runAtomic(new Runnable() {

            @Override
            public void run() {
                try {
                    StringBuilder litext = getLoremIpsumText(paragraphs, tag);
                    if(!Utilities.isRowWhite(document, offset)) {
                        //generate the li text at a new line if the current one is not empty
                        litext.insert(0, '\n');
                    }
                    document.insertString(offset, litext.toString(), null);
                    reformat.reformat(offset, offset + litext.length());
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        });
    } finally {
        reformat.unlock();
    }
}
 
Example 11
Source File: JavaFormatterUnitTestCase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Perform reformatting of the whole document's text.
 */
protected void reformat() {
    final BaseDocument doc = getDocument();
    final Reformat formatter = Reformat.get(getDocument());
    formatter.lock();
    try {
        doc.runAtomic (new Runnable () {
            public void run () {
                try {
                    formatter.reformat(0, doc.getLength());
                } catch (BadLocationException e) {
                    e.printStackTrace(getLog());
                    fail(e.getMessage());
                }
            }
        });
    } finally {
        formatter.unlock();
    }
}
 
Example 12
Source File: SpringXMLConfigCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void substituteText(JTextComponent c, final int offset, final int len, String toAdd) {
    final BaseDocument doc = (BaseDocument) c.getDocument();
    CharSequence prefix = getSubstitutionText();
    String text = prefix.toString();
    if(toAdd != null) {
        text += toAdd;
    }
    final String finalText = text;
    doc.runAtomic(new Runnable() {

        @Override
        public void run() {
            try {
                Position position = doc.createPosition(offset);
                doc.remove(offset, len);
                doc.insertString(position.getOffset(), finalText.toString(), null);
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });
}
 
Example 13
Source File: SpringXMLConfigCompletionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
void updateSchemaLocation(Document doc, final int offset, final String namespace, final String schemaLocation) {
        BaseDocument baseDoc = (BaseDocument) doc;
        final XMLSyntaxSupport syntaxSupport = XMLSyntaxSupport.getSyntaxSupport(doc);

        baseDoc.runAtomic(new Runnable() {

            @Override
            public void run() {
                try {
                    SyntaxElement element = syntaxSupport.getElementChain(offset);
                    if (element.getType() == Node.ELEMENT_NODE &&
                        ((TagElement)element).isStart()) {
                        NamedNodeMap nnm = element.getNode().getAttributes();
                        Attr attr = (Attr)nnm.getNamedItem("xsi:schemaLocation");    //NOI18N
                        if (attr != null) {
                            String val = attr.getValue();
                            if (!val.contains(namespace)) {
                                attr.setValue(val + "\n       " + namespace + " " + schemaLocation);    //NOI18N
                            }
                        }
                    }
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        });
}
 
Example 14
Source File: HtmlPaletteUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void insert(final String s, final JTextComponent target, final boolean reformat)
        throws BadLocationException {
    final Document _doc = target.getDocument();
    if (_doc == null || !(_doc instanceof BaseDocument)) {
        return;
    }

    BaseDocument doc = (BaseDocument) _doc;
    final Reformat reformatter = Reformat.get(doc);
    reformatter.lock();
    try {
        doc.runAtomic(new Runnable() {

            public void run() {
                try {
                    String s2 = s == null ? "" : s;
                    int start = insert(s2, target, _doc);
                    if (reformat && start >= 0 && _doc instanceof BaseDocument) {
                        // format the inserted text
                        int end = start + s2.length();
                        reformatter.reformat(start, end);
                    }
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        });

    } finally {
        reformatter.unlock();
    }

}
 
Example 15
Source File: XMLFormatUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void reformat(final BaseDocument doc, final int startOffset, final int endOffset) {
    final XMLLexerFormatter formatter = new XMLLexerFormatter(null);
    doc.runAtomic(new Runnable() {
        public void run() {
            formatter.doReformat(doc, startOffset, endOffset);
        }
    });
}
 
Example 16
Source File: XMLLexerFormatter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void reformat(Context context, final int startOffset, final int endOffset)
        throws BadLocationException {
    final BaseDocument doc = (BaseDocument) context.document();
    doc.runAtomic(new Runnable() {

        public void run() {
            doReformat(doc, startOffset, endOffset);
        }
    });
}
 
Example 17
Source File: AbstractCamelCasePosition.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public final void actionPerformed(ActionEvent evt, final JTextComponent target) {
    if (target != null) {
        if (originalAction != null && !isUsingCamelCase()) {
            if (originalAction instanceof BaseAction) {
                ((BaseAction) originalAction).actionPerformed(evt, target);
            } else {
                originalAction.actionPerformed(evt);
            }
        } else {
            final BaseDocument bdoc = org.netbeans.editor.Utilities.getDocument(target);
            if (bdoc != null) {
                bdoc.runAtomic(new Runnable() {
                    public void run() {
                        DocumentUtilities.setTypingModification(bdoc, true);
                        try {
                            int offset = newOffset(target);
                            if (offset != -1) {
                                moveToNewOffset(target, offset);
                            }
                        } catch (BadLocationException ble) {
                            target.getToolkit().beep();
                        } finally {
                            DocumentUtilities.setTypingModification(bdoc, false);
                        }
                    }
                });
            } else {
                target.getToolkit().beep();
            }
        }
    }
}
 
Example 18
Source File: TagBasedLexerFormatter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void enterPressed(Context context) {
    BaseDocument doc = (BaseDocument)context.document();   
    doc.runAtomic(new EnterPressedTask(context));
}
 
Example 19
Source File: GsfCompletionItem.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected void substituteText(JTextComponent c, final int offset, final int len, String toAdd) {
    final BaseDocument doc = (BaseDocument)c.getDocument();
    final String text = getInsertPrefix().toString();
    if (text != null) {
        //int semiPos = toAdd != null && toAdd.endsWith(";") ? findPositionForSemicolon(c) : -2; //NOI18N
        //if (semiPos > -2)
        //    toAdd = toAdd.length() > 1 ? toAdd.substring(0, toAdd.length() - 1) : null;
        //if (toAdd != null && !toAdd.equals("\n")) {//NOI18N
        //    TokenSequence<JavaTokenId> sequence = Utilities.getJavaTokenSequence(c, offset + len);
        //    if (sequence == null) {
        //        text += toAdd;
        //        toAdd = null;
        //    }
        //    boolean added = false;
        //    while(toAdd != null && toAdd.length() > 0) {
        //        String tokenText = sequence.token().text().toString();
        //        if (tokenText.startsWith(toAdd)) {
        //            len = sequence.offset() - offset + toAdd.length();
        //            text += toAdd;
        //            toAdd = null;
        //        } else if (toAdd.startsWith(tokenText)) {
        //            sequence.moveNext();
        //            len = sequence.offset() - offset;
        //            text += toAdd.substring(0, tokenText.length());
        //            toAdd = toAdd.substring(tokenText.length());
        //            added = true;
        //        } else if (sequence.token().id() == JavaTokenId.WHITESPACE && sequence.token().text().toString().indexOf('\n') < 0) {//NOI18N
        //            if (!sequence.moveNext()) {
        //                text += toAdd;
        //                toAdd = null;
        //            }
        //        } else {
        //            if (!added)
        //                text += toAdd;
        //            toAdd = null;
        //        }
        //    }
        //}

        //  Update the text
        doc.runAtomic(new Runnable() {
            public void run() {
                try {
                    int semiPos = -2;
                    String textToReplace = doc.getText(offset, len);
                    if (text.equals(textToReplace)) {
                        if (semiPos > -1) {
                            doc.insertString(semiPos, ";", null); //NOI18N
                        }
                        return;
                    }
                    int common = 0;
                    while (text.regionMatches(0, textToReplace, 0, ++common));
                    common--;
                    Position position = doc.createPosition(offset + common);
                    Position semiPosition = semiPos > -1 ? doc.createPosition(semiPos) : null;
                    doc.remove(offset + common, len - common);
                    doc.insertString(position.getOffset(), text.substring(common), null);
                    if (semiPosition != null) {
                        doc.insertString(semiPosition.getOffset(), ";", null);
                    }
                } catch (BadLocationException e) {
                    // Can't update
                }
            }
        });
    }
}
 
Example 20
Source File: TagBasedLexerFormatter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public boolean isJustAfterClosingTag(BaseDocument doc, int pos) {
    IsJustAfterClosingTagTask task = new IsJustAfterClosingTagTask(doc, pos);
    doc.runAtomic(task);
    return task.getResult();
}