@Override protected Transferable createTransferable(JComponent c) { JTextPane aTextPane = (JTextPane) c; HTMLEditorKit kit = ((HTMLEditorKit) aTextPane.getEditorKit()); StyledDocument sdoc = aTextPane.getStyledDocument(); int sel_start = aTextPane.getSelectionStart(); int sel_end = aTextPane.getSelectionEnd(); int i = sel_start; StringBuilder output = new StringBuilder(); while (i < sel_end) { Element e = sdoc.getCharacterElement(i); Object nameAttr = e.getAttributes().getAttribute(StyleConstants.NameAttribute); int start = e.getStartOffset(), end = e.getEndOffset(); if (nameAttr == HTML.Tag.BR) { output.append("\n"); } else if (nameAttr == HTML.Tag.CONTENT) { if (start < sel_start) { start = sel_start; } if (end > sel_end) { end = sel_end; } try { String str = sdoc.getText(start, end - start); output.append(str); } catch (BadLocationException ble) { Debug.error(me + "Copy-paste problem!\n%s", ble.getMessage()); } } i = end; } return new StringSelection(output.toString()); }
// TODO: make this a method of SikuliDocument, no need to pass document as argument private void changeIndentation(DefaultStyledDocument doc, int linenum, int columns) throws BadLocationException { PreferencesUser pref = PreferencesUser.getInstance(); boolean expandTab = pref.getExpandTab(); int tabWidth = pref.getTabWidth(); if (linenum < 0) { throw new BadLocationException("Negative line", -1); } Element map = doc.getDefaultRootElement(); if (linenum >= map.getElementCount()) { throw new BadLocationException("No such line", doc.getLength() + 1); } if (columns == 0) { return; } Element lineElem = map.getElement(linenum); int lineStart = lineElem.getStartOffset(); int lineLength = lineElem.getEndOffset() - lineStart; String line = doc.getText(lineStart, lineLength); // determine current indentation and number of whitespace characters int wsChars; int indentation = 0; for (wsChars = 0; wsChars < line.length(); wsChars++) { char c = line.charAt(wsChars); if (c == ' ') { indentation++; } else if (c == '\t') { indentation += tabWidth; } else { break; } } int newIndentation = indentation + columns; if (newIndentation <= 0) { doc.remove(lineStart, wsChars); return; } // build whitespace string for new indentation StringBuilder newWs = new StringBuilder(newIndentation / tabWidth + tabWidth - 1); int ind = 0; if (!expandTab) { for (; ind + tabWidth <= newIndentation; ind += tabWidth) { newWs.append('\t'); } } for (; ind < newIndentation; ind++) { newWs.append(' '); } doc.replace(lineStart, wsChars, newWs.toString(), null); }
/** * DOCUMENT ME! * * @param lineNumber DOCUMENT ME! * @return DOCUMENT ME! */ private Element init(int lineNumber) { Document doc = buffer.getDocument(); Element line = doc.getDefaultRootElement().getElement(lineNumber); try { int options = Pattern.DOTALL; String find = PreferenceManager.getString("snr.find", ""); if ((find != null) && !find.equals("")) { if (PreferenceManager.getBoolean("snr.case", false)) { find = find.toLowerCase(); options |= Pattern.CASE_INSENSITIVE; } if (PreferenceManager.getBoolean("snr.whole", false)) { find = "\\b" + find + "\\b"; } int offset = line.getStartOffset(); int length = line.getEndOffset() - offset; if (PreferenceManager.getInt("snr.direction", FORWARD) == FORWARD) { if ((buffer.getSelectionEnd() > line.getStartOffset()) && (buffer.getSelectionEnd() <= line.getEndOffset())) { offset = buffer.getSelectionEnd(); length = line.getEndOffset() - offset; } } else { if ((buffer.getSelectionStart() > line.getStartOffset()) && (buffer.getSelectionStart() <= line.getEndOffset())) { length = buffer.getSelectionStart() - offset; } } String text = doc.getText(offset, length); Pattern pattern = Pattern.compile(find, options); this.matcher = pattern.matcher(text); } } catch (BadLocationException e) { log.error(e.getMessage(), e); } return line; }
/** * Returns the line. * * @param content the content * @param offset the offset to start at * @return the line */ protected String getLine(String content, int offset) { int line = m_RootElement.getElementIndex(offset); Element lineElement = m_RootElement.getElement(line); int start = lineElement.getStartOffset(); int end = lineElement.getEndOffset(); return content.substring(start, end - 1); }
/** * Paints the word-wrapped text. * * @param g The graphics context in which to paint. * @param a The shape (usually a rectangle) in which to paint. */ public void paint(Graphics g, Shape a) { Rectangle alloc = (a instanceof Rectangle) ? (Rectangle) a : a.getBounds(); tabBase = alloc.x; Graphics2D g2d = (Graphics2D) g; host = (RSyntaxTextArea) getContainer(); int ascent = host.getMaxAscent(); int fontHeight = host.getLineHeight(); FoldManager fm = host.getFoldManager(); TokenPainter painter = host.getTokenPainter(); Element root = getElement(); // Whether token styles should always be painted, even in selections int selStart = host.getSelectionStart(); int selEnd = host.getSelectionEnd(); boolean useSelectedTextColor = host.getUseSelectedTextColor(); int n = getViewCount(); // Number of lines. int x = alloc.x + getLeftInset(); tempRect.y = alloc.y + getTopInset(); Rectangle clip = g.getClipBounds(); for (int i = 0; i < n; i++) { tempRect.x = x + getOffset(X_AXIS, i); // tempRect.y = y + getOffset(Y_AXIS, i); tempRect.width = getSpan(X_AXIS, i); tempRect.height = getSpan(Y_AXIS, i); // System.err.println("For line " + i + ": tempRect==" + tempRect); if (tempRect.intersects(clip)) { Element lineElement = root.getElement(i); int startOffset = lineElement.getStartOffset(); int endOffset = lineElement.getEndOffset() - 1; // Why always "-1"? View view = getView(i); if (!useSelectedTextColor || selStart == selEnd || (startOffset >= selEnd || endOffset < selStart)) { drawView(painter, g2d, alloc, view, fontHeight, tempRect.y + ascent); } else { // System.out.println("Drawing line with selection: " + i); drawViewWithSelection( painter, g2d, alloc, view, fontHeight, tempRect.y + ascent, selStart, selEnd); } } tempRect.y += tempRect.height; Fold possibleFold = fm.getFoldForLine(i); if (possibleFold != null && possibleFold.isCollapsed()) { i += possibleFold.getCollapsedLineCount(); // Visible indicator of collapsed lines Color c = RSyntaxUtilities.getFoldedLineBottomColor(host); if (c != null) { g.setColor(c); g.drawLine(x, tempRect.y - 1, alloc.width, tempRect.y - 1); } } } }
/** * Attach a {@link Document} to enable line number tracking when editing. The position to track is * before the first non-whitespace character on the line. Edits happening before that position * will cause the line number to update accordingly. Multiple {@link #startTracking} calls will * replace the tracked document. Whoever wants a tracked line should track it and add itself as * listener if necessary. ({@link LineHighlight}, {@link LineBreakpoint}) * * @param doc the {@link Document} to use for line number tracking */ public synchronized void startTracking(Document doc) { // System.out.println("tracking: " + this); if (doc == null) { return; // null arg } if (doc == this.doc) { return; // already tracking that doc } try { Element line = doc.getDefaultRootElement().getElement(lineIdx); if (line == null) { return; // line doesn't exist } String lineText = doc.getText(line.getStartOffset(), line.getEndOffset() - line.getStartOffset()); // set tracking position at (=before) first non-white space character on line pos = doc.createPosition(line.getStartOffset() + nonWhiteSpaceOffset(lineText)); this.doc = doc; doc.addDocumentListener(this); } catch (BadLocationException ex) { Logger.getLogger(LineID.class.getName()).log(Level.SEVERE, null, ex); pos = null; this.doc = null; } }
@Override public int getKeyword(int pos, boolean strict) { Element line = elem.getElement(elem.getElementIndex(pos)); int end = line.getEndOffset(); int tok = -1; start = line.getStartOffset(); int startL = start; int s = -1; try { yyreset(new StringReader(doc.getText(start, end - start))); if (!strict) { pos++; } while (startL < pos && s != startL) { s = startL; tok = yylex(); startL = start + yychar + yylength(); } return tok; } catch (Exception e) { return LexerConstants.DEFAULT; } }
/** * Writes out text. If a range is specified when the constructor is invoked, then only the * appropriate range of text is written out. * * @param elem an Element * @exception IOException on any I/O error * @exception BadLocationException if pos represents an invalid location within the document. */ protected void text(Element elem) throws BadLocationException, IOException { int start = Math.max(getStartOffset(), elem.getStartOffset()); int end = Math.min(getEndOffset(), elem.getEndOffset()); if (start < end) { if (segment == null) { segment = new Segment(); } getDocument().getText(start, end - start, segment); newlineOutputed = false; if (segment.count > 0) { if (segment.array[segment.offset + segment.count - 1] == '\n') { newlineOutputed = true; } if (inPre && end == preEndOffset) { if (segment.count > 1) { segment.count--; } else { return; } } replaceEntities = true; setCanWrapLines(!inPre); write(segment.array, segment.offset, segment.count); setCanWrapLines(false); replaceEntities = false; } } }
/** return indent for nearest non-ws line */ private static int getIndent(final Document document, int elementIndex) throws BadLocationException { Element rootElement = document.getDefaultRootElement(); boolean isTextWSOnly; int eso = rootElement.getStartOffset(); boolean extendIndent = false; do { if (elementIndex < 1) { break; } Element element = rootElement.getElement(elementIndex--); eso = element.getStartOffset(); String elementText = document.getText(eso, element.getEndOffset() - eso); isTextWSOnly = elementText.matches("\\s+"); // NOI18N if (!isTextWSOnly) { final String ett = elementText.trim(); extendIndent = ett.endsWith("{") || ett.endsWith("["); // NOI18N } } while (isTextWSOnly); int indent = IndentUtils.lineIndent(document, eso); if (extendIndent) { indent += IndentUtils.tabSize(document); } return indent; }
public int computeDocumentOffset(int line, int column) throws BadLocationException { if (line < 0 || column < 0) throw new BadLocationException("Negative line/col", -1); Element lineElement = editor.getDocument().getDefaultRootElement().getElement(line - 1); int beginLineOffset = lineElement.getStartOffset(); int endLineOffset = lineElement.getEndOffset(); String text = editor.getDocument().getText(beginLineOffset, endLineOffset - beginLineOffset); int parserChar = 1; int documentChar = 0; while (parserChar < column) { if (documentChar < text.length() && text.charAt(documentChar) == '\t') { parserChar += 8; documentChar += 1; } else { parserChar += 1; documentChar += 1; } } return beginLineOffset + documentChar; }
public Token getWordAt(int offs, Pattern p) { Token word = null; try { Element line = getParagraphElement(offs); if (line == null) { return word; } int lineStart = line.getStartOffset(); int lineEnd = Math.min(line.getEndOffset(), getLength()); Segment seg = new Segment(); getText(lineStart, lineEnd - lineStart, seg); if (seg.count > 0) { // we need to get the word using the words pattern p Matcher m = p.matcher(seg); int o = offs - lineStart; while (m.find()) { if (m.start() <= o && o <= m.end()) { word = new Token(TokenType.DEFAULT, m.start() + lineStart, m.end() - m.start()); break; } } } } catch (BadLocationException ex) { Logger.getLogger(SyntaxDocument.class.getName()).log(Level.SEVERE, null, ex); } finally { return word; } }
/** * constructs region Node * * @param regionName * @param regionInfo RegionInfo * @param pregion Protocol region */ public void constructRegion(RegionInfo regionInfo, Object pregion) throws CollabException { String regionName = regionInfo.getID(); String mode = regionInfo.getMode(); int beginOffset = 0; int endOffset = 0; StyledDocument fileDocument = getDocument(); if (mode.equals(RegionInfo.LINE_RANGE)) { javax.swing.text.Element beginElement = fileDocument.getDefaultRootElement().getElement(regionInfo.getbegin()); beginOffset = beginElement.getStartOffset(); javax.swing.text.Element endElement = fileDocument.getDefaultRootElement().getElement(regionInfo.getend()); endOffset = endElement.getEndOffset(); } else { beginOffset = regionInfo.getbegin(); endOffset = regionInfo.getend(); int endCorrection = regionInfo.getCorrection(); endOffset += endCorrection; if (endOffset < 0) endOffset = 0; } if (pregion instanceof JavaRegion) { JavaRegion javaRegion = (JavaRegion) pregion; int length = endOffset - beginOffset; javaRegion.setRegionName(regionName); javaRegion.setBeginOffset(new java.math.BigInteger(String.valueOf(beginOffset))); javaRegion.setLength(new java.math.BigInteger(String.valueOf(length))); } else { super.constructRegion(regionInfo, pregion); } }
private static String getIdentifier(StyledDocument doc, JEditorPane ep, int offset) { 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; return t.substring(identStart, identEnd); } catch (BadLocationException e) { return null; } }
/** * 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(); }
public JSONArray convertHTMLToFlag(HTMLDocument htmlDoc) { boolean isExistFace = false; ElementIterator it = new ElementIterator(htmlDoc); Element element; while ((element = it.next()) != null) { if (element.getName().equals(HTML.Tag.IMG.toString())) { isExistFace = true; try { String name = element.getAttributes().getAttribute(HTML.Attribute.NAME).toString(); // String src = element.getAttributes().getAttribute(HTML.Attribute.SRC).toString(); int offset = element.getStartOffset(); htmlDoc.replace(offset, element.getEndOffset() - offset, "~face:" + name + "~", null); } catch (BadLocationException ex) { Logger.getLogger(QQImageUtil.class.getName()).log(Level.SEVERE, null, ex); } } } String text = null; try { text = htmlDoc.getText(0, htmlDoc.getLength()); htmlDoc.remove(0, htmlDoc.getLength()); } catch (BadLocationException ex) { Logger.getLogger(QQImageUtil.class.getName()).log(Level.SEVERE, null, ex); } if (isExistFace) { text = text.replaceFirst("\\n", ""); } // Log.println(text); JSONArray msg = new JSONArray(); String[] arr = text.split("~"); for (int i = 0; i < arr.length; i++) { String temp = arr[i]; // Log.println(temp); if (temp.startsWith("face:")) { String[] tempArray = temp.split(":"); JSONArray face = new JSONArray(); face.add(tempArray[0]); String regex = ",([0-9]*):" + tempArray[1] + ","; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(faceFlag); String result = null; if (m.find()) { result = m.group(1); } else { result = tempArray[1]; } int faceNumber = Integer.parseInt(result); face.add(faceNumber); msg.add(face); } else { msg.add(temp); } } // Log.println(msg); return msg; }
public void removeElement(Element e) { try { Document doc = getEditorPnl().getEditor().getDocument(); doc.remove(e.getStartOffset(), e.getEndOffset() - e.getStartOffset()); } catch (Exception ex) { ex.printStackTrace(); } }
/** * If the selection is multi lined, then the full lines are selected, otherwise, nothing is done. * * @return true if the selection is multi-line, or a whole line */ public static boolean selectLines(JTextComponent target) { if (target.getSelectionStart() == target.getSelectionEnd()) { return false; } PlainDocument pDoc = (PlainDocument) target.getDocument(); Element es = pDoc.getParagraphElement(target.getSelectionStart()); // if more than one line is selected, we need to subtract one from the end // so that we do not select the line with the caret and no selection in it Element ee = pDoc.getParagraphElement(target.getSelectionEnd() - 1); if (es.equals(ee) && ee.getEndOffset() != target.getSelectionEnd()) { return false; } int start = es.getStartOffset(); int end = ee.getEndOffset(); target.select(start, end - 1); return true; }
/** * Provides a mapping from the view coordinate space to the logical coordinate space of the model. * * @param fx the X coordinate >= 0 * @param fy the Y coordinate >= 0 * @param a the allocated region to render into * @return the location within the model that best represents the given point in the view >= 0 */ @Override public int viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) { bias[0] = Position.Bias.Forward; Rectangle alloc = a.getBounds(); RSyntaxDocument doc = (RSyntaxDocument) getDocument(); int x = (int) fx; int y = (int) fy; // If they're asking about a view position above the area covered by // this view, then the position is assumed to be the starting position // of this view. if (y < alloc.y) { return getStartOffset(); } // If they're asking about a position below this view, the position // is assumed to be the ending position of this view. else if (y > alloc.y + alloc.height) { return host.getLastVisibleOffset(); } // They're asking about a position within the coverage of this view // vertically. So, we figure out which line the point corresponds to. // If the line is greater than the number of lines contained, then // simply use the last line as it represents the last possible place // we can position to. else { Element map = doc.getDefaultRootElement(); int lineIndex = Math.abs((y - alloc.y) / lineHeight); // metrics.getHeight() ); FoldManager fm = host.getFoldManager(); // System.out.print("--- " + lineIndex); lineIndex += fm.getHiddenLineCountAbove(lineIndex, true); // System.out.println(" => " + lineIndex); if (lineIndex >= map.getElementCount()) { return host.getLastVisibleOffset(); } Element line = map.getElement(lineIndex); // If the point is to the left of the line... if (x < alloc.x) { return line.getStartOffset(); } else if (x > alloc.x + alloc.width) { return line.getEndOffset() - 1; } else { // Determine the offset into the text int p0 = line.getStartOffset(); Token tokenList = doc.getTokenListForLine(lineIndex); tabBase = alloc.x; int offs = tokenList.getListOffset((RSyntaxTextArea) getContainer(), this, tabBase, x); return offs != -1 ? offs : p0; } } // End of else. }
private static final 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; }
/** * Gets the line at given position. The line returned will NOT include the line terminator '\n' * * @param pos Position (usually from text.getCaretPosition() * @return the STring of text at given position * @throws BadLocationException */ public String getLineAt(int pos) throws BadLocationException { Element e = getParagraphElement(pos); Segment seg = new Segment(); getText(e.getStartOffset(), e.getEndOffset() - e.getStartOffset(), seg); char last = seg.last(); if (last == '\n' || last == '\r') { seg.count--; } return seg.toString(); }
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); } }
public void removeLines() { Element root = getDocument().getDefaultRootElement(); while (root.getElementCount() > maxLines) { Element firstLine = root.getElement(0); try { getDocument().remove(0, firstLine.getEndOffset()); } catch (BadLocationException ble) { LOGGER.warn("Can't remove excess lines: {}", ble); } } }
private String getElementText(Element element) { String text = ""; try { int startOffset = element.getStartOffset(); int endOffset = element.getEndOffset(); int length = endOffset - startOffset; text = element.getDocument().getText(startOffset, length); } catch (Exception e) { logger.error("", e); } return text.trim(); }
/** 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; }
public File reparseBefore() { Element e = this.getDocument().getDefaultRootElement(); if (e.getEndOffset() - e.getStartOffset() == 1) { return null; } File temp = FileManager.createTempFile("reparse"); try { writeFile(temp.getAbsolutePath()); return temp; } catch (IOException ex) { } return null; }
private void handleDecreaseIndent(int line, Element elem, StyledDocument doc) throws BadLocationException { int start = elem.getStartOffset(); int end = elem.getEndOffset() - 1; doc.getText(start, end - start, segLine); int i = segLine.offset; end = i + segLine.count; if (end > i) { String leadingWS = PythonIndentation.getLeadingWhitespace(doc, start, end - start); int toRemove = indentationLogic.checkDedent(leadingWS, line + 1); doc.remove(start, toRemove); } }
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 ble) { System.out.println(ble); } }
private void doError(SAXParseException e, ParserNotice.Level level) { int line = e.getLineNumber() - 1; Element root = doc.getDefaultRootElement(); Element elem = root.getElement(line); int offs = elem.getStartOffset(); int len = elem.getEndOffset() - offs; if (line == root.getElementCount() - 1) { len++; } DefaultParserNotice pn = new DefaultParserNotice(XmlParser.this, e.getMessage(), line, offs, len); pn.setLevel(level); result.addNotice(pn); }
// <editor-fold defaultstate="collapsed" desc="replace text patterns with image buttons"> public boolean reparse() { File temp = null; Element e = this.getDocument().getDefaultRootElement(); if (e.getEndOffset() - e.getStartOffset() == 1) { return true; } if ((temp = reparseBefore()) != null) { if (reparseAfter(temp)) { updateDocumentListeners(); return true; } } return false; }
/** * Insert a line in the text element containing the passed position skipping a number of character * from the beginning of the element. The function of the skipping of characters is to "jump" over * the prompt in the beginning of a line. * * @param pos the position from which to retrieve the element that contains it * @param skip how many characters are skipped from the beginning of the element when inserting * the string * @param line the line to insert */ public void setCurrentLine(final int pos, final int skip, final String line) { final Element element = getParagraphElement(pos); final int start = element.getStartOffset(); final int end = element.getEndOffset(); try { remove(start + skip, end - (start + skip + 1)); super.insertString(start + skip, line, normal); } catch (final BadLocationException e) { System.out.println("Bad location!"); e.printStackTrace(); } }