javax.swing.text.PlainDocument Java Examples

The following examples show how to use javax.swing.text.PlainDocument. 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: ActionUtils.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the line of text at the given position.  The returned value may
 * be null.  It will not contain the trailing new-line character.
 * @param target the text component
 * @param pos char position
 * @return
 */
public static String getLineAt(JTextComponent target, int pos) {
    String line = null;
    Document doc = target.getDocument();
    if (doc instanceof PlainDocument) {
        PlainDocument pDoc = (PlainDocument) doc;
        int start = pDoc.getParagraphElement(pos).getStartOffset();
        int end = pDoc.getParagraphElement(pos).getEndOffset();
        try {
            line = doc.getText(start, end - start);
            if (line != null && line.endsWith("\n")) {
                line = line.substring(0, line.length() - 1);
            }
        } catch (BadLocationException ex) {
            Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return line;
}
 
Example #2
Source File: ProxyHighlightsContainerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testSimple() {
    PlainDocument doc = new PlainDocument();
    HighlightsContainer layer = createRandomBag(doc, "layer");
    HighlightsSequence highlights = layer.getHighlights(0, 100);
    
    ProxyHighlightsContainer proxyLayer = new ProxyHighlightsContainer(doc, new HighlightsContainer [] { layer });
    HighlightsSequence proxyHighlights = proxyLayer.getHighlights(0, 100);

    for ( ; highlights.moveNext(); ) {
        // Ignore empty highlights
        if (highlights.getStartOffset() == highlights.getEndOffset()) {
            continue;
        }

        assertTrue("Wrong number of proxy highlights", proxyHighlights.moveNext());

        assertEquals("Start offset does not match", highlights.getStartOffset(), proxyHighlights.getStartOffset());
        assertEquals("End offset does not match", highlights.getEndOffset(), proxyHighlights.getEndOffset());
        assertTrue("Attributes do not match", highlights.getAttributes().isEqual(proxyHighlights.getAttributes()));
    }
}
 
Example #3
Source File: ActionUtils.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the lines that span the selection (split as an array of Strings)
 * if there is no selection then current line is returned.
 * 
 * Note that the strings returned will not contain the terminating line feeds
 * 
 * The text component will then have the full lines set as selection
 * @param target
 * @return String[] of lines spanning selection / or Dot
 */
public static String[] getSelectedLines(JTextComponent target) {
    String[] lines = null;
    try {
        PlainDocument pDoc = (PlainDocument) target.getDocument();
        int start = pDoc.getParagraphElement(target.getSelectionStart()).getStartOffset();
        int end;
        if (target.getSelectionStart() == target.getSelectionEnd()) {
            end = pDoc.getParagraphElement(target.getSelectionEnd()).getEndOffset();
        } else {
            // if more than one line is selected, we need to subtract one from the end
            // so that we do not select the line with the caret and no selection in it
            end = pDoc.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
        }
        target.select(start, end);
        lines = pDoc.getText(start, end - start).split("\n");
        target.select(start, end);
    } catch (BadLocationException ex) {
        Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
        lines = EMPTY_STRING_ARRAY;
    }
    return lines;
}
 
Example #4
Source File: SyntaxUtil.java    From nextreports-designer with Apache License 2.0 6 votes vote down vote up
/**
 * Return the line of text at the given position. The returned value may
 * be null. It will not contain the trailing new-line character.
 * 
 * @param doc
 * @param pos
 * @return
 */
public static String getLineAt(PlainDocument doc, int pos) {
    String line = null;
    int start = doc.getParagraphElement(pos).getStartOffset();
    int end = doc.getParagraphElement(pos).getEndOffset();
    try {
        line = doc.getText(start, end - start);
        if (line != null && line.endsWith("\n")) {
            line = line.substring(0, line.length() - 1);
        }
    } catch (BadLocationException e) {
        LOG.error(e.getMessage(), e);
    }
    
    return line;
}
 
Example #5
Source File: ChooseByNameBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
private MyTextField() {
  super(40);
  enableEvents(AWTEvent.KEY_EVENT_MASK);
  myCompletionKeyStroke = getShortcut(IdeActions.ACTION_CODE_COMPLETION);
  forwardStroke = getShortcut(IdeActions.ACTION_GOTO_FORWARD);
  backStroke = getShortcut(IdeActions.ACTION_GOTO_BACK);
  setFocusTraversalKeysEnabled(false);
  putClientProperty("JTextField.variant", "search");
  setDocument(new PlainDocument() {
    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
      super.insertString(offs, str, a);
      if (str != null && str.length() > 1) {
        handlePaste(str);
      }
    }
  });
}
 
Example #6
Source File: HighlightingManagerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testExcludeTwoLayers() {
    OffsetsBag bag = new OffsetsBag(new PlainDocument());
    
    MemoryMimeDataProvider.reset(null);
    MemoryMimeDataProvider.addInstances(
        "text/plain", new SingletonLayerFactory("layer", ZOrder.DEFAULT_RACK, true, bag));

    JEditorPane pane = new JEditorPane();
    String [] removed = new String[] {"^org\\.netbeans\\.modules\\.editor\\.lib2\\.highlighting\\..*$", "^org\\.netbeans\\.modules\\.editor\\.lib2\\.highlighting\\.TextSelectionHighlighting$"};
    pane.putClientProperty("HighlightsLayerExcludes", removed);
    pane.setContentType("text/plain");
    assertEquals("The pane has got wrong mime type", "text/plain", pane.getContentType());
    
    HighlightingManager hm = HighlightingManager.getInstance(pane);
    HighlightsContainer hc = hm.getHighlights(HighlightsLayerFilter.IDENTITY);

    assertNotNull("Can't get fixed HighlightsContainer", hc);
    assertFalse("There should be no fixed highlights", hc.getHighlights(0, Integer.MAX_VALUE).moveNext());
}
 
Example #7
Source File: PositionsBagRandomTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private PositionsBag mergeContainers(boolean merge, String [] layerNames, HighlightsContainer[] containers) {
    PositionsBag bag = new PositionsBag(new PlainDocument(), merge);

    for (int i = 0; i < containers.length; i++) {
        HighlightsSequence layerHighlights = 
            containers[i].getHighlights(START, END);
        
        for ( ; layerHighlights.moveNext(); ) {
            bag.addHighlight(
                new SimplePosition(layerHighlights.getStartOffset()), 
                new SimplePosition(layerHighlights.getEndOffset()), 
                layerHighlights.getAttributes());
        }
    }
    
    return bag;
}
 
Example #8
Source File: PlainDocumentTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCuriosities() throws Exception {
    // Test position at offset 0 does not move after insert
    Document doc = new PlainDocument();
    doc.insertString(0, "test", null);
    Position pos = doc.createPosition(0);
    assertEquals(0, pos.getOffset());
    doc.insertString(0, "a", null);
    assertEquals(0, pos.getOffset());
    
    // Test there is an extra newline above doc.getLength()
    assertEquals("\n", doc.getText(doc.getLength(), 1));
    assertEquals("atest\n", doc.getText(0, doc.getLength() + 1));
    
    // Test the last line element contains the extra newline
    Element lineElem = doc.getDefaultRootElement().getElement(0);
    assertEquals(0, lineElem.getStartOffset());
    assertEquals(doc.getLength() + 1, lineElem.getEndOffset());

    // Test that once position gets to zero it won't go anywhere else (unless undo performed)
    pos = doc.createPosition(1);
    doc.remove(0, 1);
    assertEquals(0, pos.getOffset());
    doc.insertString(0, "b", null);
    assertEquals(0, pos.getOffset());
}
 
Example #9
Source File: ProxyHighlightsContainerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testEvents() {
    PlainDocument doc = new PlainDocument();
    PositionsBag hsA = new PositionsBag(doc);
    PositionsBag hsB = new PositionsBag(doc);
    
    ProxyHighlightsContainer chc = new ProxyHighlightsContainer(doc, new HighlightsContainer [] { hsA, hsB });
    Listener listener = new Listener();
    chc.addHighlightsChangeListener(listener);
    
    hsA.addHighlight(new SimplePosition(10), new SimplePosition(20), new SimpleAttributeSet());
    assertEquals("Wrong number of events", 1, listener.eventsCnt);
    assertEquals("Wrong change start offset", 10, listener.lastEventStartOffset);
    assertEquals("Wrong change end offset", 20, listener.lastEventEndOffset);

    listener.reset();
    hsB.addHighlight(new SimplePosition(11), new SimplePosition(12), new SimpleAttributeSet());
    assertEquals("Wrong number of events", 1, listener.eventsCnt);
    assertEquals("Wrong change start offset", 11, listener.lastEventStartOffset);
    assertEquals("Wrong change end offset", 12, listener.lastEventEndOffset);
}
 
Example #10
Source File: ActionUtils.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return the lines that span the selection (split as an array of Strings)
 * if there is no selection then current line is returned.
 *
 * Note that the strings returned will not contain the terminating line feeds
 * If the document is empty, then an empty string array is returned.  So
 * you can always iterate over the returned array without a null check
 *
 * The text component will then have the full lines set as selection
 * @param target
 * @return String[] of lines spanning selection / or line containing dot
 */
public static String[] getSelectedLines(JTextComponent target) {
	String[] lines = null;
	try {
		PlainDocument pDoc = (PlainDocument) target.getDocument();
		int start = pDoc.getParagraphElement(target.getSelectionStart()).getStartOffset();
		int end;
		if (target.getSelectionStart() == target.getSelectionEnd()) {
			end = pDoc.getParagraphElement(target.getSelectionEnd()).getEndOffset();
		} else {
			// if more than one line is selected, we need to subtract one from the end
			// so that we do not select the line with the caret and no selection in it
			end = pDoc.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
		}
		target.select(start, end);
		lines = pDoc.getText(start, end - start).split("\n");
		target.select(start, end);
	} catch (BadLocationException ex) {
		Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
		lines = EMPTY_STRING_ARRAY;
	}
	return lines;
}
 
Example #11
Source File: UnindentAction.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
public void actionPerformed(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    Integer tabStop = (Integer) target.getDocument().getProperty(PlainDocument.tabSizeAttribute);
    String indent = ActionUtils.SPACES.substring(0, tabStop);
    if (target != null) {
        String[] lines = ActionUtils.getSelectedLines(target);
        int start = target.getSelectionStart();
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            if (line.startsWith(indent)) {
                sb.append(line.substring(indent.length()));
            } else if (line.startsWith("\t")) {
                sb.append(line.substring(1));
            } else {
                sb.append(line);
            }
            sb.append('\n');
        }
        target.replaceSelection(sb.toString());
        target.select(start, start + sb.length());
    }
}
 
