Example usage for javax.swing.text Element getStartOffset

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

Introduction

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

Prototype

public int getStartOffset();

Source Link

Document

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

Usage

From source file:com.keevosh.springframework.boot.netbeans.SpringBootConfigurationCompletionProvider.java

static int getRowFirstNonWhite(StyledDocument doc, int offset) throws BadLocationException {
    Element lineElement = doc.getParagraphElement(offset);
    int start = lineElement.getStartOffset();
    while (start + 1 < lineElement.getEndOffset()) {
        try {//from   w w w.j ava2s.  c om
            if (doc.getText(start, 1).charAt(0) != ' ') {
                break;
            }
        } catch (BadLocationException ex) {
            throw (BadLocationException) new BadLocationException(
                    "calling getText(" + start + ", " + (start + 1) + ") on doc of length: " + doc.getLength(),
                    start).initCause(ex);
        }
        start++;
    }
    return start;
}

From source file:Main.java

/**
 * Prints a <code>Document</code> using a monospaced font, word wrapping on
 * the characters ' ', '\t', '\n', ',', '.', and ';'.  This method is
 * expected to be called from Printable 'print(Graphics g)' functions.
 *
 * @param g The graphics context to write to.
 * @param doc The <code>javax.swing.text.Document</code> to print.
 * @param fontSize the point size to use for the monospaced font.
 * @param pageIndex The page number to print.
 * @param pageFormat The format to print the page with.
 * @param tabSize The number of spaces to expand tabs to.
 *
 * @see #printDocumentMonospaced/* ww w.j  a v a2s .com*/
 */
public static int printDocumentMonospacedWordWrap(Graphics g, Document doc, int fontSize, int pageIndex,
        PageFormat pageFormat, int tabSize) {

    g.setColor(Color.BLACK);
    g.setFont(new Font("Monospaced", Font.PLAIN, fontSize));

    // Initialize our static variables (these are used by our tab expander below).
    tabSizeInSpaces = tabSize;
    fm = g.getFontMetrics();

    // Create our tab expander.
    //RPrintTabExpander tabExpander = new RPrintTabExpander();

    // Get width and height of characters in this monospaced font.
    int fontWidth = fm.charWidth('w'); // Any character will do here, since font is monospaced.
    int fontHeight = fm.getHeight();

    int MAX_CHARS_PER_LINE = (int) pageFormat.getImageableWidth() / fontWidth;
    int MAX_LINES_PER_PAGE = (int) pageFormat.getImageableHeight() / fontHeight;

    final int STARTING_LINE_NUMBER = MAX_LINES_PER_PAGE * pageIndex;

    // The (x,y) coordinate to print at (in pixels, not characters).
    // Since y is the baseline of where we'll start printing (not the top-left
    // corner), we offset it by the font's ascent ( + 1 just for good measure).
    xOffset = (int) pageFormat.getImageableX();
    int y = (int) pageFormat.getImageableY() + fm.getAscent() + 1;

    // A counter to keep track of the number of lines that WOULD HAVE been
    // printed if we were printing all lines.
    int numPrintedLines = 0;

    // Keep going while there are more lines in the document.
    currentDocLineNumber = 0; // The line number of the document we're currently on.
    rootElement = doc.getDefaultRootElement(); // To shorten accesses in our loop.
    numDocLines = rootElement.getElementCount(); // The number of lines in our document.
    while (currentDocLineNumber < numDocLines) {

        // Get the line we are going to print.
        String curLineString;
        Element currentLine = rootElement.getElement(currentDocLineNumber);
        int startOffs = currentLine.getStartOffset();
        try {
            curLineString = doc.getText(startOffs, currentLine.getEndOffset() - startOffs);
        } catch (BadLocationException ble) { // Never happens
            ble.printStackTrace();
            return Printable.NO_SUCH_PAGE;
        }

        // Remove newlines, because they end up as boxes if you don't; this is a monospaced font.
        curLineString = curLineString.replaceAll("\n", "");

        // Replace tabs with how many spaces they should be.
        if (tabSizeInSpaces == 0) {
            curLineString = curLineString.replaceAll("\t", "");
        } else {
            int tabIndex = curLineString.indexOf('\t');
            while (tabIndex > -1) {
                int spacesNeeded = tabSizeInSpaces - (tabIndex % tabSizeInSpaces);
                String replacementString = "";
                for (int i = 0; i < spacesNeeded; i++)
                    replacementString += ' ';
                // Note that "\t" is actually a regex for this method.
                curLineString = curLineString.replaceFirst("\t", replacementString);
                tabIndex = curLineString.indexOf('\t');
            }
        }

        // If this document line is too long to fit on one printed line on the page,
        // break it up into multpile lines.
        while (curLineString.length() > MAX_CHARS_PER_LINE) {

            int breakPoint = getLineBreakPoint(curLineString, MAX_CHARS_PER_LINE) + 1;

            numPrintedLines++;
            if (numPrintedLines > STARTING_LINE_NUMBER) {
                g.drawString(curLineString.substring(0, breakPoint), xOffset, y);
                y += fontHeight;
                if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE)
                    return Printable.PAGE_EXISTS;
            }

            curLineString = curLineString.substring(breakPoint, curLineString.length());

        }

        currentDocLineNumber += 1; // We have printed one more line from the document.

        numPrintedLines++;
        if (numPrintedLines > STARTING_LINE_NUMBER) {
            g.drawString(curLineString, xOffset, y);
            y += fontHeight;
            if (numPrintedLines == STARTING_LINE_NUMBER + MAX_LINES_PER_PAGE)
                return Printable.PAGE_EXISTS;
        }

    }

    // Now, the whole document has been "printed."  Decide if this page had any text on it or not.
    if (numPrintedLines > STARTING_LINE_NUMBER)
        return Printable.PAGE_EXISTS;
    return Printable.NO_SUCH_PAGE;

}

