Java Code Examples for javax.swing.text.Document#getLength()

The following examples show how to use javax.swing.text.Document#getLength() . 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 check out the related API usage on the sidebar.
Example 1
Source Project: PacketProxy   File: WrapEditorKit.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void write(Writer out, Document doc, int pos, int len) throws IOException, BadLocationException {
	if ((pos < 0) || ((pos + len) > doc.getLength())) {
		throw new BadLocationException("DefaultEditorKit.write", pos);
	}

	Segment data = new Segment();
	int nleft = len;
	int offs = pos;

	while (nleft > 0) {
		int n = Math.min(nleft, 4096);
		doc.getText(offs, n, data);
		out.write(data.array, data.offset, data.count);
		offs += n;
		nleft -= n;
	}
}
 
Example 2
synchronized void returnPressed() {
    Document doc = getDocument();
    int len = doc.getLength();
    Segment segment = new Segment();
    try {
        doc.getText(outputMark, len - outputMark, segment);
    } catch(javax.swing.text.BadLocationException ignored) {
        ignored.printStackTrace();
    }
    if(segment.count > 0) {
        history.add(segment.toString());
    }
    historyIndex = history.size();
    inPipe.write(segment.array, segment.offset, segment.count);
    append("\n");
    outputMark = doc.getLength();
    inPipe.write("\n");
    inPipe.flush();
    console1.flush();
}
 
Example 3
Source Project: netbeans   File: DocumentTesting.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void run(Context context) throws Exception {
    Document doc = getDocument(context);
    int docLen = doc.getLength();
    if (docLen == 0)
        return; // Nothing to possibly remove
    Random random = context.container().random();
    int length;
    if (REMOVE_CHAR == name()) { // Just use ==
        length = 1;
    } else if (REMOVE_TEXT == name()) { // Just use ==
        Integer maxLength = (Integer) context.getPropertyOrNull(REMOVE_TEXT_MAX_LENGTH);
        if (maxLength == null)
            maxLength = Integer.valueOf(10);
        if (maxLength > docLen)
            maxLength = Integer.valueOf(docLen);
        length = random.nextInt(maxLength) + 1;
    } else {
        throw new IllegalStateException("Unexpected op name=" + name());
    }
    int offset = random.nextInt(docLen - length + 1);
    remove(context, offset, length);
}
 
Example 4
synchronized void returnPressed() {
    Document doc = getDocument();
    int len = doc.getLength();
    Segment segment = new Segment();
    try {
        doc.getText(outputMark, len - outputMark, segment);
    } catch(javax.swing.text.BadLocationException ignored) {
        ignored.printStackTrace();
    }
    if(segment.count > 0) {
        history.add(segment.toString());
    }
    historyIndex = history.size();
    inPipe.write(segment.array, segment.offset, segment.count);
    append("\n");
    outputMark = doc.getLength();
    inPipe.write("\n");
    inPipe.flush();
    console1.flush();
}
 
Example 5
Source Project: netbeans   File: CustomCodeView.java    License: Apache License 2.0 6 votes vote down vote up
private static int getLineCount(Document doc) {
    int length = doc.getLength();
    String text;
    int count = 0;
    try {
        text = doc.getText(0, length);
    } catch (BadLocationException ex) { // should not happen
        Exceptions.printStackTrace(ex);
        return -1;
    }
    for (int i=0; i < length; i++) {
        if (text.charAt(i) == '\n') {
            count++;
        }
    }
    return count;
}
 
Example 6
Source Project: netbeans   File: ModificationResult.java    License: Apache License 2.0 6 votes vote down vote up
private static void processDocumentLocked(Document doc, Difference diff) throws BadLocationException {
    switch (diff.getKind()) {
        case INSERT:
            doc.insertString(diff.getStartPosition().getOffset(), diff.getNewText(), null);
            break;
        case REMOVE:
            doc.remove(diff.getStartPosition().getOffset(), diff.getEndPosition().getOffset() - diff.getStartPosition().getOffset());
            break;
        case CHANGE: {
            // first insert the new content, THEN remove the old one. In situations where the content AFTER the
            // change is not writable this ordering allows to replace the content, but if we first delete, 
            // replacement cannot be inserted into the nonwritable area.
            int offs = diff.getStartPosition().getOffset();
            int removeLen = diff.getEndPosition().getOffset() - offs;
            
            // [NETBEANS-4270] Can't use "delta = diff.getNewText().length()".
            // doc.insertString may filter chars, e.g. '\r', and change length.
            int initialLength = doc.getLength();
            doc.insertString(offs, diff.getNewText(), null);
            int delta = doc.getLength() - initialLength;
            doc.remove(delta + offs, removeLen);
            break;
        }
    }
}
 
