Java Code Examples for javax.swing.text.Element#getElement()

The following examples show how to use javax.swing.text.Element#getElement() . 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: JEditTextArea.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns the offset where the selection ends on the specified line.
 */
public int getSelectionEnd(int line) {
	if (line == selectionEndLine) {
		return selectionEnd;
	} else if (rectSelect) {
		Element map = document.getDefaultRootElement();
		int end = selectionEnd - map.getElement(selectionEndLine).getStartOffset();

		Element lineElement = map.getElement(line);
		int lineStart = lineElement.getStartOffset();
		int lineEnd = lineElement.getEndOffset() - 1;
		return Math.min(lineEnd, lineStart + end);
	} else {
		return getLineEndOffset(line) - 1;
	}
}
 
Example 2
Source File: DocumentUtilities.java    From netbeans with 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 3
Source File: FSwingHtml.java    From pra with MIT License 6 votes vote down vote up
public static String getAllText(Element e){
	try {
     StringBuffer sb = new StringBuffer();
     int count = e.getElementCount();
     for (int i = 0; i < count; i++) {
       Element c = e.getElement(i);
       AttributeSet abC = c.getAttributes();
       if (abC.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) 
         sb.append(getText(c));
     }
     return sb.toString();
	} catch (Exception er) {
		er.printStackTrace();
	}
	return null;
}
 
Example 4
Source File: TrailingWhitespaceRemoveTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static void checkNoTrailingWhitespace(Document doc) {
    Element lineRoot = DocumentUtilities.getParagraphRootElement(doc);
    CharSequence docText = DocumentUtilities.getText(doc);
    for (int i = 0; i < lineRoot.getElementCount(); i++) {
        Element lineElem = lineRoot.getElement(i);
        int lineLastOffset = lineElem.getEndOffset() - 2;
        if (lineLastOffset >= lineElem.getStartOffset()) { // At least one non newline char
            switch (docText.charAt(lineLastOffset)) {
                case ' ':
                case '\t':
                    throw new IllegalStateException("Trailing whitespace exists at lineIndex=" + i + // NOI18N
                            ", lineStartOffset=" + lineElem.getStartOffset() + // NOI18N
                            ", lineEndOffset=" + lineElem.getEndOffset() + // NOI18N
                            '\n' + dumpLines(null, doc));
            }
        }
    }
}
 
Example 5
Source File: TrailingWhitespaceRemoveTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void removeTrailingWhitespace(Document doc) throws Exception {
    Element lineRoot = DocumentUtilities.getParagraphRootElement(doc);
    CharSequence docText = DocumentUtilities.getText(doc);
    int lineCount = lineRoot.getElementCount();
    for (int i = 0; i < lineCount; i++) {
        Element lineElem = lineRoot.getElement(i);
        int lineStartOffset = lineElem.getStartOffset();
        int lineLastOffset = lineElem.getEndOffset() - 1;
        int offset;
        for (offset = lineLastOffset - 1; offset >= lineStartOffset; offset--) {
            char c = docText.charAt(offset);
            // Currently only remove ' ' and '\t' - may be revised
            if (c != ' ' && c != '\t') {
                break;
            }
        }
        // Increase offset (either below lineStartOffset or on non-white char)
        offset++;
        if (offset < lineLastOffset) {
            doc.remove(offset, lineLastOffset - offset);
        }
    }
}
 
Example 6
Source File: SyntaxDocument.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Reparses the document, by passing the specified lines to the token marker. This should be
 * called after a large quantity of text is first inserted.
 * 
 * @param start
 *            The first line to parse
 * @param len
 *            The number of lines, after the first one to parse
 */
public void tokenizeLines(int start, int len) {
	if (tokenMarker == null || !tokenMarker.supportsMultilineTokens()) {
		return;
	}

	Segment lineSegment = new Segment();
	Element map = getDefaultRootElement();

	len += start;

	try {
		for (int i = start; i < len; i++) {
			Element lineElement = map.getElement(i);
			int lineStart = lineElement.getStartOffset();
			getText(lineStart, lineElement.getEndOffset() - lineStart - 1, lineSegment);
			tokenMarker.markTokens(lineSegment, i);
		}
	} catch (BadLocationException bl) {
		bl.printStackTrace();
	}
}
 
Example 7
Source File: ElementTreePanel.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a TreePath to the element at <code>position</code>.
 */
protected TreePath getPathForIndex(int position, Object root,
        Element rootElement) {
    TreePath path = new TreePath(root);
    Element child = rootElement.getElement(rootElement.getElementIndex(
            position));

    path = path.pathByAddingChild(rootElement);
    path = path.pathByAddingChild(child);
    while (!child.isLeaf()) {
        child = child.getElement(child.getElementIndex(position));
        path = path.pathByAddingChild(child);
    }
    return path;
}
 
Example 8
Source File: LimitLinesDocumentListener.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
private void removeFromStart(Document document, Element root) {
	Element line = root.getElement(0);
	int end = line.getEndOffset();

	try {
		document.remove(0, end);
	} catch (BadLocationException ble) {
		System.out.println(ble);
	}
}
 
Example 9
Source File: JEditorPaneRtfMarkupProcessor.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 
 */
protected void addElements(List<Element> elements, Element element) 
{
	if(element instanceof LeafElement)
	{
		elements.add(element);
	}
	for(int i = 0; i < element.getElementCount(); i++)
	{
		Element child = element.getElement(i);
		addElements(elements, child);
	}
}
 
