@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());
  }
Exemple #2
1
    // 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);
    }
  /** 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;
  }
Exemple #4
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;
   }
 }
 public void removeElement(Element e) {
   try {
     Document doc = getEditorPnl().getEditor().getDocument();
     doc.remove(e.getStartOffset(), e.getEndOffset() - e.getStartOffset());
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
  /**
   * Provides a mapping from the view coordinate space to the logical coordinate space of the model.
   *
   * @param fx the X coordinate &gt;= 0
   * @param fy the Y coordinate &gt;= 0
   * @param a the allocated region to render into
   * @return the location within the model that best represents the given point in the view &gt;= 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.
  }
 /**
  * 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();
 }
  /**
   * 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;
  }
  /** 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--;
      }
    }
  }
Exemple #10
0
 private int getRealEnd() {
   //		if ( end != null) {
   return end.getParentElement().getElementIndex(end.getStartOffset());
   //		} else {
   //			return start.getParentElement().getElementCount();
   //		}
 }
 /**
  * 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);
 }
  /**
   * Highlight lines to start or end delimiter.
   *
   * @param content the content to parse
   * @param line the line number
   * @throws BadLocationException if offsets are wrong
   */
  protected void highlightLinesAfter(String content, int line) throws BadLocationException {
    int offset = m_RootElement.getElement(line).getEndOffset();

    // Start/End delimiter not found, nothing to do

    int startDelimiter = -1;
    int endDelimiter = -1;
    if (getMultiLineComment()) {
      startDelimiter = indexOf(content, getMultiLineCommentStart(), offset);
      endDelimiter = indexOf(content, getMultiLineCommentEnd(), offset);
    }

    if (startDelimiter < 0) startDelimiter = content.length();

    if (endDelimiter < 0) endDelimiter = content.length();

    int delimiter = Math.min(startDelimiter, endDelimiter);

    if (delimiter < offset) return;

    // Start/End delimiter found, reapply highlighting

    int endLine = m_RootElement.getElementIndex(delimiter);

    for (int i = line + 1; i < endLine; i++) {
      Element branch = m_RootElement.getElement(i);
      Element leaf = m_Self.getCharacterElement(branch.getStartOffset());
      AttributeSet as = leaf.getAttributes();

      if (as.isEqual(DEFAULT_COMMENT)) applyHighlighting(content, i);
    }
  }
  /**
   * 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);
        }
      }
    }
  }
  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;
  }
  /**
   * 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);
    }
  }
Exemple #16
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;
     }
   }
 }
 /**
  * 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();
 }
Exemple #19
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;
    }
  }
  /**
   * 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;
  }
 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;
   }
 }
Exemple #22
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;
  }
Exemple #23
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 "";
  }
 void editorPane_keyPressed(KeyEvent e) {
   StyledDocument doc = editorPane.getStyledDocument();
   int pos = editorPane.getCaretPosition();
   int code = e.getKeyCode();
   Element el;
   switch (code) {
     case KeyEvent.VK_BACK_SPACE:
     case KeyEvent.VK_DELETE:
     case KeyEvent.VK_LEFT:
     case KeyEvent.VK_KP_LEFT:
       if (pos == 0) return;
       // we want to get the element to the left of position.
       el = doc.getCharacterElement(pos - 1);
       break;
     case KeyEvent.VK_RIGHT:
     case KeyEvent.VK_KP_RIGHT:
       // we want to get the element to the right of position.
       el = doc.getCharacterElement(pos + 1);
       break;
     default:
       return; // bail we don't handle it.
   }
   AttributeSet attr = el.getAttributes();
   String el_name = (String) attr.getAttribute(StyleConstants.NameAttribute);
   int el_range = el.getEndOffset() - el.getStartOffset() - 1;
   if (el_name.startsWith("Parameter") && StyleConstants.getComponent(attr) != null) {
     try {
       switch (code) {
         case KeyEvent.VK_BACK_SPACE:
         case KeyEvent.VK_DELETE:
           doc.remove(el.getStartOffset(), el_range);
           break;
         case KeyEvent.VK_LEFT:
         case KeyEvent.VK_KP_LEFT:
           editorPane.setCaretPosition(pos - el_range);
           break;
         case KeyEvent.VK_RIGHT:
         case KeyEvent.VK_KP_RIGHT:
           editorPane.setCaretPosition(pos + (el_range));
           break;
       }
     } catch (BadLocationException ex) {
     }
   }
 }
 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;
 }
  /**
   * Determine the area of the document whose syntax highlighting is impacted by the change of
   * source content
   *
   * @param offset The initial offset of the change
   * @param length The length of the change
   * @throws BadLocationException If the change processing fails
   */
  public void processChangedLines(int offset, int length) throws BadLocationException {

    Element line;
    int startOffset = offset;
    int changeOffset = offset;
    int changeLength = length;
    MutableAttributeSet highlight = getStyle(InformSyntax.Normal.getName());
    MutableAttributeSet tokenCheck = getStyle(InformSyntax.Normal.getName());

    // Locate start of first highlight token at insert/remove offset

    if (changeOffset > 0) {

      // Check for the element before the insertion/removal point (offset-1) so if the
      // insertion/removal point is at the boundary of two elements we get the previous
      // highlight token not the following highlight token

      Element token = getCharacterElement(offset - 1);
      startOffset = token.getStartOffset();
      highlight = (MutableAttributeSet) token.getAttributes();

      tokenCheck = getStyle((String) highlight.getAttribute(AttributeSet.NameAttribute));

      while (highlight.containsAttributes(tokenCheck) && changeOffset > 0) {
        changeOffset = startOffset;
        token = getCharacterElement(changeOffset - 1);
        startOffset = token.getStartOffset();
        highlight = (MutableAttributeSet) token.getAttributes();
      }
    }

    // Find the length of the text in the document impacted by the insert/remove.
    // The length of the text between the start of the first highlight token at the insert point
    // to the end of the current line plus the length of the text being inserted into the document.

    if (length > 0) {
      line = getParagraphElement(offset + length);
    } else {
      line = getParagraphElement(offset);
    }
    changeLength = line.getEndOffset() - changeOffset;

    applyHighlighting(changeOffset, changeLength);
  }
 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();
 }
Exemple #28
0
  /** 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;
  }
Exemple #29
0
 public int getLineStartOffset(int line) throws BadLocationException {
   // line starting from 0
   Element map = getDocument().getDefaultRootElement();
   if (line < 0) {
     throw new BadLocationException("Negative line", -1);
   } else if (line >= map.getElementCount()) {
     throw new BadLocationException("No such line", getDocument().getLength() + 1);
   } else {
     Element lineElem = map.getElement(line);
     return lineElem.getStartOffset();
   }
 }
Exemple #30
0
 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);
   }
 }