Example 7
Source Project: netbeans   File: DocumentUtilities.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get string representation of an offset for debugging purposes
 * in form "offset[line:column]". Both lines and columns start counting from 1
 * like in the editor's status bar. Tabs are expanded when counting the column.
 *
 * @param sb valid string builder to which text will be appended or null in which case
 *  the method itself will create a string builder and it will return it.
 * @param doc non-null document in which the offset is located.
 * @param offset offset in the document.
 * @return non-null string builder to which the description was added.
 * @since 1.27
 */
public static StringBuilder appendOffset(StringBuilder sb, Document doc, int offset) {
    if (sb == null) {
        sb = new StringBuilder(50);
    }
    sb.append(offset).append('[');
    if (offset < 0) { // Offset too low
        sb.append("<0");
    } else if (offset > doc.getLength() + 1) { // +1 for AbstractDocument-based docs
        sb.append(">").append(doc.getLength());
    } else { // Valid offset
        Element paragraphRoot = getParagraphRootElement(doc);
        int lineIndex = paragraphRoot.getElementIndex(offset);
        Element lineElem = paragraphRoot.getElement(lineIndex);
        sb.append(lineIndex + 1).append(':'); // Line
        sb.append(visualColumn(doc, lineElem.getStartOffset(), offset) + 1); // Column
    }
    sb.append(']');
    return sb;
}
 
Example 8
Source Project: netbeans   File: WordMatchTest.java    License: 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 9
@Override
public void actionPerformed(ActionEvent e) {
	JTextComponent target = getTextComponent(e);
	boolean beep = true;
	if ((target != null) && (target.isEditable())) {
		try {
			Document doc = target.getDocument();
			int ss = 0;
			int se = doc.getLength();

			if (ss != se) {
				doc.remove(ss, se - ss);
				beep = false;
			}
		} catch (BadLocationException bl) {
		}
	}
	if (beep) {
		UIManager.getLookAndFeel().provideErrorFeedback(target);
	}
}
 
Example 10
public Token tokenAtPos(Point lastPos) {
    Document d = getDocument();
    if (d instanceof SyntaxDocument) {
        SyntaxDocument sd = (SyntaxDocument) d;

        //correction of token last character
        int pos = viewToModel(lastPos);
        Rectangle r;
        try {
            r = modelToView(pos);
            if (r != null) {
                if (lastPos.x < r.x) {
                    pos--;
                }
            }
        } catch (BadLocationException ex) {
            //ignore
        }
        Token t = sd.getTokenAt(pos);

        //Correction of token of length 1 character
        if (pos > 0 && pos < d.getLength() - 1 && t != null && t.length == 1) {
            Token tprev = sd.getTokenAt(pos - 1);
            if (tprev == t) {
                t = sd.getTokenAt(pos + 1);
            }
        }

        return t;
    }
    return null;
}
 
Example 11
Source Project: FlatLaf   File: FlatCaret.java    License: Apache License 2.0 5 votes vote down vote up
protected void selectAllOnFocusGained() {
	JTextComponent c = getComponent();
	Document doc = c.getDocument();
	if( doc == null || !c.isEnabled() || !c.isEditable() )
		return;

	Object selectAllOnFocusPolicy = c.getClientProperty( SELECT_ALL_ON_FOCUS_POLICY );
	if( selectAllOnFocusPolicy == null )
		selectAllOnFocusPolicy = this.selectAllOnFocusPolicy;

	if( SELECT_ALL_ON_FOCUS_POLICY_NEVER.equals( selectAllOnFocusPolicy ) )
		return;

	if( !SELECT_ALL_ON_FOCUS_POLICY_ALWAYS.equals( selectAllOnFocusPolicy ) ) {
		// policy is "once" (or null or unknown)

		// was already focused?
		if( wasFocused )
			return;

		// check whether selection was modified before gaining focus
		int dot = getDot();
		int mark = getMark();
		if( dot != mark || dot != doc.getLength() )
			return;
	}

	// select all
	if( c instanceof JFormattedTextField ) {
		EventQueue.invokeLater( () -> {
			setDot( 0 );
			moveDot( doc.getLength() );
		} );
	} else {
		setDot( 0 );
		moveDot( doc.getLength() );
	}
}
 
