@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());
  }
 /** Replaces the current word token */
 public void replaceWord(String newWord) {
   if (currentWordPos != -1) {
     try {
       /* ORIGINAL
         document.remove(currentWordPos, currentWordEnd - currentWordPos);
         document.insertString(currentWordPos, newWord, null);
       */
       // Howard's Version for Ekit
       Element element =
           ((javax.swing.text.html.HTMLDocument) document).getCharacterElement(currentWordPos);
       AttributeSet attribs = element.getAttributes();
       document.remove(currentWordPos, currentWordEnd - currentWordPos);
       document.insertString(currentWordPos, newWord, attribs);
       // End Howard's Version
       // Need to reset the segment
       document.getText(0, document.getLength(), text);
     } catch (BadLocationException ex) {
       throw new RuntimeException(ex.getMessage());
     }
     // Position after the newly replaced word(s)
     // Position after the newly replaced word(s)
     first = true;
     currentWordPos = getNextWordStart(text, currentWordPos + newWord.length());
     if (currentWordPos != -1) {
       currentWordEnd = getNextWordEnd(text, currentWordPos);
       nextWordPos = getNextWordStart(text, currentWordEnd);
       sentanceIterator.setText(text);
       sentanceIterator.following(currentWordPos);
     } else moreTokens = false;
   }
 }
Example #3
0
 /**
  * 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 void mouseClicked(MouseEvent me) {
   Element el = doc.getCharacterElement(viewToModel(me.getPoint()));
   if (el == null) return;
   AttributeSet as = el.getAttributes();
   if (as.isDefined("ip")) {
     String ip = (String) as.getAttribute("ip");
     ScriptException se = (ScriptException) as.getAttribute("exception");
     Node node = net.getAtIP(ip);
     if (node == null) {
       Utility.displayError("Error", "Computer does not exist");
       return;
     }
     String errorString =
         "--ERROR--\n"
             + "Error at line number "
             + se.getLineNumber()
             + " and column number "
             + se.getColumnNumber()
             + "\n"
             + se.getMessage();
     new ScriptDialog(
             parentFrame,
             str -> {
               if (str != null) {
                 node.setScript(str);
               }
             },
             node.getScript(),
             errorString)
         .setVisible(true);
   }
 }
  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;
  }
  /**
   * 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);
        }
      }
    }
  }
Example #7
0
  @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;
     }
   }
 }
  /**
   * 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;
    }

    // write out end tags for item on stack
    closeOutUnwantedEmbeddedTags(elem.getAttributes());
    if (inContent) {
      if (!newlineOutputed && !inPre) {
        writeLineSeparator();
      }
      newlineOutputed = false;
      inContent = false;
    }
    if (!inPre) {
      indent();
    }
    if (matchNameAttribute(elem.getAttributes(), HTML.Tag.PRE)) {
      inPre = false;
    }
    write('<');
    write('/');
    write(elem.getName());
    write('>');
    writeLineSeparator();
  }
  /** {@inheritDoc} */
  public ParseResult parse(RSyntaxDocument doc, String style) {

    result.clearNotices();
    Element root = doc.getDefaultRootElement();
    result.setParsedLines(0, root.getElementCount() - 1);

    if (spf == null || doc.getLength() == 0) {
      return result;
    }

    try {
      SAXParser sp = spf.newSAXParser();
      Handler handler = new Handler(doc);
      DocumentReader r = new DocumentReader(doc);
      InputSource input = new InputSource(r);
      sp.parse(input, handler);
      r.close();
    } catch (SAXParseException spe) {
      // A fatal parse error - ignore; a ParserNotice was already created.
    } catch (Exception e) {
      // e.printStackTrace(); // Will print if DTD specified and can't be found
      result.addNotice(
          new DefaultParserNotice(this, "Error parsing XML: " + e.getMessage(), 0, -1, -1));
    }

    return result;
  }
Example #11
0
  /** DOCUMENT ME! */
  public void previous() {
    for (int count = 0, i = buffer.getCurrentLine(); i >= 0; ) {
      Element line = init(i);

      int offset = line.getStartOffset();
      int start = 0;
      int end = 0;

      while (matcher.find()) {
        start = offset + matcher.start();
        end = offset + matcher.end();
      }

      if (start != end) {
        buffer.select(start, end);

        break;
      }

      if (PreferenceManager.getBoolean("snr.warp", false) && (i == 0)) {
        if (count > 1) {
          Toolkit.getDefaultToolkit().beep();

          break;
        }

        count++;

        i = buffer.getLineCount() - 1;
      } else {
        i--;
      }
    }
  }
