javax.swing.text.Document Java Examples

The following examples show how to use javax.swing.text.Document. 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: XmlTokenList.java    From netbeans with 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 #2
Source File: UndoableEditWrapperTest.java    From netbeans with 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 #3
Source File: MainPanel.java    From java-swing-tips with 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 #4
Source File: CamelCaseOperations.java    From netbeans with 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 #5
Source File: LWTextComponentPeer.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@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 #6
Source File: TextManager.java    From jeveassets with 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 #7
Source File: TokenSequenceTest.java    From netbeans with 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 #8
Source File: Formatter.java    From netbeans with 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 #9
Source File: BreadcrumbsController.java    From netbeans with 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 #10
Source File: PlainDocumentTest.java    From netbeans with 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 #11
Source File: HintsControllerImpl.java    From netbeans with 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 #12
Source File: JavadocCompletionQuery.java    From netbeans with 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 #13
Source File: YamlCompletion.java    From netbeans with 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 #14
Source File: Util.java    From netbeans with 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 #15
Source File: LWTextAreaPeer.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@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 #16
Source File: DiffResultsViewForLine.java    From netbeans with 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 #17
Source File: HtmlHintsProviderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testOrderOfRegisteredRules() throws ParseException {
        Language htmlGsfLanguage = LanguageRegistry.getInstance().getLanguageByMimeType("text/html");
        GsfHintsManager manager = new GsfHintsManager("text/html", new HtmlHintsProvider(), htmlGsfLanguage);
        
        final RuleContext rc = new RuleContext();
        Document doc = getDocument("fake");
        Source source = Source.create(doc);
        ParserManager.parse(Collections.singleton(source), new UserTask() {

            @Override
            public void run(ResultIterator resultIterator) throws Exception {
                HtmlParserResult parserResult = (HtmlParserResult)resultIterator.getParserResult();
                assertNotNull(parserResult);
                rc.parserResult = parserResult;
                
            }
        });
        List<? extends HtmlRule> rules = HtmlHintsProvider.getSortedRules(manager, rc, false);
        //check if the last one is the "All Other" rule
        int rulesNum = 22;
        
        assertEquals(rulesNum, rules.size());
        
//        for(HtmlRule rule : rules) {
//            System.out.println(rule.getDisplayName());
//        }
        
        //uncomment once Bug 223793 - Order of hints for CSL languages gets fixed
        assertEquals("All Other", rules.get(rulesNum - 1).getDisplayName());
        assertEquals("Common But Not Valid", rules.get(0).getDisplayName());
        
        
    }
 
Example #18
Source File: KOHtmlExtension.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public OffsetRange getReferenceSpan(final Document doc, final int caretOffset) {
    final OffsetRange[] value = new OffsetRange[1];
    doc.render(new Runnable() {

        @Override
        public void run() {
            TokenSequence<? extends HTMLTokenId> ts = LexerUtils.getTokenSequence(doc, caretOffset, HTMLTokenId.language(), false);
            if (ts == null) {
                return;
            }

            ts.move(caretOffset);
            if (ts.moveNext()) {
                HTMLTokenId id = ts.token().id();
                if (id == HTMLTokenId.TAG_OPEN || id == HTMLTokenId.TAG_CLOSE) {
                    boolean customElement = isTagCustomKnockoutElement(Source.create(doc).getFileObject(), ts.token().text().toString());
                    if (customElement) {
                        value[0] = new OffsetRange(ts.offset(), ts.offset() + ts.token().length());
                    }
                }
            }
        }
    });
    if (value[0] != null) {
        return value[0];
    }
    return OffsetRange.NONE;
}
 
Example #19
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
public void textProgress(boolean append) {
  if (append) {
    area.append("*");
  } else {
    try {
      Document doc = area.getDocument();
      doc.remove(doc.getLength() - 1, 1);
    } catch (BadLocationException ex) {
      // should never happen
      RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
      wrap.initCause(ex);
      throw wrap;
    }
  }
}
 
Example #20
Source File: AddBeanPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String findClassName() {
    final String[] clazzName = new String[1];
    JavaSource js = JavaSource.forDocument(document);
    if (js == null) {
        return null;
    }
    try {
        js.runUserActionTask(new Task<CompilationController>() {

            @Override
            public void run(CompilationController cc) throws Exception {
                cc.toPhase(JavaSource.Phase.RESOLVED);
                Document doc = cc.getDocument();
                if (doc != null) {
                    ExpressionTree packageTree = cc.getCompilationUnit().getPackageName();
                    if (packageTree != null) {
                        TreePath path = cc.getTrees().getPath(cc.getCompilationUnit(), packageTree);
                        Name qualifiedName = cc.getElements().getPackageOf(
                                cc.getTrees().getElement(path)).getQualifiedName();
                        clazzName[0] = qualifiedName.toString() + "."; //NOI18N
                    }
                    String cls = new ClassScanner().scan(cc.getCompilationUnit(), null);
                    if (clazzName[0] == null) {
                        clazzName[0] = cls;
                    } else {
                        clazzName[0] += cls;
                    }
                }


            }
        }, true);
        return clazzName[0];
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }

    return null;
}
 
