Example usage for javax.swing.text Element getEndOffset

List of usage examples for javax.swing.text Element getEndOffset

Introduction

In this page you can find the example usage for javax.swing.text Element getEndOffset.

Prototype

public int getEndOffset();

Source Link

Document

Fetches the offset from the beginning of the document that this element ends at.

Usage

From source file:Main.java

public void reapplyStyles() {
    Element sectionElem = bodyElement.getElement(bodyElement.getElementCount() - 1);
    int paraCount = sectionElem.getElementCount();
    for (int i = 0; i < paraCount; i++) {
        Element e = sectionElem.getElement(i);
        int rangeStart = e.getStartOffset();
        int rangeEnd = e.getEndOffset();
        htmlDocument.setParagraphAttributes(rangeStart, rangeEnd - rangeStart, e.getAttributes(), true);
    }//w  w  w . java2s  .  co m
}

From source file:com.mirth.connect.client.ui.components.rsta.ac.js.MirthSourceCompletionProvider.java

@Override
public List<Completion> getCompletionsAt(JTextComponent tc, Point p) {
    Set<Completion> completions = new HashSet<Completion>();
    List<Completion> parentCompletions = super.getCompletionsAt(tc, p);
    if (CollectionUtils.isNotEmpty(parentCompletions)) {
        completions.addAll(parentCompletions);
    }// w  w  w .j  a  v a  2 s.  c  o m

    int offset = tc.viewToModel(p);
    if (offset < 0 || offset >= tc.getDocument().getLength()) {
        lastCompletionsAtText = null;
        lastParameterizedCompletionsAt = null;
        return new ArrayList<Completion>(completions);
    }

    Segment s = new Segment();
    Document doc = tc.getDocument();
    Element root = doc.getDefaultRootElement();
    int line = root.getElementIndex(offset);
    Element elem = root.getElement(line);
    int start = elem.getStartOffset();
    int end = elem.getEndOffset() - 1;

    try {

        doc.getText(start, end - start, s);

        // Get the valid chars before the specified offset.
        int startOffs = s.offset + (offset - start) - 1;
        while (startOffs >= s.offset && Character.isLetterOrDigit(s.array[startOffs])) {
            startOffs--;
        }

        // Get the valid chars at and after the specified offset.
        int endOffs = s.offset + (offset - start);
        while (endOffs < s.offset + s.count && Character.isLetterOrDigit(s.array[endOffs])) {
            endOffs++;
        }

        int len = endOffs - startOffs - 1;
        if (len <= 0) {
            lastParameterizedCompletionsAt = null;
            return new ArrayList<Completion>(completions);
        }
        String text = new String(s.array, startOffs + 1, len);

        if (text.equals(lastCompletionsAtText)) {
            if (CollectionUtils.isNotEmpty(lastParameterizedCompletionsAt)) {
                completions.addAll(lastParameterizedCompletionsAt);
            }
            return new ArrayList<Completion>(completions);
        }

        lastCompletionsAtText = text;
        lastParameterizedCompletionsAt = completionCache.getClassCompletions(tc, text);

        if (CollectionUtils.isNotEmpty(lastParameterizedCompletionsAt)) {
            completions.addAll(lastParameterizedCompletionsAt);
        }
        return new ArrayList<Completion>(completions);

    } catch (BadLocationException ble) {
        ble.printStackTrace(); // Never happens
    }

    lastCompletionsAtText = null;
    lastParameterizedCompletionsAt = null;

    return new ArrayList<Completion>(completions);
}

From source file:com.github.alexfalappa.nbspringboot.cfgprops.completion.CfgPropCompletionItem.java