Example #12
0
  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;
    }
  }
Example #13
0
 private int getRealEnd() {
   //		if ( end != null) {
   return end.getParentElement().getElementIndex(end.getStartOffset());
   //		} else {
   //			return start.getParentElement().getElementCount();
   //		}
 }
Example #14
0
  /**
   * Repaint the region of change covered by the given document event. Damages the line that begins
   * the range to cover the case when the insert/remove is only on one line. If lines are added or
   * removed, damages the whole view. The longest line is checked to see if it has changed.
   */
  protected void updateDamage(DocumentEvent changes, Shape a, ViewFactory f) {
    Component host = getContainer();
    updateMetrics();
    Element elem = getElement();
    DocumentEvent.ElementChange ec = changes.getChange(elem);
    Element[] added = (ec != null) ? ec.getChildrenAdded() : null;
    Element[] removed = (ec != null) ? ec.getChildrenRemoved() : null;
    if (((added != null) && (added.length > 0)) || ((removed != null) && (removed.length > 0))) {
      // lines were added or removed...
      if (added != null) {
        int addedAt = ec.getIndex(); // FIXME: Is this correct?????
        for (int i = 0; i < added.length; i++) possiblyUpdateLongLine(added[i], addedAt + i);
      }
      if (removed != null) {
        for (int i = 0; i < removed.length; i++) {
          if (removed[i] == longLine) {
            longLineWidth = -1; // Must do this!!
            calculateLongestLine();
            break;
          }
        }
      }
      preferenceChanged(null, true, true);
      host.repaint();
    }

    // This occurs when syntax highlighting only changes on lines
    // (i.e. beginning a multiline comment).
    else if (changes.getType() == DocumentEvent.EventType.CHANGE) {
      // System.err.println("Updating the damage due to a CHANGE event...");
      int startLine = changes.getOffset();
      int endLine = changes.getLength();
      damageLineRange(startLine, endLine, a, host);
    } else {
      Element map = getElement();
      int line = map.getElementIndex(changes.getOffset());
      damageLineRange(line, line, a, host);
      if (changes.getType() == DocumentEvent.EventType.INSERT) {
        // check to see if the line is longer than current
        // longest line.
        Element e = map.getElement(line);
        if (e == longLine) {
          // We must recalculate longest line's width here
          // because it has gotten longer.
          longLineWidth = getLineWidth(line);
          preferenceChanged(null, true, false);
        } else {
          // If long line gets updated, update the status bars too.
          if (possiblyUpdateLongLine(e, line)) preferenceChanged(null, true, false);
        }
      } else if (changes.getType() == DocumentEvent.EventType.REMOVE) {
        if (map.getElement(line) == longLine) {
          // removed from longest line... recalc
          longLineWidth = -1; // Must do this!
          calculateLongestLine();
          preferenceChanged(null, true, false);
        }
      }
    }
  }
Example #15
0
  /**
   * Adds the matching block end.
   *
   * @param offset the offset
   * @return the string after adding the matching block end
   * @throws BadLocationException if the offset is invalid
   */
  protected String addMatchingBlockEnd(int offset) throws BadLocationException {
    StringBuffer result;
    StringBuffer whiteSpace = new StringBuffer();
    int line = m_RootElement.getElementIndex(offset);
    int i = m_RootElement.getElement(line).getStartOffset();

    while (true) {
      String temp = m_Self.getText(i, 1);

      if (temp.equals(" ") || temp.equals("\t")) {
        whiteSpace.append(temp);
        i++;
      } else {
        break;
      }
    }

    // assemble string
    result = new StringBuffer();
    result.append(m_BlockStart);
    result.append("\n");
    result.append(whiteSpace.toString());
    if (m_UseBlanks) result.append(m_Indentation);
    else result.append("\t");
    result.append("\n");
    result.append(whiteSpace.toString());
    result.append(m_BlockEnd);

    return result.toString();
  }