Example 12
void update(DocumentEvent e) {
	try {
		Document doc = e.getDocument();
		int len = doc.getLength();
		String text = doc.getText(0, len);
		filePane.setFileName(XDMUtils.getFileName(text));
	} catch (Exception err) {
		Logger.log(err);
	}
}
 
Example 13
private boolean refactorToStyleSheet(ModificationResult modificationResult, RefactoringContext context) {
    Document extSheetDoc = GsfUtilities.getDocument(refactoring.getExternalSheet(), true);

    int insertOffset = extSheetDoc.getLength();
    int baseIndent = getPreviousLineIndent(extSheetDoc, insertOffset);

    return refactorToEmbeddedSection(modificationResult, context, refactoring.getExternalSheet(),
            insertOffset, baseIndent, null, null);
}
 
Example 14
Source Project: bigtable-sql   File: MessagePanel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Do the real appending of text to the message panel. The last message is always highlighted.
 * @todo Highlight not only the last message, but all messages from SQL statements which were run together.
 *
 * @param string	The String to be appended.
 * @param saSet		The SimpleAttributeSet to be used for for the string.
 */
private void append(String string, SimpleAttributeSet saSet)
{
	Document document = getStyledDocument();
	try
	{
        /////////////////////////////////////////////////////////////////////////////////
        // Checks if the former message should be highlighted in a 'history' color.
        if (document.getLength() >= _lastLength && null != _lastMessage)
		{
           SimpleAttributeSet historySaSet = _saSetHistoryBySaSet.get(_lastSASet);
           document.remove(_lastLength, _lastMessage.length());
           document.insertString(document.getLength(), _lastMessage, historySaSet);
		}
        //
        ///////////////////////////////////////////////////////////////////////////////////

        _lastLength = document.getLength();
		_lastMessage = string;
		_lastSASet = saSet;

		document.insertString(document.getLength(), string, saSet);
	}
	catch (BadLocationException ble)
	{
		s_log.error("Error appending text to MessagePanel document.", ble);
	}
}
 
Example 15
Source Project: java-swing-tips   File: MainPanel.java    License: MIT License 5 votes vote down vote up
@Override public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
  Document doc = fb.getDocument();
  int currentLength = doc.getLength();
  String currentContent = doc.getText(0, currentLength);
  String before = currentContent.substring(0, offset);
  String after = currentContent.substring(length + offset, currentLength);
  String newValue = before + Objects.toString(text, "") + after;
  checkInput(newValue, offset);
  fb.replace(offset, length, text, attrs);
}
 
Example 16
Source Project: netbeans   File: EditorProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
    protected JComponent getComponent() {
        JTextComponent text = getTextComponent();

        if (text == null) {
            return null;
        }
        if (Config.getDefault().isAsEditor()) {
            return getEditorComponent(text);
        }
        Document document = myEditor.getDocument();

        if (document == null) {
            return null;
        }
        int start;
        int end;

        if (Config.getDefault().isSelection()) {
            start = text.getSelectionStart();
            end = text.getSelectionEnd();
        }
        else {
            start = 0;
            end = document.getLength();
        }
        AttributedCharacterIterator[] iterators = getIterators(document, start, end);
//out();
//out("iterators: " + iterators);
//out();
        if (iterators != null) {
            return new ComponentDocument(iterators);
        }
        try {
            return new ComponentDocument(text.getText(start, end - start));
        }
        catch (BadLocationException e) {
            return null;
        }
    }
 