Example #12
Source File: ComplexPositionsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Test
public void testPos() throws Exception {
    Document doc = new PlainDocument();
    doc.insertString(0, "\t\t\n\n", null);
    Position pos1 = doc.createPosition(1);
    Position pos2 = doc.createPosition(2);
    
    Position pos10 = ComplexPositions.create(pos1, 0);
    Position pos11 = ComplexPositions.create(pos1, 1);
    Position pos20 = ComplexPositions.create(pos2, 0);
    Position pos21 = ComplexPositions.create(pos2, 1);
    
    assertEquals(0, ComplexPositions.getSplitOffset(pos1));
    assertEquals(0, ComplexPositions.getSplitOffset(pos10));
    assertEquals(1, ComplexPositions.getSplitOffset(pos11));
    comparePos(pos1, pos10, 0);
    comparePos(pos10, pos11, -1);
    comparePos(pos1, pos2, -1);
    comparePos(pos10, pos20, -1);
    comparePos(pos20, pos21, -1);
}
 
Example #13
Source File: PHPTokenListTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Check a token list with writing.
 *
 * @param documentContent
 * @param offset
 * @param text
 * @param startOffset
 * @param golden expected words
 * @throws Exception
 */
private void tokenListTestWithWriting(String documentContent, int offset, String text, int startOffset, String... golden) throws Exception {
    Document doc = new PlainDocument();
    doc.putProperty(Language.class, PHPTokenId.language());
    doc.insertString(0, PHPTAG + documentContent, null);
    List<String> words = new ArrayList<>();
    TokenList tokenList = new PHPTokenList(doc);
    while (tokenList.nextWord()) {
    }

    doc.insertString(offset + PHPTAG.length(), text, null);
    tokenList.setStartOffset(startOffset + PHPTAG.length());
    while (tokenList.nextWord()) {
        words.add(tokenList.getCurrentWordText().toString());
    }
    assertEquals(Arrays.asList(golden), words);
}
 