@Override
public void defaultAction(JTextComponent jtc) {
    try {//  w w w.j  av  a2  s.c o m
        StyledDocument doc = (StyledDocument) jtc.getDocument();
        // calculate the amount of chars to remove (by default from property start up to caret position)
        int lenToRemove = caretOffset - propStartOffset;
        if (overwrite) {
            // NOTE: the editor removes by itself the word at caret when ctrl + enter is pressed
            // the document state here is different from when the completion was invoked thus we have to
            // find again the offset of the equal sign in the line
            Element lineElement = doc.getParagraphElement(caretOffset);
            String line = doc.getText(lineElement.getStartOffset(),
                    lineElement.getEndOffset() - lineElement.getStartOffset());
            int equalSignIndex = line.indexOf('=');
            if (equalSignIndex >= 0) {
                // from property start to equal sign
                lenToRemove = lineElement.getStartOffset() + equalSignIndex - propStartOffset;
            } else {
                // from property start to end of line (except line terminator)
                lenToRemove = lineElement.getEndOffset() - 1 - propStartOffset;
            }
        }
        // remove characters from the property name start offset
        doc.remove(propStartOffset, lenToRemove);
        doc.insertString(propStartOffset, getText(), null);
        // close the code completion box
        Completion.get().hideAll();
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:au.org.ala.delta.ui.rtf.RTFWriter.java

private void writeElement(Element element) throws BadLocationException, IOException {
    writeElement(element, element.getStartOffset(), element.getEndOffset() - element.getStartOffset());
}

From source file:com.hexidec.ekit.component.ExtendedHTMLDocument.java

@Override
public void setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace) {
    for (HTMLDocumentBehavior b : behaviors) {
        s = b.beforeSetParagraphAttributes(this, offset, length, s, replace);
    }//from w  ww  .j  ava 2  s .  c  om

    try {
        writeLock();
        // Make sure we send out a change for the length of the paragraph.
        int end = Math.min(offset + length, getLength());
        Element e = getParagraphElement(offset);
        offset = e.getStartOffset();
        e = getParagraphElement(end);
        length = Math.max(0, e.getEndOffset() - offset);
        DefaultDocumentEvent changes = new DefaultDocumentEvent(offset, length, DocumentEvent.EventType.CHANGE);
        AttributeSet sCopy = s.copyAttributes();
        int lastEnd = Integer.MAX_VALUE;
        for (int pos = offset; pos <= end; pos = lastEnd) {
            Element paragraph = getParagraphElement(pos);
            if (lastEnd == paragraph.getEndOffset()) {
                lastEnd++;
            } else {
                lastEnd = paragraph.getEndOffset();
            }
            MutableAttributeSet attr = (MutableAttributeSet) paragraph.getAttributes();
            changes.addEdit(new AttributeUndoableEdit(paragraph, sCopy, replace));
            if (replace) {
                attr.removeAttributes(attr);
            }

            DocumentUtil.copyAllAttributesRemovingMarked(attr, s);
        }
        changes.end();
        fireChangedUpdate(changes);
        fireUndoableEditUpdate(new UndoableEditEvent(this, changes));
    } finally {
        writeUnlock();
    }
}

From source file:com.hexidec.ekit.component.ExtendedHTMLDocument.java

public void replaceAttributes(Element e, AttributeSet a, Tag tag) {
    if ((e != null) && (a != null)) {
        try {/*from  www.j a v  a 2 s . co m*/
            writeLock();
            int start = e.getStartOffset();
            DefaultDocumentEvent changes = new DefaultDocumentEvent(start, e.getEndOffset() - start,
                    DocumentEvent.EventType.CHANGE);
            AttributeSet sCopy = a.copyAttributes();
            changes.addEdit(new AttributeUndoableEdit(e, sCopy, false));
            MutableAttributeSet attr = (MutableAttributeSet) e.getAttributes();
            Enumeration aNames = attr.getAttributeNames();
            Object value;
            Object aName;
            while (aNames.hasMoreElements()) {
                aName = aNames.nextElement();
                value = attr.getAttribute(aName);
                if (value != null && !value.toString().equalsIgnoreCase(tag.toString())) {
                    attr.removeAttribute(aName);
                }
            }
            attr.addAttributes(a);
            changes.end();
            fireChangedUpdate(changes);
            fireUndoableEditUpdate(new UndoableEditEvent(this, changes));
        } finally {
            writeUnlock();
        }
    }
}

From source file:net.sf.jasperreports.engine.util.JEditorPaneRtfMarkupProcessor.java

@Override
public String convert(String srcText) {
    JEditorPane editorPane = new JEditorPane("text/rtf", srcText);
    editorPane.setEditable(false);//from  w  w  w.  j av a 2s .  com

    List<Element> elements = new ArrayList<Element>();

    Document document = editorPane.getDocument();

    Element root = document.getDefaultRootElement();
    if (root != null) {
        addElements(elements, root);
    }

    String chunk = null;
    Element element = null;
    int startOffset = 0;
    int endOffset = 0;

    JRStyledText styledText = new JRStyledText();
    styledText.setGlobalAttributes(new HashMap<Attribute, Object>());
    for (int i = 0; i < elements.size(); i++) {
        if (chunk != null) {
            styledText.append(chunk);
            styledText.addRun(
                    new JRStyledText.Run(getAttributes(element.getAttributes()), startOffset, endOffset));
        }

        chunk = null;
        element = elements.get(i);
        startOffset = element.getStartOffset();
        endOffset = element.getEndOffset();

        try {
            chunk = document.getText(startOffset, endOffset - startOffset);
        } catch (BadLocationException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error converting markup.", e);
            }
        }

    }

    if (chunk != null && !"\n".equals(chunk)) {
        styledText.append(chunk);
        styledText.addRun(new JRStyledText.Run(getAttributes(element.getAttributes()), startOffset, endOffset));
    }

    return JRStyledTextParser.getInstance().write(styledText);
}