Example 17
Source Project: netbeans   File: JaxWsCodeGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public static void insertMethodCall(InvokeOperationCookie.TargetSourceType targetSourceType,
        DataObject dataObj, Lookup sourceNodeLookup) {

    EditorCookie cookie = dataObj.getCookie(EditorCookie.class);
    OperationNode opNode = sourceNodeLookup.lookup(OperationNode.class);
    boolean inJsp = InvokeOperationCookie.TargetSourceType.JSP == targetSourceType;
    Node portNode = opNode.getParentNode();
    Node serviceNode = portNode.getParentNode();
    addProjectReference(serviceNode, dataObj);
    final Document document;
    int position = -1;
    if (inJsp) {
        //TODO:
        //this should be handled differently, see issue 60609
        document = cookie.getDocument();
        try {
            String content = document.getText(0, document.getLength());
            position = content.lastIndexOf("</body>"); //NOI18N
            if (position < 0) {
                position = content.lastIndexOf("</html>"); //NOI18N
            }
            if (position >= 0) { //find where line begins
                while (position > 0 && content.charAt(position - 1) != '\n' && content.charAt(position - 1) != '\r') {
                    position--;
                }
            } else {
                position = document.getLength();
            }
        } catch (BadLocationException ble) {
            Exceptions.printStackTrace(ble);
        }
    } else {
        EditorCookie ec = dataObj.getCookie(EditorCookie.class);
        JEditorPane pane = ec.getOpenedPanes()[0];
        document = pane.getDocument();
        position = pane.getCaretPosition();
    }
    final int pos = position;
    insertMethod(document, pos, opNode);
}
 
Example 18
Source Project: netbeans   File: DrawEngineTest.java    License: Apache License 2.0 4 votes vote down vote up
private void checkViewToModelConsistency(JEditorPane jep) throws Exception {
        Document doc = jep.getDocument();
        
        assertTrue("Expecting BaseTextUI", jep.getUI() instanceof BaseTextUI);
        BaseTextUI btui = (BaseTextUI) jep.getUI();
        Insets margin = btui.getEditorUI().getTextMargin();
        int charWidth = btui.getEditorUI().defaultSpaceWidth;
        int charHeight = btui.getEditorUI().getLineHeight();

//        System.out.println("### charWidth = " + charWidth + ", charHeight = " + charHeight
//            + ", docLen = " + doc.getLength()
//            + ", jep.width = " + jep.getWidth()
//            + ", jep.height = " + jep.getHeight());
        
        Rectangle eodRectangle = null;
        Rectangle eolRectangle = null;
        for(int y = charHeight / 2 + margin.top; y < jep.getHeight(); y += charHeight) {
            if (eodRectangle == null) {
                eolRectangle = null;
            }
            for(int x = charWidth / 2 + margin.left; x < jep.getWidth(); x += charWidth) {
                Point p = new Point(x, y);

                // view-to-model translation
                int offset = jep.viewToModel(p);
                assertTrue("Invalid v2m translation: " + s(p) + " -> " + offset+ ", docLen = " + doc.getLength(),
                        offset >= 0 && offset <= doc.getLength());
                
                // model-to-view
                Rectangle r = jep.modelToView(offset);
                assertNotNull("No m2v translation: offset = " + offset + ", docLen = " + doc.getLength(), r);

                // check
                if (eodRectangle == null) {
                    boolean eod = offset == doc.getLength();
                    boolean eol = doc.getText(offset, 1).charAt(0) == '\n';
                    
                    if (eolRectangle == null) {
                        assertTrue("Inconsistent v2m-m2v translation, point = " + s(p) + " not within " + s(r)
                            + ", offset = " + offset + ", docLen = " + doc.getLength(), r.contains(p));
                        if (eol) {
                            eolRectangle = r;
                        }
                    } else {
                        assertEquals("Inconsistent v2m-m2v translation, for point = " + s(p) + " behing eol"
                            + ", offset = " + offset + ", docLen = " + doc.getLength(), eolRectangle, r);
                    }
                    
                    if (eod) {
                        eodRectangle = r;
                    }
                } else {
                    Point pointAtTheLastLine = new Point(Math.min(p.x, eolRectangle.x), eodRectangle.y);
                    assertTrue("Inconsistent v2m-m2v translation, for point = " + s(p)
                        + " behing eod, point at the last line " + s(pointAtTheLastLine) + " is outside of " + s(r)
                        + ", offset = " + offset + ", docLen = " + doc.getLength(), r.contains(pointAtTheLastLine));
                }
            }
        }
    }
 