From source file:ShowHTMLViews.java

public static void displayElement(Document doc, Element e, int indent, PrintStream out) {
    for (int i = 0; i < indent; i++) {
        out.print("  ");
    }/*  w  ww .  j  av  a2 s. com*/
    out.println("===== Element Class: " + getShortClassName(e.getClass()));
    for (int i = 0; i < indent; i++) {
        out.print("  ");
    }
    int startOffset = e.getStartOffset();
    int endOffset = e.getEndOffset();
    out.println("Offsets [" + startOffset + ", " + endOffset + "]");
    AttributeSet a = e.getAttributes();
    Enumeration x = a.getAttributeNames();
    for (int i = 0; i < indent; i++) {
        out.print("  ");
    }
    out.println("ATTRIBUTES:");
    while (x.hasMoreElements()) {
        for (int i = 0; i < indent; i++) {
            out.print("  ");
        }
        Object attr = x.nextElement();
        out.println(" (" + attr + ", " + a.getAttribute(attr) + ")" + " [" + getShortClassName(attr.getClass())
                + "/" + getShortClassName(a.getAttribute(attr).getClass()) + "] ");
    }

    // Display the text for a leaf element
    if (e.isLeaf()) {
        try {
            String str = doc.getText(startOffset, endOffset - startOffset);
            if (str.length() > 40) {
                str = str.substring(0, 40);
            }
            if (str.length() > 0) {
                for (int i = 0; i < indent; i++) {
                    out.print("  ");
                }
                out.println("[" + str + "]");
            }
        } catch (BadLocationException ex) {
        }
    }

    // Display child elements
    int count = e.getElementCount();
    for (int i = 0; i < count; i++) {
        displayElement(doc, e.getElement(i), indent + 1, out);
    }
}

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 .  jav  a2 s.  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  a2s  . co  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 {/*ww  w.  j av a 2 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:com.github.alexfalappa.nbspringboot.cfgprops.completion.CfgPropsCompletionProvider.java

@Override
public CompletionTask createTask(int queryType, JTextComponent jtc) {
    if (queryType != CompletionProvider.COMPLETION_QUERY_TYPE) {
        return null;
    }//from   w  ww.  j  av  a 2 s  .c  om
    Project prj = Utilities.actionsGlobalContext().lookup(Project.class);
    if (prj == null) {
        return null;
    }
    logger.log(FINE, "Completing within context of prj {0}",
            FileUtil.getFileDisplayName(prj.getProjectDirectory()));
    final SpringBootService sbs = prj.getLookup().lookup(SpringBootService.class);
    if (sbs == null) {
        return null;
    }
    logger.fine("Creating completion task");
    return new AsyncCompletionTask(new AsyncCompletionQuery() {
        @Override
        protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) {
            final StyledDocument styDoc = (StyledDocument) document;
            Element lineElement = styDoc.getParagraphElement(caretOffset);
            int lineStartOffset = lineElement.getStartOffset();
            try {
                String lineToCaret = styDoc.getText(lineStartOffset, caretOffset - lineStartOffset);
                logger.log(FINER, "Completion on line to caret: {0}", lineToCaret);
                if (!lineToCaret.contains("#")) {
                    String[] parts = lineToCaret.split("=");
                    //property name extraction from part before =
                    Matcher matcher = PATTERN_PROP_NAME.matcher(parts[0]);
                    String propPrefix = null;
                    int propPrefixOffset = 0;
                    while (matcher.find()) {
                        propPrefix = matcher.group();
                        propPrefixOffset = matcher.start();
                    }
                    // check which kind of completion
                    final int equalSignOffset = lineToCaret.indexOf('=');
                    if (parts.length > 1) {
                        //value completion
                        String valPrefix = parts[1].trim();
                        completePropValue(sbs, completionResultSet, propPrefix, valPrefix,
                                lineStartOffset + lineToCaret.indexOf(valPrefix, equalSignOffset), caretOffset);
                    } else if (equalSignOffset >= 0) {
                        //value completion with empty filter
                        completePropValue(sbs, completionResultSet, propPrefix, null,
                                lineStartOffset + equalSignOffset + 1, caretOffset);
                    } else {
                        // property completion
                        completePropName(sbs, completionResultSet, propPrefix,
                                lineStartOffset + propPrefixOffset, caretOffset);
                    }
                }
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
            completionResultSet.finish();
        }
    }, jtc);
}

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);
    }//  ww w . j a  va  2  s  .c o m

    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  w  w  w . ja va2 s.com
            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();
        }
    }
}