Example #14
Source File: CompoundHighlightsContainerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testOrdering() {
    PlainDocument doc = new PlainDocument();
    PositionsBag hsA = new PositionsBag(doc);
    PositionsBag hsB = new PositionsBag(doc);

    SimpleAttributeSet attribsA = new SimpleAttributeSet();
    SimpleAttributeSet attribsB = new SimpleAttributeSet();
    
    attribsA.addAttribute("attribute", "value-A");
    attribsB.addAttribute("attribute", "value-B");
    
    hsA.addHighlight(new SimplePosition(5), new SimplePosition(15), attribsA);
    hsB.addHighlight(new SimplePosition(10), new SimplePosition(20), attribsB);
    
    CompoundHighlightsContainer chc = new CompoundHighlightsContainer(doc, new HighlightsContainer [] { hsA, hsB });
    HighlightsSequence highlights = chc.getHighlights(0, Integer.MAX_VALUE);

    assertTrue("Wrong number of highlights", highlights.moveNext());
    assertEquals("1. highlight - wrong attribs", "value-A", highlights.getAttributes().getAttribute("attribute"));

    assertTrue("Wrong number of highlights", highlights.moveNext());
    assertEquals("2. highlight - wrong attribs", "value-B", highlights.getAttributes().getAttribute("attribute"));

    assertTrue("Wrong number of highlights", highlights.moveNext());
    assertEquals("3. highlight - wrong attribs", "value-B", highlights.getAttributes().getAttribute("attribute"));
}
 