Example #16
0
  /** Paints one view that corresponds to a line (or multiple lines if folding takes effect). */
  private void paintView(View view, Graphics g, int yBase) {
    JTextComponent component = editorUI.getComponent();
    if (component == null) return;
    BaseTextUI textUI = (BaseTextUI) component.getUI();

    Element rootElem = textUI.getRootView(component).getElement();
    int line = rootElem.getElementIndex(view.getStartOffset());

    String annotation = ""; // NOI18N
    AnnotateLine al = null;
    if (!elementAnnotations.isEmpty()) {
      al = getAnnotateLine(line);
      if (al != null) {
        annotation = getDisplayName(al); // NOI18N
      }
    } else {
      annotation = elementAnnotationsSubstitute;
    }

    if (al != null && al.getRevision().equals(recentRevision)) {
      g.setColor(selectedColor());
    } else {
      g.setColor(foregroundColor());
    }
    int texty = yBase + editorUI.getLineAscent();
    int textx = 2;
    g.drawString(annotation, textx, texty);
  }
  /**
   * 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);
    }
  }
 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;
   }
 }
Example #19
0
  /*
   *  We need to know if the caret is currently positioned on the line we
   *  are about to paint so the line number can be highlighted.
   */
  private boolean isCurrentLine(int rowStartOffset) {
    int caretPosition = component.getCaretPosition();
    Element root = component.getDocument().getDefaultRootElement();

    if (root.getElementIndex(rowStartOffset) == root.getElementIndex(caretPosition)) return true;
    else return false;
  }
Example #20
0
 private void analyseDocument(Document document, int lineNum, PythonIndentation indentationLogic)
     throws BadLocationException {
   Element map = document.getDefaultRootElement();
   int endPos = map.getElement(lineNum).getEndOffset();
   indentationLogic.reset();
   indentationLogic.addText(document.getText(0, endPos));
 }
