/** * Returns the last non-whitespace, non-comment token, before the * specified offset. * * @param doc The document. * @param offs The ending offset for the search. * @return The last non-whitespace, non-comment token, or <code>null</code> * if there isn't one. * @see #getPreviousImportantToken(RSyntaxDocument, int) * @see #getNextImportantToken(Token, RSyntaxTextArea, int) */ public static Token getPreviousImportantTokenFromOffs( RSyntaxDocument doc, int offs) { Element root = doc.getDefaultRootElement(); int line = root.getElementIndex(offs); Token t = doc.getTokenListForLine(line); // Check line containing offs Token target = null; while (t!=null && t.isPaintable() && !t.containsPosition(offs)) { if (!t.isCommentOrWhitespace()) { target = t; } t = t.getNextToken(); } // Check previous line(s) if (target==null) { target = RSyntaxUtilities.getPreviousImportantToken(doc, line-1); } return target; }
private static void checkImages() throws Exception { SwingUtilities.invokeAndWait(new Runnable() { public void run() { HTMLEditorKit c = new HTMLEditorKit(); HTMLDocument doc = new HTMLDocument(); try { c.read(new StringReader("<HTML><TITLE>Test</TITLE><BODY><IMG id=test></BODY></HTML>"), doc, 0); } catch (Exception e) { throw new RuntimeException("The test failed", e); } Element elem = doc.getElement("test"); ImageView iv = new ImageView(elem); if (iv.getLoadingImageIcon() == null) { throw new RuntimeException("getLoadingImageIcon returns null"); } if (iv.getNoImageIcon() == null) { throw new RuntimeException("getNoImageIcon returns null"); } } }); }
/** * Gets index of first not space/tab element in line where caret is or caret * position if non found before its location * * @param doc edited document * @param caretOffset current caret position * @return Integer index of first space or offset passed in if none before * it * @throws BadLocationException */ static int getRowFirstNonWhite(StyledDocument doc, int caretOffset) throws BadLocationException { Element lineElement = doc.getParagraphElement(caretOffset);//line start&stop offsets int start = lineElement.getStartOffset(); int failsafe = start; 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 > caretOffset ? failsafe : start; }
/** * Writes out an end tag for the element. * * @param elem an Element * @exception IOException on any I/O error */ protected void endTag(Element elem) throws IOException { if (synthesizedElement(elem)) { return; } if (matchNameAttribute(elem.getAttributes(), HTML.Tag.PRE)) { inPre = false; } // write out end tags for item on stack closeOutUnwantedEmbeddedTags(elem.getAttributes()); if (inContent) { if (!newlineOutputed) { writeLineSeparator(); } newlineOutputed = false; inContent = false; } indent(); write('<'); write('/'); write(elem.getName()); write('>'); writeLineSeparator(); }
/** * 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; }
public void actionPerformed(ActionEvent e) { String trTag = "<tr>"; Element tr = document .getParagraphElement(editor.getCaretPosition()) .getParentElement() .getParentElement(); for (int i = 0; i < tr.getElementCount(); i++) if (tr.getElement(i).getName().toUpperCase().equals("TD")) trTag += "<td><p></p></td>"; trTag += "</tr>"; /* * HTMLEditorKit.InsertHTMLTextAction hta = new * HTMLEditorKit.InsertHTMLTextAction("insertTR",trTag, * HTML.Tag.TABLE, HTML.Tag.TR); */ try { document.insertAfterEnd(tr, trTag); //editorKit.insertHTML(document, editor.getCaretPosition(), // trTag, 3, 0, HTML.Tag.TR); } catch (Exception ex) { ex.printStackTrace(); } }
public @Override Element getElement(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Invalid line index=" + index + " < 0"); // NOI18N } int elementCount = getElementCount(); if (index >= elementCount) { throw new IndexOutOfBoundsException("Invalid line index=" + index // NOI18N + " >= lineCount=" + elementCount); // NOI18N } LineElement elem = (LineElement)super.getElement(index); if (elem == null) { // if the document is not locked elem may be null even after the initial checks (#159491) throw new IndexOutOfBoundsException("Can't find element, index=" + index //NOI18N + ", count=" + getElementCount() //NOI18N + ", documentLocked=" + (DocumentUtilities.isReadLocked(doc) || DocumentUtilities.isWriteLocked(doc))); //NOI18N } return elem; }
public @Override DocumentEvent.ElementChange getChange(Element elem) { // Super of getChange() if (changeLookup2 != null) { return (DocumentEvent.ElementChange) changeLookup2.get(elem); } int n = edits.size(); for (int i = 0; i < n; i++) { Object o = edits.elementAt(i); if (o instanceof DocumentEvent.ElementChange) { DocumentEvent.ElementChange c = (DocumentEvent.ElementChange) o; if (c.getElement() == elem) { return c; } } } return null; // End super of getChange() }
/** The operation to perform when this action is triggered. */ public void actionPerformed(ActionEvent e) { JTextComponent target = getTextComponent(e); if (target != null) { Document doc = target.getDocument(); Element map = doc.getDefaultRootElement(); int offs = target.getCaretPosition(); int lineIndex = map.getElementIndex(offs); int lineEnd = map.getElement(lineIndex).getEndOffset() - 1; if (select) { target.moveCaretPosition(lineEnd); } else { target.setCaretPosition(lineEnd); } } }
public static int getRowStart(Document doc, int offset, int lineShift) throws BadLocationException { checkOffsetValid(doc, offset); if (lineShift != 0) { Element lineRoot = doc.getDefaultRootElement(); int line = lineRoot.getElementIndex(offset); line += lineShift; if (line < 0 || line >= lineRoot.getElementCount()) { return -1; // invalid line shift } return lineRoot.getElement(line).getStartOffset(); } else { // no shift return doc.getDefaultRootElement().getElement( doc.getDefaultRootElement().getElementIndex(offset)).getStartOffset(); } }
public void testCuriosities() throws Exception { // Test position at offset 0 does not move after insert Document doc = new PlainDocument(); doc.insertString(0, "test", null); Position pos = doc.createPosition(0); assertEquals(0, pos.getOffset()); doc.insertString(0, "a", null); assertEquals(0, pos.getOffset()); // Test there is an extra newline above doc.getLength() assertEquals("\n", doc.getText(doc.getLength(), 1)); assertEquals("atest\n", doc.getText(0, doc.getLength() + 1)); // Test the last line element contains the extra newline Element lineElem = doc.getDefaultRootElement().getElement(0); assertEquals(0, lineElem.getStartOffset()); assertEquals(doc.getLength() + 1, lineElem.getEndOffset()); // Test that once position gets to zero it won't go anywhere else (unless undo performed) pos = doc.createPosition(1); doc.remove(0, 1); assertEquals(0, pos.getOffset()); doc.insertString(0, "b", null); assertEquals(0, pos.getOffset()); }
/** * Very basic Attribute handling only. Expand as needed. */ public ImageComponentView(Element e) { super(e); imageName = (String) e.getAttributes() .getAttribute(HTML.Attribute.SRC); srcOp = imageName == null || imageName.trim().length() == 0 ? null : Op.load(imageName); }
public View create(javax.swing.text.Element element) { final HTML.Tag kind = (HTML.Tag) (element.getAttributes().getAttribute(javax.swing.text.StyleConstants.NameAttribute)); if (kind instanceof HTML.Tag && element.getName().equals("img")) { final String imageName = (String) element.getAttributes().getAttribute(HTML.Attribute.SRC); if (imageName.indexOf("/") < 0) { return new ImageComponentView(element); } } return super.create(element); }
void setElementProperties(Element el, String id, String cls, String sty) { ElementDialog dlg = new ElementDialog(null); //dlg.setLocation(linkActionB.getLocationOnScreen()); Dimension dlgSize = dlg.getPreferredSize(); Dimension frmSize = this.getSize(); Point loc = this.getLocationOnScreen(); dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); dlg.setModal(true); dlg.setTitle(Local.getString("Object properties")); dlg.idField.setText(id); dlg.classField.setText(cls); dlg.styleField.setText(sty); // Uncommented, returns a simple p into the header... fix needed ? //dlg.header.setText(el.getName()); dlg.setVisible(true); if (dlg.CANCELLED) return; SimpleAttributeSet attrs = new SimpleAttributeSet(el.getAttributes()); if (dlg.idField.getText().length() > 0) attrs.addAttribute(HTML.Attribute.ID, dlg.idField.getText()); if (dlg.classField.getText().length() > 0) attrs.addAttribute(HTML.Attribute.CLASS, dlg.classField.getText()); if (dlg.styleField.getText().length() > 0) attrs.addAttribute(HTML.Attribute.STYLE, dlg.styleField.getText()); document.setParagraphAttributes(el.getStartOffset(), 0, attrs, true); }
/** * Returns true if the element is a * synthesized element. Currently we are only testing * for the p-implied tag. */ protected boolean synthesizedElement(Element elem) { if (matchNameAttribute(elem.getAttributes(), HTML.Tag.IMPLIED)) { return true; } return false; }
AbstractPositionElement(Element parent, Position startPos, Position endPos) { assert (startPos != null); assert (endPos != null); this.parent = parent; this.startPos = startPos; this.endPos = endPos; }
@Override public Element[] getRootElements() { Element[] elements = this.document.getRootElements(); Element[] wrappers = new Element[elements.length]; for (int i = 0; i < elements.length; i++) { wrappers[i] = new MyElement(elements[i]); } return wrappers; }
void removeIfEmpty(Element elem) { if (elem.getEndOffset() - elem.getStartOffset() < 2) { try { document.remove(elem.getStartOffset(), elem.getEndOffset()); } catch (Exception ex) { ex.printStackTrace(); } } }
@Override public void setVisible(boolean b) { if (b) { JTextPane pane = (JTextPane) getInvoker(); StyledDocument doc = pane.getStyledDocument(); Element elem = doc.getCharacterElement(pane.viewToModel(clickPoint)); Object l = elem.getAttributes().getAttribute(HyperlinkSupport.LINK_ATTRIBUTE); if (l != null && l instanceof AttachmentLink) { BugzillaIssue.Attachment attachment = ((AttachmentLink) l).attachment; if (attachment != null) { add(new JMenuItem(attachment.getOpenAction())); add(new JMenuItem(attachment.getSaveAction())); Action openInStackAnalyzerAction = attachment.getOpenInStackAnalyzerAction(); if(openInStackAnalyzerAction != null) { add(new JMenuItem(openInStackAnalyzerAction)); } if (attachment.isPatch()) { Action a = attachment.getApplyPatchAction(); if(a != null) { add(attachment.getApplyPatchAction()); } } super.setVisible(true); } } } else { super.setVisible(false); removeAll(); } }
public void actionPerformed(ActionEvent e) { String trTag = "<tr>"; Element tr = document .getParagraphElement(editor.getCaretPosition()) .getParentElement() .getParentElement(); for (int i = 0; i < tr.getElementCount(); i++) { if (tr.getElement(i).getName().toUpperCase().equals("TD")) trTag += "<td><p></p></td>"; } trTag += "</tr>"; /* * HTMLEditorKit.InsertHTMLTextAction hta = new * HTMLEditorKit.InsertHTMLTextAction("insertTR",trTag, * HTML.Tag.TABLE, HTML.Tag.TR); */ try { document.insertAfterEnd(tr, trTag); //editorKit.insertHTML(document, editor.getCaretPosition(), // trTag, 3, 0, HTML.Tag.TR); } catch (Exception ex) { ex.printStackTrace(); } }
private void doCopy() { /* * java.awt.datatransfer.Clipboard clip = * java.awt.Toolkit.getDefaultToolkit().getSystemClipboard(); try { * String text = editor.getSelectedText(); * //.getText(editor.getSelectionStart(), * editor.getSelectionEnd()-editor.getSelectionStart()); * clip.setContents(new java.awt.datatransfer.StringSelection(text), * null); } catch (Exception e) { e.printStackTrace(); */ Element el = document.getParagraphElement(editor.getSelectionStart()); if (el.getName().toUpperCase().equals("P-IMPLIED")) el = el.getParentElement(); String elName = el.getName(); StringWriter sw = new StringWriter(); String copy; java.awt.datatransfer.Clipboard clip = java.awt.Toolkit.getDefaultToolkit().getSystemClipboard(); try { editorKit.write( sw, document, editor.getSelectionStart(), editor.getSelectionEnd() - editor.getSelectionStart()); copy = sw.toString(); copy = copy.split("<" + elName + "(.*?)>")[1]; copy = copy.split("</" + elName + ">")[0]; clip.setContents( new java.awt.datatransfer.StringSelection(copy.trim()), null); } catch (Exception ex) { ex.printStackTrace(); } }
void removeIfEmpty(Element elem) { if (elem.getEndOffset() - elem.getStartOffset() < 2) { try { document.remove(elem.getStartOffset(), elem.getEndOffset()); } catch (Exception ex) { //ex.printStackTrace(); } } }
/** * Updates the tree based on the event type. This will invoke either * updateTree with the root element, or handleChange. */ protected void updateTree(DocumentEvent event) { updatingSelection = true; try { TreeModel model = getTreeModel(); Object root = model.getRoot(); for (int counter = model.getChildCount(root) - 1; counter >= 0; counter--) { updateTree(event, (Element) model.getChild(root, counter)); } } finally { updatingSelection = false; } }
private boolean indentNeedsIncrementing(Element current, Element next) { if ((next.getParentElement() == current) && !inPre) { if (indentNext) { indentNext = false; return true; } else if (synthesizedElement(next)) { indentNext = true; } else if (!synthesizedElement(current)) { return true; } } return false; }
private static Element findFirstElement(Element e, String name) { String elementName = e.getName(); if (elementName != null && elementName.equalsIgnoreCase(name)) { return e; } for (int i = 0; i < e.getElementCount(); i++) { Element result = findFirstElement(e.getElement(i), name); if (result != null) { return result; } } return null; }
public void actionPerformed(ActionEvent e) { String tdTag = "<td><p></p></td>"; Element td = document .getParagraphElement(editor.getCaretPosition()) .getParentElement(); try { document.insertAfterEnd(td, tdTag); } catch (Exception ex) { ex.printStackTrace(); } }
/** * Returns a token list for the specified segment of text representing * the specified line number. This method is basically a wrapper for * <code>tokenMaker.getTokenList</code> that takes into account the last * token on the previous line to assure token accuracy. * * @param line The line number of <code>text</code> in the document, * >= 0. * @return A token list representing the specified line. */ public final Token getTokenListForLine(int line) { tokenRetrievalCount++; if (line==lastLine && cachedTokenList!=null) { if (DEBUG_TOKEN_CACHING) { useCacheCount++; System.err.println("--- Using cached line; ratio now: " + useCacheCount + "/" + tokenRetrievalCount); } return cachedTokenList; } lastLine = line; Element map = getDefaultRootElement(); Element elem = map.getElement(line); int startOffset = elem.getStartOffset(); //int endOffset = (line==map.getElementCount()-1 ? elem.getEndOffset() - 1: // elem.getEndOffset() - 1); int endOffset = elem.getEndOffset() - 1; // Why always "-1"? try { getText(startOffset,endOffset-startOffset, s); } catch (BadLocationException ble) { ble.printStackTrace(); return null; } int initialTokenType = line==0 ? Token.NULL : getLastTokenTypeOnLine(line-1); //return tokenMaker.getTokenList(s, initialTokenType, startOffset); cachedTokenList = tokenMaker.getTokenList(s, initialTokenType, startOffset); return cachedTokenList; }
public int getStartOffset() { if (view != null) { return view.getStartOffset(); } Element elem = getElement(); return (elem != null) ? elem.getStartOffset() : 0; }
/** * Determines the color with which to draw a given line of text * @return the Color to draw */ protected Color getColor(Element elem) { Color col = null; try { final String s = elem.getDocument().getText( elem.getStartOffset(), elem.getEndOffset() - elem.getStartOffset() ).trim(); if (s.length() > 0) { switch (s.charAt(0)) { case '*': col = gameMsg; break; case '-': col = systemMsg; break; default: if (s.startsWith(formatChat(""))) { //$NON-NLS-1$ col = myChat; } else { col = otherChat; } break; } } } catch (BadLocationException e) { ErrorDialog.bug(e); } return col == null ? Color.black : col; }
@Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int offs = textArea.getCaretPosition(); int oldOffs = offs; Element curPara = Utilities.getParagraphElement(textArea, offs); try { offs = getNextWord(textArea, offs); if(offs >= curPara.getEndOffset() && oldOffs != curPara.getEndOffset() - 1) { // we should first move to the end of current paragraph // http://bugs.sun.com/view_bug.do?bug_id=4278839 offs = curPara.getEndOffset() - 1; } } catch (BadLocationException ble) { int end = textArea.getDocument().getLength(); if (offs != end) { if(oldOffs != curPara.getEndOffset() - 1) { offs = curPara.getEndOffset() - 1; } else { offs = end; } } } if (select) { textArea.moveCaretPosition(offs); } else { textArea.setCaretPosition(offs); } }
private static Element getLineElem(Document d, int offs) { Element map = d.getDefaultRootElement(); int index = map.getElementIndex(offs); Element elem = map.getElement(index); if ((offs>=elem.getStartOffset()) && (offs<elem.getEndOffset())) { return elem; } return null; }
@Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int offs = textArea.getCaretPosition(); boolean failed = false; try { Element curPara = Utilities.getParagraphElement(textArea, offs); offs = getPreviousWord(textArea, offs); if(offs < curPara.getStartOffset()) { offs = Utilities.getParagraphElement(textArea, offs). getEndOffset() - 1; } } catch (BadLocationException bl) { if (offs != 0) { offs = 0; } else { failed = true; } } if (!failed) { if (select) { textArea.moveCaretPosition(offs); } else { textArea.setCaretPosition(offs); } } else { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } }
/** * 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; }
/** Return default root element */ public @Override Element getDefaultRootElement() { if (defaultRootElem == null) { defaultRootElem = lineRootElement; } return defaultRootElem; }
/** * Returns the length of the specified line. * * @param line * The line */ public int getLineLength(int line) { Element lineElement = document.getDefaultRootElement().getElement(line); if (lineElement == null) { return -1; } else { return lineElement.getEndOffset() - lineElement.getStartOffset() - 1; } }