Example #15
Source File: CompoundHighlightsContainerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testConcurrentModification() throws Exception {
    PlainDocument doc = new PlainDocument();
    PositionsBag bag = createRandomBag(doc, "layer");
    HighlightsContainer [] layers = new HighlightsContainer [] { bag };
    
    CompoundHighlightsContainer hb = new CompoundHighlightsContainer(doc, layers);
    HighlightsSequence hs = hb.getHighlights(0, Integer.MAX_VALUE);
    
    assertTrue("No highlights", hs.moveNext());
    int s = hs.getStartOffset();
    int e = hs.getEndOffset();
    AttributeSet a = hs.getAttributes();

    // Change the layers
    hb.setLayers(doc, layers);
    
    assertEquals("Different startOffset", s, hs.getStartOffset());
    assertEquals("Different endOffset", e, hs.getEndOffset());
    assertEquals("Different attributes", a, hs.getAttributes());
    
    assertFalse("There should be no further highlighs after co-modification", hs.moveNext());
}
 
Example #16
Source File: ActionUtils.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return the line of text at the given position.  The returned value may
 * be null.  It will not contain the trailing new-line character.
 * @param target the text component
 * @param pos char position
 * @return
 */
public static String getLineAt(JTextComponent target, int pos) {
	String line = null;
	Document doc = target.getDocument();
	if (doc instanceof PlainDocument) {
		PlainDocument pDoc = (PlainDocument) doc;
		int start = pDoc.getParagraphElement(pos).getStartOffset();
		int end = pDoc.getParagraphElement(pos).getEndOffset();
		try {
			line = doc.getText(start, end - start);
			if (line != null && line.endsWith("\n")) {
				line = line.substring(0, line.length() - 1);
			}
		} catch (BadLocationException ex) {
			Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
	return line;
}
 
Example #17
Source File: CompoundHighlightsContainerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testEvents() {
    PlainDocument doc = new PlainDocument();
    PositionsBag hsA = new PositionsBag(doc);
    PositionsBag hsB = new PositionsBag(doc);
    
    CompoundHighlightsContainer chc = new CompoundHighlightsContainer(doc, new HighlightsContainer [] { hsA, hsB });
    Listener listener = new Listener();
    chc.addHighlightsChangeListener(listener);
    
    hsA.addHighlight(new SimplePosition(10), new SimplePosition(20), new SimpleAttributeSet());
    assertEquals("Wrong number of events", 1, listener.eventsCnt);
    assertEquals("Wrong change start offset", 10, listener.lastEventStartOffset);
    assertEquals("Wrong change end offset", 20, listener.lastEventEndOffset);

    listener.reset();
    hsB.addHighlight(new SimplePosition(11), new SimplePosition(12), new SimpleAttributeSet());
    assertEquals("Wrong number of events", 1, listener.eventsCnt);
    assertEquals("Wrong change start offset", 11, listener.lastEventStartOffset);
    assertEquals("Wrong change end offset", 12, listener.lastEventEndOffset);
}
 
Example #18
Source File: CompoundHighlightsContainerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testEvents2() {
    PlainDocument doc = new PlainDocument();
    PositionsBag hsA = new PositionsBag(doc);
    PositionsBag hsB = new PositionsBag(doc);

    hsA.addHighlight(new SimplePosition(10), new SimplePosition(20), new SimpleAttributeSet());
    hsB.addHighlight(new SimplePosition(11), new SimplePosition(12), new SimpleAttributeSet());

    CompoundHighlightsContainer chc = new CompoundHighlightsContainer();
    Listener listener = new Listener();
    chc.addHighlightsChangeListener(listener);

    // changing delegate layers fires event covering 'all' offsets
    chc.setLayers(doc, new HighlightsContainer [] { hsA, hsB });
    assertEquals("Wrong number of events", 1, listener.eventsCnt);
    assertEquals("Wrong change start offset", 0, listener.lastEventStartOffset);
    assertEquals("Wrong change end offset", Integer.MAX_VALUE, listener.lastEventEndOffset);
}
 
Example #19
Source File: DocumentUtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAddWeakPropertyChangeListenerSupported() {
    SampleListener sl = new SampleListener();
    // This simulates the construction of the BaseDocument
    PlainDocument pd = new PlainDocument();
    PropertyChangeSupport pcs = new PropertyChangeSupport(pd);
    pd.putProperty(PropertyChangeSupport.class, pcs);

    PropertyChangeListener weakListener = DocumentUtilities.addWeakPropertyChangeListener(pd, sl);
    // A PropertyChangeListener added through addWeakPropertyChangeListener
    // to a PropertyChangeListener supporting document, must be reflected
    // in a non-null return value
    assertNotNull(weakListener);

    // the backing listner needs to be invoked when a property is changed
    pcs.firePropertyChange("demoProperty", null, "demoValue");
    assertEquals(1, sl.getCallCount("demoProperty"));

    // The returned Listner must be usable for listener removal
    DocumentUtilities.removePropertyChangeListener(pd, weakListener);
    sl.reset();
    pcs.firePropertyChange("demoProperty", null, "demoValue");
    assertEquals(0, sl.getCallCount("demoProperty"));

}
 
Example #20
Source File: SyntaxDocument.java    From nextreports-designer with Apache License 2.0 6 votes vote down vote up
public SyntaxDocument(Lexer lexer) {
    super();
    putProperty(PlainDocument.tabSizeAttribute, 4); // outside ?!
    this.lexer = lexer;
    
    // Listen for undo and redo events
    addUndoableEditListener(new UndoableEditListener() {

        public void undoableEditHappened(UndoableEditEvent event) {
            if (event.getEdit().isSignificant()) {
                undo.addEdit(event.getEdit());
            }
        }
        
    });
}
 
Example #21
Source File: CompoundHighlightsContainerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testZeroPosition() throws BadLocationException {
    PlainDocument doc = new PlainDocument();
    TestHighlighsContainer thc = new TestHighlighsContainer();
    CompoundHighlightsContainer chc = new CompoundHighlightsContainer();

    chc.setLayers(doc, new HighlightsContainer[] { thc });
    doc.insertString(0, "0123456789", null);

    chc.getHighlights(0, Integer.MAX_VALUE);
    assertEquals("Should have been queried", 2, thc.queries.size());
    assertEquals("Wrong query startOffset", 0, (int) thc.queries.get(0));

    thc.queries.clear();
    doc.insertString(0, "abcd", null);
    assertEquals("Should not have been queried", 0, thc.queries.size());

    chc.getHighlights(0, Integer.MAX_VALUE);
    assertEquals("Should have been queried again", 2, thc.queries.size());
    assertEquals("Wrong query startOffset", 0, (int) thc.queries.get(0));

    thc.queries.clear();
    chc.getHighlights(0, Integer.MAX_VALUE);
    assertEquals("Should not have been queried again", 0, thc.queries.size());
}
 
Example #22
Source File: JWSProjectProperties.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Document createCBTextFieldDocument() {
    Document doc = new PlainDocument();
    String valueType = evaluator.getProperty(JNLP_CBASE_TYPE);
    String docString = "";
    if (CB_TYPE_LOCAL.equals(valueType)) {
        docString = getProjectDistDir();
    } else if (CB_TYPE_WEB.equals(valueType)) {
        docString = CB_URL_WEB;
    } else if (CB_TYPE_USER.equals(valueType)) {
        docString = getCodebaseLocation();
    }
    try {
        doc.insertString(0, docString, null);
    } catch (BadLocationException ex) {
        // do nothing, just return PlainDocument
        // XXX log the exc
    }
    return doc;
}
 
Example #23
Source File: WordMatchTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testOffset0Forward() throws Exception {
    Document doc = new PlainDocument();
    WordMatch wordMatch = WordMatch.get(doc);
    //                   012345678901234567890123456789
    doc.insertString(0, "abc abc dab ab a abab+c", null);
    int docLen = doc.getLength();
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "abca", docLen + 3);
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "daba", docLen + 3);
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "aba", docLen + 2);
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "aa", docLen + 1);
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "ababa", docLen + 4);
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "ca", docLen + 1);
    wordMatch.matchWord(0, true);
    compareText(doc, 0, "ca", docLen + 1);

    wordMatch.matchWord(0, false);
    compareText(doc, 0, "ababa", docLen + 4);
}
 