Example #21
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private static void removeLines(Document doc, Element root) {
  Element fl = root.getElement(0);
  try {
    doc.remove(0, fl.getEndOffset());
  } catch (BadLocationException ex) {
    // should never happen
    RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
    wrap.initCause(ex);
    throw wrap;
  }
}
 
Example #22
Source File: DocumentContext.java    From netbeans with Apache License 2.0 5 votes vote down vote up
DocumentContext(Document document) {
    this.document = document;
    try {
        this.syntaxSupport = XMLSyntaxSupport.getSyntaxSupport(document);
    } catch (ClassCastException cce) {
        LOGGER.log(Level.FINE, cce.getMessage());
        this.syntaxSupport = XMLSyntaxSupport.createSyntaxSupport(document);
    }
}
 
Example #23
Source File: FoldOperationImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void checkLocked() {
    Document d = getDocument();
        if (d != null) {
            // diagnostics, not throwing exceptions since it could disturb
            // editing
            if (!DocumentUtilities.isReadLocked(d)) {
                LOG.log(Level.WARNING, "Underlying document not read/write locked", 
                        Exceptions.attachSeverity(new Throwable(), Level.FINE));
            }
            if (!execution.isLockedByCaller()) {
                LOG.log(Level.WARNING, "Fold hierarchy is not locked on transaction open", 
                        Exceptions.attachSeverity(new Throwable(), Level.FINE));
            }
        }
}
 
Example #24
Source File: JavaViewHierarchyRandomTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testSimple1() throws Exception {
    loggingOn();
    RandomTestContainer container = createContainer();
    JEditorPane pane = container.getInstance(JEditorPane.class);
    Document doc = pane.getDocument();
    doc.putProperty("mimeType", "text/plain");
    RandomTestContainer.Context gContext = container.context();
    DocumentTesting.insert(gContext, 0, "a\nb");
    DocumentTesting.insert(gContext, 1, "c");
}
 
Example #25
Source File: ErrorHintsProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Result result, SchedulerEvent event) {
    resume();

    CompilationInfo info = CompilationInfo.get(result);

    if (info == null) {
        return ;
    }

    Document doc = result.getSnapshot().getSource().getDocument(false);
    
    if (doc == null) {
        Logger.getLogger(ErrorHintsProvider.class.getName()).log(Level.FINE, "SemanticHighlighter: Cannot get document!");
        return ;
    }

    long version = DocumentUtilities.getDocumentVersion(doc);
    String mimeType = result.getSnapshot().getSource().getMimeType();
    
    long start = System.currentTimeMillis();

    try {
        List<ErrorDescription> errors = computeErrors(info, doc, mimeType);

        if (errors == null) //meaning: cancelled
            return ;
        EmbeddedHintsCollector.setAnnotations(result.getSnapshot(), errors);

        ErrorPositionRefresherHelper.setVersion(doc, errors);
        
        long end = System.currentTimeMillis();

        Logger.getLogger("TIMER").log(Level.FINE, "Java Hints",
                new Object[]{info.getFileObject(), end - start});
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #26
Source File: HTMLTextComponent.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
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 #27
Source File: CloneableEditorSupportTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testDocumentCanBeRead () throws Exception {
    content = "Ahoj\nMyDoc";
    javax.swing.text.Document doc = support.openDocument ();
    assertNotNull (doc);
    
    String s = doc.getText (0, doc.getLength ());
    assertEquals ("Same text as in the stream", content, s);
    
    assertFalse ("No redo", support.getUndoRedo ().canRedo ());
    assertFalse ("No undo", support.getUndoRedo ().canUndo ());
}
 
Example #28
Source File: EditorBookmarksModule.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void propertyChange (PropertyChangeEvent evt) {
    // event for the editors tracker
    if (evt.getSource () == EditorRegistry.class) {
        if (evt.getPropertyName () == null || 
            EditorRegistry.FOCUS_GAINED_PROPERTY.equals (evt.getPropertyName ())
        ) {
            JTextComponent jtc = (JTextComponent) evt.getNewValue ();
            PropertyChangeListener l = (PropertyChangeListener) jtc.getClientProperty (DOCUMENT_TRACKER_PROP);
            if (l == null) {
                jtc.putClientProperty (DOCUMENT_TRACKER_PROP, documentListener);
                jtc.addPropertyChangeListener (documentListener);
            }
            myTask.schedule(100);
        }
        return;
    }

    // event for the document tracker
    if (evt.getSource () instanceof JTextComponent) {
        if (evt.getPropertyName () == null ||
            "document".equals (evt.getPropertyName ())
        ) { //NOI18N
            Document newDoc = (Document) evt.getNewValue ();
            if (newDoc != null) {
                myTask.schedule(100);
            }
        }
    }
}
 
Example #29
Source File: TextDocumentServiceImpl.java    From netbeans with 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 #30
Source File: HighlightingManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
synchronized void rebuildAllLayers() {
    Document doc = pane.getDocument();
    if (doc != null) {
        doc.render(new Runnable() {
            @Override
            public void run() {
                rebuildAllLayersImpl();
            }
        });
    }
}