Example 19
Source Project: netbeans   File: ParagraphViewChildren.java    License: Apache License 2.0 4 votes vote down vote up
private int viewToModelWithAmbiguousWrapLineCaretAdustment(
        double x, double y, IndexAndAlloc indexAndAlloc, Bias[] biasRet)
{
    final EditorView view = indexAndAlloc.viewOrPart;
    int ret = view.viewToModelChecked(x, y, indexAndAlloc.alloc, biasRet);
    /* NETBEANS-980: On wrap lines, the caret offset that corresponds to "right after the last
    character on the current wrap line" is ambiguous, because it can equivalently be interpreted
    as "right before the first character on the following wrap line" (because there is no explicit
    newline character to increment the offset around). The NetBeans EditorKit uses the latter
    interpretation when painting the caret and calculating visual positions via modelToView. Here,
    in viewToModel, we need to ensure that the returned offset always corresponds to a caret on
    the wrap line with the given Y position. Otherwise, keyboard actions such as UpAction,
    DownAction, and EndLineAction (in o.n.editor.BaseKit), or clicking the mouse in the area to
    the right of the end of the wrap line, will not work correctly.

    The approach here is to map the end of the wrap line to a caret position right _before_ the
    last character on the wrap line. Under word wrapping, said character will usually be a space
    (or a hyphen; see NETBEANS-977). This is the same approach as is taken in JTextArea with word
    wrapping enabled. The latter can be confirmed by entering a very long word in a word-wrapping
    JTextArea so that the last character on the wrap line is a letter rather than a space, and
    pressing the "End" key (Command+Right Arrow on Mac); the caret will end up right before the
    last character on the wrap line. Other approaches are possible, such as relying on the caret
    bias to differentiate the ambigous offsets, but the approach here seemed like the simplest
    one to implement. */
    if (isWrapped() && view.getLength() > 0 && ret >= view.getEndOffset()) {
        /* As a small improvement, avoid applying the adjustment on the very last wrap line of a
        paragraph, where it is not needed, and where the last character is likely to be something
        other than a space. This adjustment ensures that the caret ends up in the expected place
        if the user clicks on the right-hand half of the last character on the wrap line. (If the
        user clicks _beyond_ the last character of the last wrap line, hit testing would encounter
        a NewlineView instead of a HighlightsViewPart, which would yield the correct caret
        position in any case.) */
        boolean isLastWrapLineInParagraph = false;
        try {
            final Document doc = view.getDocument();
            if (ret < doc.getLength())
                isLastWrapLineInParagraph = view.getDocument().getText(ret, 1).equals("\n");
        } catch (BadLocationException e) {
            // Ignore.
        }
        if (!isLastWrapLineInParagraph)
            ret = view.getEndOffset() - 1;
    }
    return ret;
}
 
Example 20
Source Project: netbeans   File: GsfCompletionProvider.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param upToOffset If set, complete only up to the given caret offset, otherwise complete
 *   the full symbol at the offset
 */
private Env getCompletionEnvironment(ParserResult controller, boolean upToOffset)
    throws IOException {
    // If you invoke code completion while indexing is in progress, the
    // completion job (which stores the caret offset) will be delayed until
    // indexing is complete - potentially minutes later. When the job
    // is finally run we need to make sure the caret position is still valid. (93017)
    Document doc = controller.getSnapshot ().getSource ().getDocument (false);
    int length = doc != null ? doc.getLength() : (int)controller.getSnapshot ().getSource ().getFileObject().getSize();
    if (caretOffset > length) {
        caretOffset = length;
    }
    
    int offset = caretOffset;
    String prefix = null;

    // 
    // TODO - handle the upToOffset parameter
    // Look at the parse tree, and find the corresponding end node
    // offset...
    
    CodeCompletionHandler completer = getCompletable(controller);
    try {
        // TODO: use the completion helper to get the contxt
        if (completer != null && offset != -1) {
            prefix = completer.getPrefix(controller, offset, upToOffset);
        }
        if (prefix == null && doc != null) {
            int[] blk =
                org.netbeans.editor.Utilities.getIdentifierBlock((BaseDocument)doc,
                    offset);

            if (blk != null) {
                int start = blk[0];

                if (start < offset ) {
                    if (upToOffset) {
                        prefix = doc.getText(start, offset - start);
                    } else {
                        prefix = doc.getText(start, blk[1]-start);
                    }
                }
            }
        }
    } catch (BadLocationException ex) {
        ErrorManager.getDefault().notify(ex);
    }
    
    return new Env(offset, prefix, controller, completer);
}