Java Code Examples for javax.swing.text.Document

The following examples show how to use javax.swing.text.Document. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
private void append(String str) {
  Document doc = jtp.getDocument();
  String text;
  if (doc.getLength() > LIMIT) {
    timerStop();
    startButton.setEnabled(false);
    text = "doc.getLength()>1000";
  } else {
    text = str;
  }
  try {
    doc.insertString(doc.getLength(), text + LS, null);
    jtp.setCaretPosition(doc.getLength());
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example 2
Source Project: jeveassets   Source File: TextManager.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void installTextComponent(final JTextComponent component) {
	//Make sure this component does not already have a UndoManager
	Document document = component.getDocument();
	boolean found = false;
	if (document instanceof AbstractDocument) {
		AbstractDocument abstractDocument = (AbstractDocument) document;
		for (UndoableEditListener editListener : abstractDocument.getUndoableEditListeners()) {
			if (editListener.getClass().equals(CompoundUndoManager.class)) {
				CompoundUndoManager undoManager = (CompoundUndoManager) editListener;
				undoManager.reset();
				return;
			}
		}
	}
	if (!found) {
		new TextManager(component);
	}
}
 
Example 3
Source Project: netbeans   Source File: BreadcrumbsController.java    License: Apache License 2.0 6 votes vote down vote up
@Deprecated
public static void setBreadcrumbs(@NonNull Document doc, @NonNull final Node root, @NonNull final Node selected) {
    Parameters.notNull("doc", doc);
    Parameters.notNull("root", root);
    Parameters.notNull("selected", selected);
    
    final ExplorerManager manager = HolderImpl.get(doc).getManager();

    Children.MUTEX.writeAccess(new Action<Void>() {
        @Override public Void run() {
            manager.setRootContext(root);
            manager.setExploredContext(selected);
            return null;
        }
    });
}
 
Example 4
@Override
public void replaceRange(final String text, final int start,
                         final int end) {
    synchronized (getDelegateLock()) {
        // JTextArea.replaceRange() posts two different events.
        // Since we make no differences between text events,
        // the document listener has to be disabled while
        // JTextArea.replaceRange() is called.
        final Document document = getTextComponent().getDocument();
        document.removeDocumentListener(this);
        getDelegate().getView().replaceRange(text, start, end);
        revalidate();
        postEvent(new TextEvent(getTarget(), TextEvent.TEXT_VALUE_CHANGED));
        document.addDocumentListener(this);
    }
    repaintPeer();
}
 
Example 5
Source Project: netbeans   Source File: DiffResultsViewForLine.java    License: Apache License 2.0 6 votes vote down vote up
private Document getSourceDocument(StreamSource ss) {
    Document sdoc = null;
    FileObject fo = ss.getLookup().lookup(FileObject.class);
    if (fo != null) {
        try {
            DataObject dao = DataObject.find(fo);
            if (dao.getPrimaryFile() == fo) {
                EditorCookie ec = dao.getCookie(EditorCookie.class);
                if (ec != null) {
                    sdoc = ec.openDocument();
                }
            }
        } catch (Exception e) {
            // fallback to other means of obtaining the source
        }
    } else {
        sdoc = ss.getLookup().lookup(Document.class);
    }
    return sdoc;
}
 
Example 6
Source Project: netbeans   Source File: XmlTokenList.java    License: Apache License 2.0 6 votes vote down vote up
protected int[] findNextSpellSpan() throws BadLocationException {
    TokenHierarchy<Document> h = TokenHierarchy.get((Document) doc);
    TokenSequence<?> ts = h.tokenSequence();
    if (ts == null || hidden) {
        return new int[]{-1, -1};
    }

    ts.move(nextSearchOffset);

    while (ts.moveNext()) {
        TokenId id = ts.token().id();

        if (id == XMLTokenId.BLOCK_COMMENT || id == XMLTokenId.TEXT) {
            return new int[]{ts.offset(), ts.offset() + ts.token().length()};
        }
    }
    return new int[]{-1, -1};
}
 
Example 7
Source Project: netbeans   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
public static Document setDocumentContentTo(Document doc, InputStream in) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    StringBuffer sbuf = new StringBuffer();
    try {
        String line = null;
        while ((line = br.readLine()) != null) {
            sbuf.append(line);
            sbuf.append(System.getProperty("line.separator"));
        }
    } finally {
        br.close();
    }
    doc.remove(0, doc.getLength());
    doc.insertString(0,sbuf.toString(),null);
    return doc;
}
 
Example 8
Source Project: netbeans   Source File: YamlCompletion.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getPrefix(ParserResult info, int caretOffset, boolean upToOffset) {
    if (caretOffset > 0) {
        try {
            Document doc = ((YamlParserResult) info).getSnapshot().getSource().getDocument(false);
            if (doc != null) {
                return doc.getText(caretOffset - 1, 1);
            } else {
                return null;
            }
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    return null;
}
 
Example 9
Source Project: netbeans   Source File: JavadocCompletionQuery.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected boolean canFilter(JTextComponent component) {
    final int newOffset = component.getSelectionStart();
    final Document doc = component.getDocument();
    if (newOffset > caretOffset && items != null && !items.isEmpty()) {
        try {
            String prefix = doc.getText(caretOffset, newOffset - caretOffset);
            if (!isJavaIdentifierPart(prefix)) {
                Completion.get().hideDocumentation();
                Completion.get().hideCompletion();
            }
        } catch (BadLocationException ble) {
        }
    }
    return false;
}
 
Example 10
Source Project: netbeans   Source File: HintsControllerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private static void computeLineSpan(Document doc, int[] offsets) throws BadLocationException {
    String text = doc.getText(offsets[0], offsets[1] - offsets[0]);
    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--;
    
    offsets[1]  = offsets[0] + length;
    offsets[0] += column;
    
    if (offsets[1] < offsets[0]) {
        //may happen on lines without non-whitespace characters
        offsets[0] = offsets[1];
    }
}
 
Example 11
Source Project: netbeans   Source File: PlainDocumentTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testBehaviour() throws Exception {
    Document doc = new PlainDocument();
    doc.insertString(0, "test hello world", null);
    UndoManager undo = new UndoManager();
    doc.addUndoableEditListener(undo);
    Position pos = doc.createPosition(2);
    doc.remove(0, 3);
    assert (pos.getOffset() == 0);
    undo.undo();
    assert (pos.getOffset() == 2);
    
    Position pos2 = doc.createPosition(5);
    doc.remove(4, 2);
    Position pos3 = doc.createPosition(4);
    assertSame(pos2, pos3);
    undo.undo();
    assert (pos3.getOffset() == 5);
}
 
Example 12
Source Project: netbeans   Source File: Formatter.java    License: Apache License 2.0 6 votes vote down vote up
/** Should the typed tabs be expanded to the spaces? */
public boolean expandTabs() {
    Document doc = LegacyFormattersProvider.getFormattingContextDocument();
    if (doc != null) {
        Object ret = callIndentUtils("isExpandTabs", doc); //NOI18N
        if (ret instanceof Boolean) {
            return (Boolean) ret;
        }
    }

    if (!customExpandTabs && !inited) {
        prefsListener.preferenceChange(null);
    }

    return expandTabs;
}
 
Example 13
Source Project: netbeans   Source File: UndoableEditWrapperTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testWrapping() throws Exception {
        MimePath mimePath = MimePath.EMPTY;
        MockMimeLookup.setInstances(mimePath, new TestingUndoableEditWrapper(), new TestingUndoableEditWrapper2());
        CESEnv env = new CESEnv();
        Document doc = env.support.openDocument();
//        doc.addUndoableEditListener(new UndoableEditListener() {
//            @Override
//            public void undoableEditHappened(UndoableEditEvent e) {
//                UndoableEdit edit = e.getEdit();
//            }
//        });
        doc.insertString(0, "Test", null);
        Class wrapEditClass = TestingUndoableEditWrapper.WrapCompoundEdit.class;
        assertNotNull(NbDocument.getEditToBeUndoneOfType(env.support, wrapEditClass));
        Class wrapEditClass2 = TestingUndoableEditWrapper2.WrapCompoundEdit2.class;
        assertNotNull(NbDocument.getEditToBeUndoneOfType(env.support, wrapEditClass2));
        
        // A trick to get whole edit
        UndoableEdit wholeEdit = NbDocument.getEditToBeUndoneOfType(env.support, UndoableEdit.class);
        assertTrue(wholeEdit instanceof List);
        @SuppressWarnings("unchecked")
        List<? extends UndoableEdit> listEdit = (List<? extends UndoableEdit>) wholeEdit;
        assertEquals(3, listEdit.size());
        assertEquals(wrapEditClass, listEdit.get(1).getClass());
        assertEquals(wrapEditClass2, listEdit.get(2).getClass());
    }
 
Example 14
Source Project: netbeans   Source File: CamelCaseOperations.java    License: Apache License 2.0 6 votes vote down vote up
static int nextCamelCasePosition(JTextComponent textComponent) {
    int offset = textComponent.getCaretPosition();
    Document doc = textComponent.getDocument();

    // Are we at the end of the document?
    if (offset == doc.getLength()) {
        return -1;
    }

    KeystrokeHandler bc = UiUtils.getBracketCompletion(doc, offset);
    if (bc != null) {
        int nextOffset = bc.getNextWordOffset(doc, offset, false);
        if (nextOffset != -1) {
            return nextOffset;
        }
    }
    
    try {
        return Utilities.getNextWord(textComponent, offset);
    } catch (BadLocationException ble) {
        // something went wrong :(
        ErrorManager.getDefault().notify(ble);
    }
    return -1;
}
 
Example 15
@Override
public final void setText(final String text) {
    synchronized (getDelegateLock()) {
        // JTextArea.setText() posts two different events (remove & insert).
        // Since we make no differences between text events,
        // the document listener has to be disabled while
        // JTextArea.setText() is called.
        final Document document = getTextComponent().getDocument();
        document.removeDocumentListener(this);
        getTextComponent().setText(text);
        revalidate();
        if (firstChangeSkipped) {
            postEvent(new TextEvent(getTarget(),
                                    TextEvent.TEXT_VALUE_CHANGED));
        }
        document.addDocumentListener(this);
    }
    repaintPeer();
}
 
Example 16
Source Project: netbeans   Source File: TokenSequenceTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testSubSequenceInUnfinishedTH() throws Exception {
    Document doc = new ModificationTextDocument();
    //             012345678
    String text = "ab cd efg";
    doc.insertString(0, text, null);
    
    doc.putProperty(Language.class,TestTokenId.language());
    TokenHierarchy<?> hi = TokenHierarchy.get(doc);

    ((AbstractDocument)doc).readLock();
    try {
        TokenSequence<?> ts = hi.tokenSequence();
        assertTrue(ts.moveNext());

        ts = ts.subSequence(2, 6);
        assertTrue(ts.moveNext());
        LexerTestUtilities.assertTokenEquals(ts,TestTokenId.WHITESPACE, " ", 2);
        assertTrue(ts.moveNext());
        LexerTestUtilities.assertTokenEquals(ts,TestTokenId.IDENTIFIER, "cd", 3);
        assertTrue(ts.moveNext());
        LexerTestUtilities.assertTokenEquals(ts,TestTokenId.WHITESPACE, " ", 5);
        assertFalse(ts.moveNext());
    } finally {
        ((AbstractDocument)doc).readUnlock();
    }
}
 
Example 17
Source Project: netbeans   Source File: TextDocumentServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private JavaSource getSource(String fileUri) {
    Document doc = openedDocuments.get(fileUri);
    if (doc == null) {
        try {
            FileObject file = fromUri(fileUri);
            return JavaSource.forFileObject(file);
        } catch (MalformedURLException ex) {
            return null;
        }
    } else {
        return JavaSource.forDocument(doc);
    }
}
 
Example 18
Source Project: netbeans   Source File: CslTestBase.java    License: Apache License 2.0 5 votes vote down vote up
private static org.netbeans.modules.csl.core.Language getCompletableLanguage(Document doc, int offset) {
    BaseDocument baseDoc = (BaseDocument)doc;
    List<org.netbeans.modules.csl.core.Language> list = LanguageRegistry.getInstance().getEmbeddedLanguages(baseDoc, offset);
    for (org.netbeans.modules.csl.core.Language l : list) {
        if (l.getCompletionProvider() != null) {
            return l;
        }
    }

    return null;
}
 
Example 19
Source Project: netbeans   Source File: EditHistoryTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testMultipleInserts3() throws Exception {
    EditHistory history = new EditHistory();
    String original = "   HelloWorld";
    Document doc = getDocument(original);
    //012345678901234567890
    //   HelloWorld
    //   HelloWo__rld
    insert(doc, history, 10, "__");
    //012345678901234567890
    //   HelloWo__rld
    //   He__lloWo__rld
    insert(doc, history, 5, "__");
    //012345678901234567890
    //   He__lloWo__rld
    //   He__ll__oWo__rld
    insert(doc, history, 9, "__");

    String modified = doc.getText(0, doc.getLength());
    assertEquals("   He__ll__oWo__rld", modified);
    assertEquals(5, history.getStart());
    assertEquals(10, history.getOriginalEnd());
    assertEquals(16, history.getEditedEnd());
    assertEquals(5, history.getOriginalSize());
    assertEquals(11, history.getEditedSize());
    assertEquals(6, history.getSizeDelta());
    validateHistory(original, modified, history);
}
 
Example 20
Source Project: netbeans   Source File: TestMethodUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static SingleMethod getTestMethod(final Document doc, final int cursor) {
    final AtomicReference<SingleMethod> sm = new AtomicReference<>();
    if (doc != null) {

        Source s = Source.create(doc);
        try {
            ParserManager.parseWhenScanFinished(Collections.<Source>singleton(s), new UserTask() {
                @Override
                public void run(ResultIterator rit) throws Exception {
                    Result r = rit.getParserResult();
                    //0:line, 1:column
                    final int[] lc = getLineAndColumn(doc.getText(0, doc.getLength()), cursor);
                    final int line = lc[0];
                    final int col = lc[1];
                    final ModuleNode root = extractModuleNode(r);
                    final ClassNode cn = getClassNodeForLineAndColumn(root, line, col);
                    final MethodNode mn = getMethodNodeForLineAndColumn(cn, line, col);
                    if (mn != null) {
                        final SingleMethod lsm = new SingleMethod(s.getFileObject(), mn.getName());
                        sm.set(lsm);
                    }
                }

            });
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
    return sm.get();
}
 
Example 21
Source Project: netbeans   Source File: WebBrowsersOptionsPanel.java    License: Apache License 2.0 5 votes vote down vote up
private void update(DocumentEvent evt) {
    int index = browsersList.getSelectedIndex();
    Document doc = evt.getDocument();
    if (doc.equals(nameTextField.getDocument())) {
        browsersModel.setBrowserName(index, nameTextField.getText());
    } 
}
 
Example 22
Source Project: netbeans   Source File: BreadcrumbsController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param doc
 * @param selected 
 * @since 1.8
 */
public static void setBreadcrumbs(@NonNull final Document doc, @NonNull final BreadcrumbsElement selected) {
    WORKER.post(new Runnable() {
        @Override public void run() {
            List<BreadcrumbsElement> path = new ArrayList<>();
            
            BreadcrumbsElement el = selected;
            
            while (el != null) {
                path.add(el);
                el = el.getParent();
            }
            
            Node root = new BreadCrumbsNodeImpl(path.remove(path.size() - 1));
            Node last = root;
            
            Collections.reverse(path);
           
            for (BreadcrumbsElement current : path) {
                for (Node n : last.getChildren().getNodes(true)) {
                    if (n.getLookup().lookup(BreadcrumbsElement.class) == current) {
                        last = n;
                        break;
                    }
                }
            }
            
            setBreadcrumbs(doc, root, last);
        }
    });
}
 
Example 23
Source Project: netbeans   Source File: RuntimeCatalogModel.java    License: Apache License 2.0 5 votes vote down vote up
private ModelSource createModelSource(InputStream is) throws CatalogModelException{
    try {
        Document d = AbstractDocumentModel.getAccessProvider().loadSwingDocument(is);
        if(d != null)
            return new ModelSource(Lookups.fixed(new Object[]{this,d}), false);
    } catch (Exception ex) {
        throw new CatalogModelException(ex);
    }
            
    return null;
}
 
Example 24
Source Project: netbeans   Source File: XMLKit.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Document createDefaultDocument() {
    if(J2EE_LEXER_COLORING) {
        Document doc = new XMLEditorDocument(getContentType());
        doc.putProperty(Language.class, XMLTokenId.language());
        return doc;
    } else {
        return super.createDefaultDocument();
    }
}
 
Example 25
Source Project: netbeans   Source File: EventSupport.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Document readDocument(FileObject fileObject, boolean forceOpen) {
    EditorCookie ec = null;
    
    try {
        DataObject dataObject = DataObject.find (fileObject);
        ec = dataObject.getLookup ().lookup (EditorCookie.class);
    } catch (DataObjectNotFoundException ex) {
        //DataobjectNotFoundException may happen in case of deleting opened file
        //handled by returning null
    }

    if (ec == null) return null;
    Document doc = ec.getDocument ();
    if (doc == null && forceOpen) {
        try {
            try {
                doc = ec.openDocument ();
            } catch (UserQuestionException uqe) {
                uqe.confirmed ();
                doc = ec.openDocument ();
            }
        } catch (IOException ioe) {
            LOGGER.log (Level.WARNING, null, ioe);
        }
    }
    return doc;
}
 
Example 26
Source Project: netbeans   Source File: SQLCompletionEnv.java    License: Apache License 2.0 5 votes vote down vote up
private static String getDocumentText(final Document doc) {
    final String[] result = { null };
    doc.render(new Runnable() {
        public void run() {
            try {
                result[0] = doc.getText(0, doc.getLength());
            } catch (BadLocationException e) {
                // Should not happen.
            }
        }
    });
    return result[0];
}
 
Example 27
Source Project: netbeans   Source File: CustomClientServletCodeGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void init(SaasMethod m, Document doc) throws IOException {
    super.init(m, new CustomClientSaasBean((CustomSaasMethod) m, true), doc);
    
    this.j2eeAuthGen = new SaasClientJ2eeAuthenticationGenerator(getBean(), getProject());
    this.j2eeAuthGen.setLoginArguments(getLoginArguments());
    this.j2eeAuthGen.setAuthenticatorMethodParameters(getAuthenticatorMethodParameters());
    this.j2eeAuthGen.setSaasServiceFolder(getSaasServiceFolder());
    this.j2eeAuthGen.setAuthenticationProfile(getBean().getProfile(m, getDropFileType()));
    this.j2eeAuthGen.setDropFileType(getDropFileType());
}
 
Example 28
Source Project: visualvm   Source File: ThreadDumpView.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Document createDefaultDocument() {
    StyleSheet styles = getStyleSheet();
    StyleSheet ss = new StyleSheet();

    ss.addStyleSheet(styles);

    HTMLDocument doc = new CustomHTMLDocument(ss);
    doc.setParser(getParser());
    doc.setAsynchronousLoadPriority(4);
    doc.setTokenThreshold(100);
    return doc;
}
 
Example 29
Source Project: netbeans   Source File: SoapClientPojoCodeGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void init(SaasMethod m, Document doc) throws IOException {
    super.init(m, doc);
    WsdlSaasMethod wsm = (WsdlSaasMethod) m;
    Project p = FileOwnerQuery.getOwner(NbEditorUtilities.getFileObject(doc));
    SaasBean bean = new SoapClientSaasBean(wsm, p, JavaUtil.toJaxwsOperationInfos(wsm, p));
    setBean(bean);
    clearVariablePatterns();
}
 
Example 30
Source Project: netbeans   Source File: NbEditorUI.java    License: Apache License 2.0 5 votes vote down vote up
public NbEditorUI() {
        focusL = new FocusAdapter() {
            public @Override void focusGained(FocusEvent evt) {
                // Refresh file object when component made active
                Document doc = getDocument();
                if (doc != null) {
                    DataObject dob = NbEditorUtilities.getDataObject(doc);
                    if (dob != null) {
                        final FileObject fo = dob.getPrimaryFile();
                        if (fo != null) {
                            // Fixed #48151 - posting the refresh outside of AWT thread
                            synchronized (lock) {
                                objectsToRefresh.add(fo);
                            }
                            TASK.schedule(0);
                        }
                    }
                }

//                // Check if editor is docked and if so then use global status bar.
//                JTextComponent component = getComponent();
//                // Check if component is inside main window
//                boolean underMainWindow = (SwingUtilities.isDescendingFrom(component,
//                WindowManager.getDefault().getMainWindow()));
//                getStatusBar().setVisible(!underMainWindow); // Note: no longer checking the preferences settting
            }

//            @Override
//            public void focusLost(FocusEvent e) {
//                // Clear global panel
//                StatusLineFactories.clearStatusLine();
//            }


        };
    }