Example #24
Source File: WordMatchTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testOffsetDocLenBackward() throws Exception {
    Document doc = new PlainDocument();
    WordMatch wordMatch = WordMatch.get(doc);
    //                   012345678901234567890123456789
    doc.insertString(0, "abc abc dab ab a", null);
    int docLen = doc.getLength();
    wordMatch.matchWord(docLen, false);
    compareText(doc, docLen - 1, "ab", docLen + 1);
    wordMatch.matchWord(docLen, false);
    compareText(doc, docLen - 1, "abc", docLen + 2);
    wordMatch.matchWord(docLen, false);
    compareText(doc, docLen - 1, "abc", docLen + 2);

    wordMatch.matchWord(docLen, true);
    compareText(doc, docLen - 1, "ab", docLen + 1);
    wordMatch.matchWord(docLen, true);
    compareText(doc, docLen - 1, "a", docLen);
}
 
Example #25
Source File: TextmateLexerTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testUTF8() throws Exception {
    clearWorkDir();

    FileObject grammar = FileUtil.createData(FileUtil.getConfigRoot(), "Editors/text/test/grammar.json");
    try (OutputStream out = grammar.getOutputStream();
         Writer w = new OutputStreamWriter(out)) {
        w.write("{ \"scopeName\": \"test\", " +
                " \"patterns\": [\n" + 
                "  { \"name\": \"ident.test\",\n" +
                "    \"match\": \"[^ ]+\"\n" +
                "   }\n" +
                "]}\n");
    }
    grammar.setAttribute(LanguageHierarchyImpl.GRAMMAR_MARK, "test");
    Document doc = new PlainDocument();
    doc.insertString(0, " večerníček večerníček  ", null);
    doc.putProperty(Language.class, new LanguageHierarchyImpl("text/test", "test").language());
    TokenHierarchy<Document> hi = TokenHierarchy.get(doc);
    TokenSequence<?> ts = hi.tokenSequence();
    LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
    assertTokenProperties(ts, "test");
    LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "večerníček");
    assertTokenProperties(ts, "test", "ident.test");
    LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
    assertTokenProperties(ts, "test");
    LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "večerníček");
    assertTokenProperties(ts, "test", "ident.test");
    LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "  ");
    assertTokenProperties(ts, "test");
    LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "\n");
    assertFalse(ts.moveNext());
}
 