From source file:forge.screens.deckeditor.DeckImport.java

private void readInput() {
    this.tokens.clear();
    final ElementIterator it = new ElementIterator(this.txtInput.getDocument().getDefaultRootElement());
    Element e;

    DeckRecognizer recognizer = new DeckRecognizer(newEditionCheck.isSelected(), onlyCoreExpCheck.isSelected(),
            FModel.getMagicDb().getCommonCards());
    if (dateTimeCheck.isSelected()) {
        recognizer.setDateConstraint(monthDropdown.getSelectedIndex(),
                (Integer) yearDropdown.getSelectedItem());
    }//from   ww  w .  j  a va  2  s . c  om
    while ((e = it.next()) != null) {
        if (!e.isLeaf()) {
            continue;
        }
        final int rangeStart = e.getStartOffset();
        final int rangeEnd = e.getEndOffset();
        try {
            final String line = this.txtInput.getText(rangeStart, rangeEnd - rangeStart);
            this.tokens.add(recognizer.recognizeLine(line));
        } catch (final BadLocationException ex) {
        }
    }
}

From source file:EditorPaneExample16.java

public Heading getNextHeading(Document doc, ElementIterator iter) {
    Element elem;//from w  w  w.ja v a  2  s.c om

    while ((elem = iter.next()) != null) {
        AttributeSet attrs = elem.getAttributes();
        Object type = attrs.getAttribute(StyleConstants.NameAttribute);
        int level = getHeadingLevel(type);
        if (level > 0) {
            // It is a heading - get the text
            String headingText = "";
            int count = elem.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = elem.getElement(i);
                AttributeSet cattrs = child.getAttributes();
                if (cattrs.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    try {
                        int offset = child.getStartOffset();
                        headingText += doc.getText(offset, child.getEndOffset() - offset);
                    } catch (BadLocationException e) {
                    }
                }
            }
            headingText = headingText.trim();
            return new Heading(headingText, level, elem.getStartOffset());
        }
    }
    return null;
}

From source file:net.sf.jasperreports.engine.util.JEditorPaneHtmlMarkupProcessor.java

