Java Code Examples for javax.swing.text.Element#getStartOffset()
The following examples show how to use
javax.swing.text.Element#getStartOffset() .
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: SQLSyntaxDocument.java From MogwaiERDesignerNG with GNU General Public License v3.0 | 6 votes |
@Override public void remove(int offset, int length) throws BadLocationException { int former_line_count = root.getElementCount(); // the number of lines before the insertion // delete: super.remove(offset, length); Element line = root.getElement(root.getElementIndex(offset)); // line where deletion started int scan_begin = line.getStartOffset(); // start scanning at the boln of first affected line int scan_end = line.getEndOffset() - 1; // end scanning at the eoln of last affected line (after deleteion) int line_count = root.getElementCount(); // the number of lines after the insertion int first_line = root.getElementIndex(scan_begin); // the first affected line index int lines_deleted = former_line_count - line_count; // the number of inserted eolns // one or more eolns were deleted: if (lines_deleted > 0) lineToks.unshift(first_line, lines_deleted); // highlight: HighlightAffectedText(scan_begin, scan_end, offset, first_line); }
Example 2
Source File: LinkUtils.java From desktopclient-java with GNU General Public License v3.0 | 6 votes |
@Override public void mouseClicked(MouseEvent e) { WebTextPane textPane = (WebTextPane) e.getComponent(); StyledDocument doc = textPane.getStyledDocument(); Element elem = doc.getCharacterElement(textPane.viewToModel(e.getPoint())); if (!elem.getAttributes().isDefined(URL_ATT_NAME)) // not a link return; int len = elem.getEndOffset() - elem.getStartOffset(); final String url; try { url = doc.getText(elem.getStartOffset(), len); } catch (BadLocationException ex) { LOGGER.log(Level.WARNING, "can't get URL", ex); return; } Runnable run = new Runnable() { @Override public void run() { WebUtils.browseSiteSafely(fixProto(url)); } }; new Thread(run, "Link Browser").start(); }
Example 3
Source File: JEditTextArea.java From rapidminer-studio with GNU Affero General Public License v3.0 | 6 votes |
/** * 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 4
Source File: PythonIndentation.java From SikuliX1 with MIT License | 6 votes |
@Override public String getLeadingWhitespace(StyledDocument doc, int head, int len) throws BadLocationException { String ret = ""; int pos = head; while (pos < head + len) { Element e = doc.getCharacterElement(pos); if (e.getName().equals(StyleConstants.ComponentElementName)) { break; } int eStart = e.getStartOffset(); int eEnd = e.getEndOffset(); String space = getLeadingWhitespace(doc.getText(eStart, eEnd - eStart)); ret += space; if (space.length() < eEnd - eStart) { break; } pos = eEnd; } return ret; }
Example 5
Source File: SyntaxDocument.java From rapidminer-studio with GNU Affero General Public License v3.0 | 6 votes |
/** * 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 6
Source File: PUCompletionProvider.java From netbeans with Apache License 2.0 | 6 votes |
static int getRowFirstNonWhite(StyledDocument doc, int offset) throws BadLocationException { Element lineElement = doc.getParagraphElement(offset); int start = lineElement.getStartOffset(); while (start + 1 < lineElement.getEndOffset()) { try { 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; }
Example 7
Source File: FoldMultiLineView.java From netbeans with Apache License 2.0 | 5 votes |
protected @Override void reloadChildren(int index, int removeLength, int startOffset, int endOffset) { // TODO uncomment assert (index == 0 && removeLength == 0 // && startOffset == getStartOffset() && endOffset == getEndOffset()); // Rebuild all the present child views completely index = 0; removeLength = getViewCount(); Element lineElem = getElement(); // starting line element View[] added = null; ViewFactory f = getViewFactory(); if (f != null) { int lineElemEndOffset = lineElem.getEndOffset(); // Ending offset of the previously created view - here start with // begining of the first line int lastViewEndOffset = lineElem.getStartOffset(); List childViews = new ArrayList(); // Append ending fragment if necessary // asserted non-empty list => foldEndOffset populated if (lastViewEndOffset < lineElemEndOffset) { // need ending fragment View lineView = f.create(lineElem); View endingFrag = lineView.createFragment(lastViewEndOffset, lineElemEndOffset); childViews.add(endingFrag); // lastViewEndOffset = lineElemEndOffset; <- can be ignored here } added = new View[childViews.size()]; childViews.toArray(added); } replace(index, removeLength, added); }
Example 8
Source File: BaseDocument.java From netbeans with Apache License 2.0 | 5 votes |
public void checkTrailingSpaces(int offset) { try { int lineNum = Utilities.getLineOffset(this, offset); int lastEditedLine = lastPositionEditedByTyping != null ? Utilities.getLineOffset(this, lastPositionEditedByTyping.getOffset()) : -1; if (lastEditedLine != -1 && lastEditedLine != lineNum) { // clear trailing spaces in the last edited line Element root = getDefaultRootElement(); Element elem = root.getElement(lastEditedLine); int start = elem.getStartOffset(); int end = elem.getEndOffset(); String line = getText(start, end - start); int endIndex = line.length() - 1; if (endIndex >= 0 && line.charAt(endIndex) == '\n') { endIndex--; if (endIndex >= 0 && line.charAt(endIndex) == '\r') { endIndex--; } } int startIndex = endIndex; while (startIndex >= 0 && Character.isWhitespace(line.charAt(startIndex)) && line.charAt(startIndex) != '\n' && line.charAt(startIndex) != '\r') { startIndex--; } startIndex++; if (startIndex >= 0 && startIndex <= endIndex) { remove(start + startIndex, endIndex - startIndex + 1); } } } catch (BadLocationException e) { LOG.log(Level.WARNING, null, e); } }
Example 9
Source File: bug6857057.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
bug6857057() { Element elem = new StubBranchElement(" G L Y P H V"); GlyphView view = new GlyphView(elem); float pos = elem.getStartOffset(); float len = elem.getEndOffset() - pos; int res = view.getBreakWeight(View.X_AXIS, pos, len); if (res != View.ExcellentBreakWeight) { throw new RuntimeException("breakWeight != ExcellentBreakWeight"); } }
Example 10
Source File: MapcalcDocument.java From hortonmachine with GNU General Public License v3.0 | 5 votes |
private String getLine( String content, int offset ) { int line = rootElement.getElementIndex(offset); Element lineElement = rootElement.getElement(line); int start = lineElement.getStartOffset(); int end = lineElement.getEndOffset(); return content.substring(start, end - 1); }
Example 11
Source File: MainPanel.java From java-swing-tips with MIT License | 5 votes |
@Override public void setText(String str) { super.setText(str); FontMetrics fm = getFontMetrics(getFont()); Document doc = getDocument(); Element root = doc.getDefaultRootElement(); int lineCount = root.getElementCount(); // = root.getElementIndex(doc.getLength()); int maxWidth = 10; try { for (int i = 0; i < lineCount; i++) { Element e = root.getElement(i); int rangeStart = e.getStartOffset(); int rangeEnd = e.getEndOffset(); String line = doc.getText(rangeStart, rangeEnd - rangeStart); int width = fm.stringWidth(line); if (maxWidth < width) { maxWidth = width; } } } catch (BadLocationException ex) { // should never happen RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested()); wrap.initCause(ex); throw wrap; } setRows(lineCount); setColumns(1 + maxWidth / getColumnWidth()); }
Example 12
Source File: bug6857057.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
bug6857057() { Element elem = new StubBranchElement(" G L Y P H V"); GlyphView view = new GlyphView(elem); float pos = elem.getStartOffset(); float len = elem.getEndOffset() - pos; int res = view.getBreakWeight(View.X_AXIS, pos, len); if (res != View.ExcellentBreakWeight) { throw new RuntimeException("breakWeight != ExcellentBreakWeight"); } }
Example 13
Source File: MessageConsole.java From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 | 5 votes |
private void removeFromEnd(Document document, Element root) { // We use start minus 1 to make sure we remove the newline // character of the previous line Element line = root.getElement(root.getElementCount() - 1); int start = line.getStartOffset(); int end = line.getEndOffset(); try { document.remove(start - 1, end - start); } catch (BadLocationException ex) { LOG.log(Level.WARNING, ex.getMessage(), ex); } }
Example 14
Source File: MainPanel.java From java-swing-tips with MIT License | 5 votes |
public static int getWordStart(JTextComponent c, int offs) throws BadLocationException { Element line = Optional.ofNullable(Utilities.getParagraphElement(c, offs)) .orElseThrow(() -> new BadLocationException("No word at " + offs, offs)); Document doc = c.getDocument(); int lineStart = line.getStartOffset(); int lineEnd = Math.min(line.getEndOffset(), doc.getLength()); int offs2 = offs; Segment seg = SegmentCache.getSharedSegment(); doc.getText(lineStart, lineEnd - lineStart, seg); if (seg.count > 0) { BreakIterator words = BreakIterator.getWordInstance(c.getLocale()); words.setText(seg); int wordPosition = seg.offset + offs - lineStart; if (wordPosition >= words.last()) { wordPosition = words.last() - 1; words.following(wordPosition); offs2 = lineStart + words.previous() - seg.offset; } else { words.following(wordPosition); offs2 = lineStart + words.previous() - seg.offset; for (int i = offs; i > offs2; i--) { char ch = seg.charAt(i - seg.offset); if (ch == '_' || ch == '-') { offs2 = i + 1; break; } } } } SegmentCache.releaseSharedSegment(seg); return offs2; }
Example 15
Source File: CAccessibleText.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
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 16
Source File: ToolTipAnnotation.java From netbeans with Apache License 2.0 | 5 votes |
private static String getIdentifier(final StyledDocument doc, final JEditorPane ep, final int offset) { String t = null; if (ep.getCaret() != null) { // #255228 if ((ep.getSelectionStart() <= offset) && (offset <= ep.getSelectionEnd())) { t = ep.getSelectedText(); } if (t != null) { return t; } } int line = NbDocument.findLineNumber(doc, offset); int col = NbDocument.findLineColumn(doc, offset); Element lineElem = NbDocument.findLineRootElement(doc).getElement(line); try { if (lineElem == null) { return null; } int lineStartOffset = lineElem.getStartOffset(); int lineLen = lineElem.getEndOffset() - lineStartOffset; if (col + 1 >= lineLen) { // do not evaluate when mouse hover behind the end of line (112662) return null; } t = doc.getText(lineStartOffset, lineLen); return getExpressionToEvaluate(t, col); } catch (BadLocationException e) { return null; } }
Example 17
Source File: SyntaxDocument.java From visualvm with GNU General Public License v2.0 | 5 votes |
/** * Helper method to get the length of an element and avoid getting * a too long element at the end of the document * @param e * @return */ private int getElementLength(Element e) { int end = e.getEndOffset(); if (end >= (getLength() - 1)) { end--; } return end - e.getStartOffset(); }
Example 18
Source File: ValueCompletionItem.java From nb-springboot with Apache License 2.0 | 4 votes |
@Override public void defaultAction(JTextComponent jtc) { logger.log(Level.FINER, "Accepted value completion: {0}", hint.toString()); try { StyledDocument doc = (StyledDocument) jtc.getDocument(); // calculate the amount of chars to remove (by default from dot up to caret position) int lenToRemove = caretOffset - dotOffset; 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('='); int colonIndex = line.indexOf(':'); int commaIndex = line.indexOf(',', dotOffset - lineElement.getStartOffset()); if (equalSignIndex >= 0 && dotOffset < equalSignIndex) { // from dot to equal sign lenToRemove = lineElement.getStartOffset() + equalSignIndex - dotOffset; } else if (colonIndex >= 0 && dotOffset < colonIndex) { // from dot to colon lenToRemove = lineElement.getStartOffset() + colonIndex - dotOffset; } else if (commaIndex >= 0) { // from dot to comma lenToRemove = lineElement.getStartOffset() + commaIndex - dotOffset; } else { // from dot to end of line (except line terminator) lenToRemove = lineElement.getEndOffset() - 1 - dotOffset; } } // remove characters from dot then insert new text doc.remove(dotOffset, lenToRemove); doc.insertString(dotOffset, hint.getValue().toString(), null); // close the code completion box if (!continueCompletion) { Completion.get().hideAll(); } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } }
Example 19
Source File: GapBranchElement.java From netbeans with Apache License 2.0 | 4 votes |
/** * Implementation that remembers the last returned element index * and checks the element at the last index when next called. * <br> * This may improve performance if there are typically many repetitive calls * with offset values hitting the last returned element index. */ public int getElementIndex(int offset) { int low = 0; int high = getElementCount() - 1; if (high == -1) { // no children => return -1 return -1; } int lastIndex = lastReturnedElementIndex; // make copy to be thread-safe if (lastIndex >= low && lastIndex <= high) { Element lastElem = getElement(lastIndex); int lastElemStartOffset = lastElem.getStartOffset(); if (offset >= lastElemStartOffset) { int lastElemEndOffset = lastElem.getEndOffset(); if (offset < lastElemEndOffset) { // hit return lastIndex; } else { // above low = lastIndex + 1; } } else { // below lastIndex high = lastIndex - 1; } } while (low <= high) { int mid = (low + high) / 2; int elemStartOffset = ((Element)children.get(mid)).getStartOffset(); if (elemStartOffset < offset) { low = mid + 1; } else if (elemStartOffset > offset) { high = mid - 1; } else { // element starts at offset lastReturnedElementIndex = mid; return mid; } } if (high < 0) { high = 0; } lastReturnedElementIndex = high; return high; }
Example 20
Source File: ToolTipAnnotation.java From netbeans with Apache License 2.0 | 4 votes |
private static String getIdentifier ( JPDADebugger debugger, StyledDocument doc, JEditorPane ep, int offset, boolean[] isFunctionPtr ) { // do always evaluation if the tooltip is invoked on a text selection String t = null; if ( (ep.getSelectionStart () <= offset) && (offset <= ep.getSelectionEnd ()) ) { t = ep.getSelectedText (); } if (t != null) { return t; } int line = NbDocument.findLineNumber ( doc, offset ); int col = NbDocument.findLineColumn ( doc, offset ); try { Element lineElem = NbDocument.findLineRootElement (doc). getElement (line); if (lineElem == null) { return null; } int lineStartOffset = lineElem.getStartOffset (); int lineLen = lineElem.getEndOffset() - lineStartOffset; t = doc.getText (lineStartOffset, lineLen); int identStart = col; while (identStart > 0 && (Character.isJavaIdentifierPart ( t.charAt (identStart - 1) ) || (t.charAt (identStart - 1) == '.'))) { identStart--; } int identEnd = col; while (identEnd < lineLen && Character.isJavaIdentifierPart(t.charAt(identEnd)) ) { identEnd++; } if (identStart == identEnd) { return null; } String ident = t.substring (identStart, identEnd); //if (JS_KEYWORDS.contains(ident)) { // JS keyword => Do not show anything // return null; //} while (identEnd < lineLen && Character.isWhitespace(t.charAt(identEnd)) ) { identEnd++; } if (identEnd < lineLen && t.charAt(identEnd) == '(') { // We're at a function call isFunctionPtr[0] = true; } return ident; } catch (BadLocationException e) { return null; } }