Example #26
Source File: DocumentUtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAddWeakPropertyChangeListenerUnsupported() {
    // It is expected, that if the backing document does not support
    // PropertyChangeListener (PlainDocument), null is returned
    SampleListener sl = new SampleListener();
    PlainDocument pd = new PlainDocument();
    PropertyChangeListener weakListener = DocumentUtilities.addWeakPropertyChangeListener(pd, sl);
    assertNull(weakListener);
}
 
Example #27
Source File: WordMatchTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testMultiDocs() throws Exception {
    JEditorPane pane = new JEditorPane();
    pane.setText("abc ax ec ajo");
    JFrame frame = new JFrame();
    frame.getContentPane().add(pane);
    frame.pack(); // Allows to EditorRegistry.register() to make an item in the component list
    EditorApiPackageAccessor.get().setIgnoredAncestorClass(JEditorPane.class);
    EditorApiPackageAccessor.get().register(pane);
    
    Document doc = new PlainDocument();
    WordMatch wordMatch = WordMatch.get(doc);
    //                   012345678901234567890123456789
    doc.insertString(0, "abc a x ahoj", null);
    int docLen = doc.getLength();
    int offset = 5;
    wordMatch.matchWord(offset, false);
    compareText(doc, offset - 1, "abc ", docLen + 2);
    wordMatch.matchWord(offset, false);
    compareText(doc, offset - 1, "ahoj ", docLen + 3);
    wordMatch.matchWord(offset, false);
    compareText(doc, offset - 1, "ax ", docLen + 1);
    wordMatch.matchWord(offset, false);
    compareText(doc, offset - 1, "ajo ", docLen + 2);
    wordMatch.matchWord(offset, false);
    compareText(doc, offset - 1, "ajo ", docLen + 2);
    pane.setText(""); // Ensure this doc would affect WordMatch for other docs
}
 