Example 10
Source File: CAccessibleText.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static int[] getRangeForLine(final Accessible a, final int lineIndex) {
    Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return null;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();
    final Element line = root.getElement(lineIndex);
    if (line == null) return null;

    return new int[] { line.getStartOffset(), line.getEndOffset() };
}
 
Example 11
Source File: TextLineNumber.java    From RepDev with GNU General Public License v3.0 5 votes vote down vote up
protected String getTextLineNumber(int rowStartOffset)
{
	Element root = component.getDocument().getDefaultRootElement();
	int index = root.getElementIndex( rowStartOffset );
	Element line = root.getElement( index );

	if (line.getStartOffset() == rowStartOffset)
		return String.valueOf(index + 1);
	else
		return "";
}
 
Example 12
Source File: ElementTreePanel.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a TreePath to the element at <code>position</code>.
 */
protected TreePath getPathForIndex(int position, Object root,
        Element rootElement) {
    TreePath path = new TreePath(root);
    Element child = rootElement.getElement(rootElement.getElementIndex(
            position));

    path = path.pathByAddingChild(rootElement);
    path = path.pathByAddingChild(child);
    while (!child.isLeaf()) {
        child = child.getElement(child.getElementIndex(position));
        path = path.pathByAddingChild(child);
    }
    return path;
}
 
Example 13
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 14
Source File: CAccessibleText.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static int[] getRangeForLine(final Accessible a, final int lineIndex) {
    Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return null;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();
    final Element line = root.getElement(lineIndex);
    if (line == null) return null;

    return new int[] { line.getStartOffset(), line.getEndOffset() };
}
 
Example 15
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
protected void traverseElementById(Element element) {
  if (element.isLeaf()) {
    checkId(element);
  } else {
    for (int i = 0; i < element.getElementCount(); i++) {
      Element child = element.getElement(i);
      checkId(child);
      if (!child.isLeaf()) {
        traverseElementById(child);
      }
    }
  }
}
 
Example 16
Source File: FixLineSyntaxState.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static void invalidateAllSyntaxStateInfos(BaseDocument doc) {
    Element lineRoot = getLineRoot(doc);
    int elemCount = lineRoot.getElementCount();
    for (int i = elemCount - 1; i >= 0; i--) {
        LineElement line = (LineElement) lineRoot.getElement(i);
        line.legacySetAttributesObject(null);
    }
}
 
Example 17
Source File: DrawEngineDocView.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected @Override View createCustomView(ViewFactory f,
int startOffset, int maxEndOffset, int elementIndex) {
    if (elementIndex == -1) {
        throw new IllegalStateException("Need underlying line element structure"); // NOI18N
    }
    
    View view = null;

    Element elem = getElement();
    Element lineElem = elem.getElement(elementIndex);
    view = f.create(lineElem);
    return view;
}
 
Example 18
Source File: CAccessibleText.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static int[] getRangeForLine(final Accessible a, final int lineIndex) {
    Accessible sa = CAccessible.getSwingAccessible(a);
    if (!(sa instanceof JTextComponent)) return null;

    final JTextComponent jc = (JTextComponent) sa;
    final Element root = jc.getDocument().getDefaultRootElement();
    final Element line = root.getElement(lineIndex);
    if (line == null) return null;

    return new int[] { line.getStartOffset(), line.getEndOffset() };
}
 
Example 19
Source File: ElementTreePanel.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a TreePath to the element at <code>position</code>.
 */
protected TreePath getPathForIndex(int position, Object root,
        Element rootElement) {
    TreePath path = new TreePath(root);
    Element child = rootElement.getElement(rootElement.getElementIndex(
            position));

    path = path.pathByAddingChild(rootElement);
    path = path.pathByAddingChild(child);
    while (!child.isLeaf()) {
        child = child.getElement(child.getElementIndex(position));
        path = path.pathByAddingChild(child);
    }
    return path;
}
 
Example 20
Source File: GetJavaWord.java    From netbeans with Apache License 2.0 4 votes vote down vote up
static String forPane(JEditorPane p) {
    if (p == null) return null;
 
    String selection = p.getSelectedText ();
 
    if ( selection != null && selection.length() > 0 ) {
        return selection;
    } else {
 
        // try to guess which word is underneath the caret's dot.
 
        Document doc = p.getDocument();
        Element lineRoot;
 
        if (doc instanceof StyledDocument) {
            lineRoot = NbDocument.findLineRootElement((StyledDocument)doc);
        } else {
            lineRoot = doc.getDefaultRootElement();
        }
        int dot = p.getCaret().getDot();
        Element line = lineRoot.getElement(lineRoot.getElementIndex(dot));
 
        if (line == null) return null;
 
        String text = null;
        try {
            text = doc.getText(line.getStartOffset(),
                line.getEndOffset() - line.getStartOffset());
        } catch (BadLocationException e) {
            return null;
        }
        
        if ( text == null )
            return null;
        int pos = dot - line.getStartOffset();

        if ( pos < 0 || pos >= text.length() )
            return null;

        int bix, eix;

        for( bix = Character.isJavaIdentifierPart( text.charAt( pos ) ) ? pos : pos - 1;
                bix >= 0 && Character.isJavaIdentifierPart( text.charAt( bix ) ); bix-- );
        for( eix = pos; eix < text.length() && Character.isJavaIdentifierPart( text.charAt( eix )); eix++ );

        return bix == eix ? null : text.substring( bix + 1, eix  );
    }
}