@Override
public String convert(String srcText) {
    JEditorPane editorPane = new JEditorPane("text/html", srcText);
    editorPane.setEditable(false);//from   w w  w. j a v a 2s.  co m

    List<Element> elements = new ArrayList<Element>();

    Document document = editorPane.getDocument();

    Element root = document.getDefaultRootElement();
    if (root != null) {
        addElements(elements, root);
    }

    int startOffset = 0;
    int endOffset = 0;
    int crtOffset = 0;
    String chunk = null;
    JRPrintHyperlink hyperlink = null;
    Element element = null;
    Element parent = null;
    boolean bodyOccurred = false;
    int[] orderedListIndex = new int[elements.size()];
    String whitespace = "    ";
    String[] whitespaces = new String[elements.size()];
    for (int i = 0; i < elements.size(); i++) {
        whitespaces[i] = "";
    }

    StringBuilder text = new StringBuilder();
    List<JRStyledText.Run> styleRuns = new ArrayList<>();

    for (int i = 0; i < elements.size(); i++) {
        if (bodyOccurred && chunk != null) {
            text.append(chunk);
            Map<Attribute, Object> styleAttributes = getAttributes(element.getAttributes());
            if (hyperlink != null) {
                styleAttributes.put(JRTextAttribute.HYPERLINK, hyperlink);
                hyperlink = null;
            }
            if (!styleAttributes.isEmpty()) {
                styleRuns.add(
                        new JRStyledText.Run(styleAttributes, startOffset + crtOffset, endOffset + crtOffset));
            }
        }

        chunk = null;
        element = elements.get(i);
        parent = element.getParentElement();
        startOffset = element.getStartOffset();
        endOffset = element.getEndOffset();
        AttributeSet attrs = element.getAttributes();

        Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
        Object object = (elementName != null) ? null : attrs.getAttribute(StyleConstants.NameAttribute);
        if (object instanceof HTML.Tag) {

            HTML.Tag htmlTag = (HTML.Tag) object;
            if (htmlTag == Tag.BODY) {
                bodyOccurred = true;
                crtOffset = -startOffset;
            } else if (htmlTag == Tag.BR) {
                chunk = "\n";
            } else if (htmlTag == Tag.OL) {
                orderedListIndex[i] = 0;
                String parentName = parent.getName().toLowerCase();
                whitespaces[i] = whitespaces[elements.indexOf(parent)] + whitespace;
                if (parentName.equals("li")) {
                    chunk = "";
                } else {
                    chunk = "\n";
                    ++crtOffset;
                }
            } else if (htmlTag == Tag.UL) {
                whitespaces[i] = whitespaces[elements.indexOf(parent)] + whitespace;

                String parentName = parent.getName().toLowerCase();
                if (parentName.equals("li")) {
                    chunk = "";
                } else {
                    chunk = "\n";
                    ++crtOffset;
                }

            } else if (htmlTag == Tag.LI) {

                whitespaces[i] = whitespaces[elements.indexOf(parent)];
                if (element.getElement(0) != null && (element.getElement(0).getName().toLowerCase().equals("ol")
                        || element.getElement(0).getName().toLowerCase().equals("ul"))) {
                    chunk = "";
                } else if (parent.getName().equals("ol")) {
                    int index = elements.indexOf(parent);
                    Object type = parent.getAttributes().getAttribute(HTML.Attribute.TYPE);
                    Object startObject = parent.getAttributes().getAttribute(HTML.Attribute.START);
                    int start = startObject == null ? 0
                            : Math.max(0, Integer.valueOf(startObject.toString()) - 1);
                    String suffix = "";

                    ++orderedListIndex[index];

                    if (type != null) {
                        switch (((String) type).charAt(0)) {
                        case 'A':
                            suffix = getOLBulletChars(orderedListIndex[index] + start, true);
                            break;
                        case 'a':
                            suffix = getOLBulletChars(orderedListIndex[index] + start, false);
                            break;
                        case 'I':
                            suffix = JRStringUtil.getRomanNumeral(orderedListIndex[index] + start, true);
                            break;
                        case 'i':
                            suffix = JRStringUtil.getRomanNumeral(orderedListIndex[index] + start, false);
                            break;
                        case '1':
                        default:
                            suffix = String.valueOf(orderedListIndex[index] + start);
                            break;
                        }
                    } else {
                        suffix += orderedListIndex[index] + start;
                    }
                    chunk = whitespaces[index] + suffix + DEFAULT_BULLET_SEPARATOR + "  ";

                } else {
                    chunk = whitespaces[elements.indexOf(parent)] + DEFAULT_BULLET_CHARACTER + "  ";
                }
                crtOffset += chunk.length();
            } else if (element instanceof LeafElement) {
                if (element instanceof RunElement) {
                    RunElement runElement = (RunElement) element;
                    AttributeSet attrSet = (AttributeSet) runElement.getAttribute(Tag.A);
                    if (attrSet != null) {
                        hyperlink = new JRBasePrintHyperlink();
                        hyperlink.setHyperlinkType(HyperlinkTypeEnum.REFERENCE);
                        hyperlink.setHyperlinkReference((String) attrSet.getAttribute(HTML.Attribute.HREF));
                        hyperlink.setLinkTarget((String) attrSet.getAttribute(HTML.Attribute.TARGET));
                    }
                }
                try {
                    chunk = document.getText(startOffset, endOffset - startOffset);
                } catch (BadLocationException e) {
                    if (log.isDebugEnabled()) {
                        log.debug("Error converting markup.", e);
                    }
                }
            }
        }
    }

    if (chunk != null) {
        if (!"\n".equals(chunk)) {
            text.append(chunk);
            Map<Attribute, Object> styleAttributes = getAttributes(element.getAttributes());
            if (hyperlink != null) {
                styleAttributes.put(JRTextAttribute.HYPERLINK, hyperlink);
                hyperlink = null;
            }
            if (!styleAttributes.isEmpty()) {
                styleRuns.add(
                        new JRStyledText.Run(styleAttributes, startOffset + crtOffset, endOffset + crtOffset));
            }
        } else {
            //final newline, not appending
            //check if there's any style run that would have covered it, that can happen if there's a <li> tag with style
            int length = text.length();
            for (ListIterator<JRStyledText.Run> it = styleRuns.listIterator(); it.hasNext();) {
                JRStyledText.Run run = it.next();
                //only looking at runs that end at the position where the newline should have been
                //we don't want to hide bugs in which runs that span after the text length are created
                if (run.endIndex == length + 1) {
                    if (run.startIndex < run.endIndex - 1) {
                        it.set(new JRStyledText.Run(run.attributes, run.startIndex, run.endIndex - 1));
                    } else {
                        it.remove();
                    }
                }
            }
        }
    }

    JRStyledText styledText = new JRStyledText(null, text.toString());
    for (JRStyledText.Run run : styleRuns) {
        styledText.addRun(run);
    }
    styledText.setGlobalAttributes(new HashMap<Attribute, Object>());

    return JRStyledTextParser.getInstance().write(styledText);
}