Example #28
Source File: DocumentUtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testGetText() throws Exception {
    PlainDocument doc = new PlainDocument();
    CharSequence text = DocumentUtilities.getText(doc);
    assertEquals(1, text.length());
    assertEquals('\n', text.charAt(0));

    text = DocumentUtilities.getText(doc);
    doc.insertString(0, "a\nb", null);
    for (int i = 0; i < doc.getLength() + 1; i++) {
        assertEquals(doc.getText(i, 1).charAt(0), text.charAt(i));
    }
}
 
Example #29
Source File: PositionsBagFindHighlightTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected @Override void setUp() {
        cnt = this.getTestNumber();
        bag = new PositionsBag(new PlainDocument(), false);
        
        for(int i = 0; i < cnt; i++) {
            bag.addHighlight(new SimplePosition(i * 10), new SimplePosition(i * 10 + 5), SimpleAttributeSet.EMPTY);
        }

        startOffset = 10 * cnt / 5 - 1;
        endOffset = 10 * (cnt/ 5 + 1) - 1;
        
//        System.out.println("cnt = " + cnt + " : startOffset = " + startOffset + " : endOffset = " + endOffset);
    }
 
Example #30
Source File: TextFieldDataBind.java    From iec61850bean with Apache License 2.0 5 votes vote down vote up
@Override
protected JComponent init() {
  inputField = new JTextField();
  PlainDocument doc = (PlainDocument) inputField.getDocument();
  doc.setDocumentFilter(filter);
  resetImpl();
  return inputField;
}