Example #21
0
    private static int getNSVisualPosition(EditorPane txt, int pos, int direction) {
      Element root = txt.getDocument().getDefaultRootElement();
      int numLines = root.getElementIndex(txt.getDocument().getLength() - 1) + 1;
      int line = root.getElementIndex(pos) + 1;
      int tarLine = direction == SwingConstants.NORTH ? line - 1 : line + 1;
      try {
        if (tarLine <= 0) {
          return 0;
        }
        if (tarLine > numLines) {
          return txt.getDocument().getLength();
        }

        Rectangle curRect = txt.modelToView(pos);
        Rectangle tarEndRect;
        if (tarLine < numLines) {
          tarEndRect = txt.modelToView(txt.getLineStartOffset(tarLine) - 1);
        } else {
          tarEndRect = txt.modelToView(txt.getDocument().getLength() - 1);
        }
        Debug.log(9, "curRect: " + curRect + ", tarEnd: " + tarEndRect);

        if (curRect.x > tarEndRect.x) {
          pos = txt.viewToModel(new Point(tarEndRect.x, tarEndRect.y));
        } else {
          pos = txt.viewToModel(new Point(curRect.x, tarEndRect.y));
        }
      } catch (BadLocationException e) {
        Debug.error(me + "Problem getting next visual position\n%s", e.getMessage());
      }

      return pos;
    }
  /**
   * Returns the start of the word at the given offset.
   *
   * @param textArea The text area.
   * @param offs The offset into the text area's content.
   * @return The start offset of the word.
   * @throws BadLocationException If <code>offs</code> is invalid.
   * @see #getWordEnd(RSyntaxTextArea, int)
   */
  public static int getWordStart(RSyntaxTextArea textArea, int offs) throws BadLocationException {

    Document doc = textArea.getDocument();
    Element line = getLineElem(doc, offs);
    if (line == null) {
      throw new BadLocationException("No word at " + offs, offs);
    }

    int lineStart = line.getStartOffset();
    if (offs == lineStart) { // Start of the line.
      return offs;
    }

    int endOffs = Math.min(offs + 1, doc.getLength());
    String s = doc.getText(lineStart, endOffs - lineStart);
    if (s != null && s.length() > 0) {
      int i = s.length() - 1;
      char ch = s.charAt(i);
      if (Character.isWhitespace(ch)) {
        while (i > 0 && Character.isWhitespace(s.charAt(i - 1))) {
          i--;
        }
        offs = lineStart + i;
      } else if (Character.isLetterOrDigit(ch)) {
        while (i > 0 && Character.isLetterOrDigit(s.charAt(i - 1))) {
          i--;
        }
        offs = lineStart + i;
      }
    }

    return offs;
  }
  /**
   * Returns the bounding box (in the current view) of a specified position in the model. This
   * method is designed for line-wrapped views to use, as it allows you to specify a "starting
   * position" in the line, from which the x-value is assumed to be zero. The idea is that you
   * specify the first character in a physical line as <code>p0</code>, as this is the character
   * where the x-pixel value is 0.
   *
   * @param textArea The text area containing the text.
   * @param s A segment in which to load the line. This is passed in so we don't have to reallocate
   *     a new <code>Segment</code> for each call.
   * @param p0 The starting position in the physical line in the document.
   * @param p1 The position for which to get the bounding box in the view.
   * @param e How to expand tabs.
   * @param rect The rectangle whose x- and width-values are changed to represent the bounding box
   *     of <code>p1</code>. This is reused to keep from needlessly reallocating Rectangles.
   * @param x0 The x-coordinate (pixel) marking the left-hand border of the text. This is useful if
   *     the text area has a border, for example.
   * @return The bounding box in the view of the character <code>p1</code>.
   * @throws BadLocationException If <code>p0</code> or <code>p1</code> is not a valid location in
   *     the specified text area's document.
   * @throws IllegalArgumentException If <code>p0</code> and <code>p1</code> are not on the same
   *     line.
   */
  public static Rectangle getLineWidthUpTo(
      RSyntaxTextArea textArea, Segment s, int p0, int p1, TabExpander e, Rectangle rect, int x0)
      throws BadLocationException {

    RSyntaxDocument doc = (RSyntaxDocument) textArea.getDocument();

    // Ensure p0 and p1 are valid document positions.
    if (p0 < 0) throw new BadLocationException("Invalid document position", p0);
    else if (p1 > doc.getLength()) throw new BadLocationException("Invalid document position", p1);

    // Ensure p0 and p1 are in the same line, and get the start/end
    // offsets for that line.
    Element map = doc.getDefaultRootElement();
    int lineNum = map.getElementIndex(p0);
    // We do ">1" because p1 might be the first position on the next line
    // or the last position on the previous one.
    // if (lineNum!=map.getElementIndex(p1))
    if (Math.abs(lineNum - map.getElementIndex(p1)) > 1)
      throw new IllegalArgumentException(
          "p0 and p1 are not on the " + "same line (" + p0 + ", " + p1 + ").");

    // Get the token list.
    Token t = doc.getTokenListForLine(lineNum);

    // Modify the token list 't' to begin at p0 (but still have correct
    // token types, etc.), and get the x-location (in pixels) of the
    // beginning of this new token list.
    makeTokenListStartAt(t, p0, e, textArea, 0);

    rect = t.listOffsetToView(textArea, e, p1, x0, rect);
    return rect;
  }
 /**
  * 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 #25
0
 /**
  * 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);
 }
Example #26
0
  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;
  }
Example #27
0
  /*
   *	Get the line number to be drawn. The empty string will be returned
   *  when a line of text has wrapped.
   */
  protected String getTextLineNumber(int rowStartOffset) {
    Element root = component.getDocument().getDefaultRootElement();
    int index = root.getElementIndex(rowStartOffset);
    Element line = root.getElement(index);

    if (line.getStartOffset() == rowStartOffset) return String.valueOf(index + 1);
    else return "";
  }
 public void removeElement(Element e) {
   try {
     Document doc = getEditorPnl().getEditor().getDocument();
     doc.remove(e.getStartOffset(), e.getEndOffset() - e.getStartOffset());
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
 private void configureBand(final javax.swing.text.Element textElement, final Band band) {
   if ("paragraph".equals(textElement.getName()) || "section".equals(textElement.getName())) {
     band.getStyle().setStyleProperty(BandStyleKeys.LAYOUT, "block");
     band.getStyle().setStyleProperty(ElementStyleKeys.MIN_WIDTH, new Float(-100));
   } else {
     band.getStyle().setStyleProperty(BandStyleKeys.LAYOUT, "inline");
   }
 }
 /**
  * Loads all of the children to initialize the view. This is called by the <code>setParent</code>
  * method. Subclasses can re-implement this to initialize their child views in a different manner.
  * The default implementation creates a child view for each child element.
  *
  * @param f the view factory
  */
 protected void loadChildren(ViewFactory f) {
   Element e = getElement();
   int n = e.getElementCount();
   if (n > 0) {
     View[] added = new View[n];
     for (int i = 0; i < n; i++) added[i] = new WrappedLine(e.getElement(i));
     replace(0, 0, added);
   }
 }