Exemplo n.º 1
1
  private void updateTemplateFromEditor(PrintfTemplate template) {
    ArrayList params = new ArrayList();
    String format = null;
    int text_length = editorPane.getDocument().getLength();
    try {
      format = editorPane.getDocument().getText(0, text_length);
    } catch (BadLocationException ex1) {
    }
    Element section_el = editorPane.getDocument().getDefaultRootElement();
    // Get number of paragraphs.
    int num_para = section_el.getElementCount();
    for (int p_count = 0; p_count < num_para; p_count++) {
      Element para_el = section_el.getElement(p_count);
      // Enumerate the content elements
      int num_cont = para_el.getElementCount();
      for (int c_count = 0; c_count < num_cont; c_count++) {
        Element content_el = para_el.getElement(c_count);
        AttributeSet attr = content_el.getAttributes();
        // Get the name of the style applied to this content element; may be null
        String sn = (String) attr.getAttribute(StyleConstants.NameAttribute);
        // Check if style name match
        if (sn != null && sn.startsWith("Parameter")) {
          // we extract the label.
          JLabel l = (JLabel) StyleConstants.getComponent(attr);
          if (l != null) {
            params.add(l.getName());
          }
        }
      }
    }

    template.setFormat(format);
    template.setTokens(params);
  }
Exemplo n.º 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);
    }
Exemplo n.º 3
0
 public Element getLineAtCaret(int caretPosition) {
   Element root = getDocument().getDefaultRootElement();
   if (caretPosition == -1) {
     return root.getElement(root.getElementIndex(getCaretPosition()));
   } else {
     return root.getElement(root.getElementIndex(root.getElementIndex(caretPosition)));
   }
 }
Exemplo n.º 4
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;
  }
Exemplo n.º 5
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));
 }
Exemplo n.º 6
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 "";
  }
Exemplo n.º 7
0
  /*
   *  Determine the Y offset for the current row
   */
  private int getOffsetY(int rowStartOffset, FontMetrics fontMetrics) throws BadLocationException {
    //  Get the bounding rectangle of the row

    Rectangle r = component.modelToView(rowStartOffset);
    int lineHeight = fontMetrics.getHeight();
    int y = r.y + r.height;
    int descent = 0;

    //  The text needs to be positioned above the bottom of the bounding
    //  rectangle based on the descent of the font(s) contained on the row.

    if (r.height == lineHeight) // default font is being used
    {
      descent = fontMetrics.getDescent();
    } else // We need to check all the attributes for font changes
    {
      if (fonts == null) fonts = new HashMap<String, FontMetrics>();

      Element root = component.getDocument().getDefaultRootElement();
      int index = root.getElementIndex(rowStartOffset);
      Element line = root.getElement(index);

      for (int i = 0; i < line.getElementCount(); i++) {
        Element child = line.getElement(i);
        AttributeSet as = child.getAttributes();
        String fontFamily = (String) as.getAttribute(StyleConstants.FontFamily);
        Integer fontSize = (Integer) as.getAttribute(StyleConstants.FontSize);
        String key = fontFamily + fontSize;

        FontMetrics fm = fonts.get(key);

        if (fm == null) {
          Font font = new Font(fontFamily, Font.PLAIN, fontSize);
          fm = component.getFontMetrics(font);
          fonts.put(key, fm);
        }

        descent = Math.max(descent, fm.getDescent());
      }
    }

    return y - descent;
  }
Exemplo n.º 8
0
  /** Returns the selected text, or null if no selection is active. */
  public final String getSelectedText() {
    if (selectionStart == selectionEnd) return null;

    if (rectSelect) {
      // Return each row of the selection on a new line

      Element map = document.getDefaultRootElement();

      int start = selectionStart - map.getElement(selectionStartLine).getStartOffset();
      int end = selectionEnd - map.getElement(selectionEndLine).getStartOffset();

      // Certain rectangles satisfy this condition...
      if (end < start) {
        int tmp = end;
        end = start;
        start = tmp;
      }

      StringBuffer buf = new StringBuffer();
      Segment seg = new Segment();

      for (int i = selectionStartLine; i <= selectionEndLine; i++) {
        Element lineElement = map.getElement(i);
        int lineStart = lineElement.getStartOffset();
        int lineEnd = lineElement.getEndOffset() - 1;
        int lineLen = lineEnd - lineStart;

        lineStart = Math.min(lineStart + start, lineEnd);
        lineLen = Math.min(end - start, lineEnd - lineStart);

        getText(lineStart, lineLen, seg);
        buf.append(seg.array, seg.offset, seg.count);

        if (i != selectionEndLine) buf.append('\n');
      }

      return buf.toString();
    } else {
      return getText(selectionStart, selectionEnd - selectionStart);
    }
  }
Exemplo n.º 9
0
 public boolean reparseCheckContent() {
   Element e = this.getDocument().getDefaultRootElement();
   String txt;
   if (e.getElementCount() > 2) {
     return false;
   } else if (e.getElement(1).getEndOffset() - e.getElement(1).getStartOffset() > 1) {
     return false;
   } else {
     int is = e.getElement(0).getStartOffset();
     int ie = e.getElement(0).getEndOffset();
     try {
       txt = e.getElement(0).getDocument().getText(is, ie - 1);
       if (txt.endsWith(Settings.TypeCommentToken)) {
         return true;
       }
     } catch (BadLocationException ex) {
       return false;
     }
   }
   return false;
 }
Exemplo n.º 10
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();
   }
 }
Exemplo n.º 11
0
 public Element getLineAtPoint(MouseEvent me) {
   Point p = me.getLocationOnScreen();
   Point pp = getLocationOnScreen();
   p.translate(-pp.x, -pp.y);
   int pos = viewToModel(p);
   Element root = getDocument().getDefaultRootElement();
   int e = root.getElementIndex(pos);
   if (e == -1) {
     return null;
   }
   return root.getElement(e);
 }
Exemplo n.º 12
0
    public void actionPerformed(JTextComponent text) {
      indentationLogic = ((EditorPane) text).getIndentationLogic();
      StyledDocument doc = (StyledDocument) text.getDocument();
      Element map = doc.getDefaultRootElement();
      Caret c = text.getCaret();
      int dot = c.getDot();
      int mark = c.getMark();
      int line1 = map.getElementIndex(dot);

      if (dot != mark) {
        int line2 = map.getElementIndex(mark);
        int begin = Math.min(line1, line2);
        int end = Math.max(line1, line2);
        Element elem;
        try {
          for (line1 = begin; line1 < end; line1++) {
            elem = map.getElement(line1);
            handleDecreaseIndent(line1, elem, doc);
          }
          elem = map.getElement(end);
          int start = elem.getStartOffset();
          if (Math.max(c.getDot(), c.getMark()) != start) {
            handleDecreaseIndent(end, elem, doc);
          }
        } catch (BadLocationException ble) {
          Debug.error(me + "Problem while de-indenting line\n%s", ble.getMessage());
          UIManager.getLookAndFeel().provideErrorFeedback(text);
        }
      } else {
        Element elem = map.getElement(line1);
        try {
          handleDecreaseIndent(line1, elem, doc);
        } catch (BadLocationException ble) {
          Debug.error(me + "Problem while de-indenting line\n%s", ble.getMessage());
          UIManager.getLookAndFeel().provideErrorFeedback(text);
        }
      }
    }
Exemplo n.º 13
0
    public void actionPerformed(JTextComponent text) {
      indentationLogic = ((EditorPane) text).getIndentationLogic();
      boolean indentError = false;
      Document doc = text.getDocument();
      Element map = doc.getDefaultRootElement();
      String tabWhitespace = PreferencesUser.getInstance().getTabWhitespace();
      Caret c = text.getCaret();
      int dot = c.getDot();
      int mark = c.getMark();
      int dotLine = map.getElementIndex(dot);
      int markLine = map.getElementIndex(mark);

      if (dotLine != markLine) {
        int first = Math.min(dotLine, markLine);
        int last = Math.max(dotLine, markLine);
        Element elem;
        int start;
        try {
          for (int i = first; i < last; i++) {
            elem = map.getElement(i);
            start = elem.getStartOffset();
            doc.insertString(start, tabWhitespace, null);
          }
          elem = map.getElement(last);
          start = elem.getStartOffset();
          if (Math.max(c.getDot(), c.getMark()) != start) {
            doc.insertString(start, tabWhitespace, null);
          }
        } catch (BadLocationException ble) {
          Debug.error(me + "Problem while indenting line\n%s", ble.getMessage());
          UIManager.getLookAndFeel().provideErrorFeedback(text);
        }
      } else {
        text.replaceSelection(tabWhitespace);
      }
    }
Exemplo n.º 14
0
 public void caretUpdate(CaretEvent e) {
   // when the cursor moves on _textView
   // this method will be called. Then, we
   // must determine what the line number is
   // and update the line number view
   Element root = textView.getDocument().getDefaultRootElement();
   int line = root.getElementIndex(e.getDot());
   root = root.getElement(line);
   int col = root.getElementIndex(e.getDot());
   lineNumberView.setText(line + ":" + col);
   // if text is selected then enable copy and cut
   boolean isSelection = e.getDot() != e.getMark();
   copyAction.setEnabled(isSelection);
   cutAction.setEnabled(isSelection);
 }
Exemplo n.º 15
0
 private void parse(Element node) {
   if (!showThumbs) {
     // do not show any thumbnails
     return;
   }
   int count = node.getElementCount();
   for (int i = 0; i < count; i++) {
     Element elm = node.getElement(i);
     Debug.log(8, elm.toString());
     if (elm.isLeaf()) {
       int start = elm.getStartOffset(), end = elm.getEndOffset();
       parseRange(start, end);
     } else {
       parse(elm);
     }
   }
 }
Exemplo n.º 16
0
    private String addWhiteSpace(Document doc, int offset) throws BadLocationException {
      StringBuilder whiteSpace = new StringBuilder("\n");
      Element rootElement = doc.getDefaultRootElement();
      int line = rootElement.getElementIndex(offset);
      int i = rootElement.getElement(line).getStartOffset();

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

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

      return whiteSpace.toString();
    }
Exemplo n.º 17
0
 private void checkCompletion(java.awt.event.KeyEvent ke) throws BadLocationException {
   Document doc = getDocument();
   Element root = doc.getDefaultRootElement();
   int pos = getCaretPosition();
   int lineIdx = root.getElementIndex(pos);
   Element line = root.getElement(lineIdx);
   int start = line.getStartOffset(), len = line.getEndOffset() - start;
   String strLine = doc.getText(start, len - 1);
   Debug.log(9, "[" + strLine + "]");
   if (strLine.endsWith("find") && ke.getKeyChar() == '(') {
     ke.consume();
     doc.insertString(pos, "(", null);
     ButtonCapture btnCapture = new ButtonCapture(this, line);
     insertComponent(btnCapture);
     doc.insertString(pos + 2, ")", null);
   }
 }
Exemplo n.º 18
0
 private int getFunctionStartOffset(String func, Element node) throws BadLocationException {
   Document doc = getDocument();
   int count = node.getElementCount();
   Pattern patDef = Pattern.compile("def\\s+" + func + "\\s*\\(");
   for (int i = 0; i < count; i++) {
     Element elm = node.getElement(i);
     if (elm.isLeaf()) {
       int start = elm.getStartOffset(), end = elm.getEndOffset();
       String line = doc.getText(start, end - start);
       Matcher matcher = patDef.matcher(line);
       if (matcher.find()) {
         return start;
       }
     } else {
       int p = getFunctionStartOffset(func, elm);
       if (p >= 0) {
         return p;
       }
     }
   }
   return -1;
 }
Exemplo n.º 19
0
    private void insertNewlineWithAutoIndent(JTextComponent text) {
      try {
        int caretPos = text.getCaretPosition();
        StyledDocument doc = (StyledDocument) text.getDocument();
        Element map = doc.getDefaultRootElement();
        int lineNum = map.getElementIndex(caretPos);
        Element line = map.getElement(lineNum);
        int start = line.getStartOffset();
        int end = line.getEndOffset() - 1;
        int len = end - start;
        String s = doc.getText(start, len);

        String leadingWS = PythonIndentation.getLeadingWhitespace(doc, start, caretPos - start);
        StringBuffer sb = new StringBuffer("\n");
        sb.append(leadingWS);
        // TODO better control over automatic indentation
        indentationLogic.checkIndent(leadingWS, lineNum + 1);

        // If there is only whitespace between the caret and
        // the EOL, pressing Enter auto-indents the new line to
        // the same place as the previous line.
        int nonWhitespacePos = PythonIndentation.atEndOfLine(doc, caretPos, start, s, len);
        if (nonWhitespacePos == -1) {
          if (leadingWS.length() == len) {
            // If the line was nothing but whitespace, select it
            // so its contents get removed.
            text.setSelectionStart(start);
          } else {
            // Select the whitespace between the caret and the EOL
            // to remove it
            text.setSelectionStart(caretPos);
          }
          text.setSelectionEnd(end);
          text.replaceSelection(sb.toString());
          // auto-indentation for python statements like if, while, for, try,
          // except, def, class and auto-deindentation for break, continue,
          // pass, return
          analyseDocument(doc, lineNum, indentationLogic);
          // auto-completion: add colon if it is obvious
          if (indentationLogic.shouldAddColon()) {
            doc.insertString(caretPos, ":", null);
            indentationLogic.setLastLineEndsWithColon();
          }
          int lastLineChange = indentationLogic.shouldChangeLastLineIndentation();
          int nextLineChange = indentationLogic.shouldChangeNextLineIndentation();
          if (lastLineChange != 0) {
            Debug.log(5, "change line %d indentation by %d columns", lineNum + 1, lastLineChange);
            changeIndentation((DefaultStyledDocument) doc, lineNum, lastLineChange);
            // nextLineChange was determined based on indentation of last line before
            // the change
            nextLineChange += lastLineChange;
          }
          if (nextLineChange != 0) {
            Debug.log(5, "change line %d indentation by %d columns", lineNum + 2, nextLineChange);
            changeIndentation((DefaultStyledDocument) doc, lineNum + 1, nextLineChange);
          }
        } // If there is non-whitespace between the caret and the
        // EOL, pressing Enter takes that text to the next line
        // and auto-indents it to the same place as the last
        // line. Additional auto-indentation or dedentation for
        // specific python statements is only done for the next line.
        else {
          text.setCaretPosition(nonWhitespacePos);
          doc.insertString(nonWhitespacePos, sb.toString(), null);
          analyseDocument(doc, lineNum, indentationLogic);
          int nextLineChange = indentationLogic.shouldChangeNextLineIndentation();
          if (nextLineChange != 0) {
            Debug.log(5, "change line %d indentation by %d columns", lineNum + 2, nextLineChange);
            changeIndentation((DefaultStyledDocument) doc, lineNum + 1, nextLineChange);
          }
        }

      } catch (BadLocationException ble) {
        text.replaceSelection("\n");
        Debug.error(me + "Problem while inserting new line with auto-indent\n%s", ble.getMessage());
      }
    }
Exemplo n.º 20
0
  /**
   * Replaces the selection with the specified text.
   *
   * @param selectedText The replacement text for the selection
   */
  public void setSelectedText(String selectedText) {
    if (!editable) {
      throw new InternalError("Text component" + " read only");
    }

    document.beginCompoundEdit();

    try {
      if (rectSelect) {
        Element map = document.getDefaultRootElement();

        int start = selectionStart - map.getElement(selectionStartLine).getStartOffset();
        int end = selectionEnd - map.getElement(selectionEndLine).getStartOffset();

        // Certain rectangles satisfy this condition...
        if (end < start) {
          int tmp = end;
          end = start;
          start = tmp;
        }

        int lastNewline = 0;
        int currNewline = 0;

        for (int i = selectionStartLine; i <= selectionEndLine; i++) {
          Element lineElement = map.getElement(i);
          int lineStart = lineElement.getStartOffset();
          int lineEnd = lineElement.getEndOffset() - 1;
          int rectStart = Math.min(lineEnd, lineStart + start);

          document.remove(rectStart, Math.min(lineEnd - rectStart, end - start));

          if (selectedText == null) continue;

          currNewline = selectedText.indexOf('\n', lastNewline);
          if (currNewline == -1) currNewline = selectedText.length();

          document.insertString(rectStart, selectedText.substring(lastNewline, currNewline), null);

          lastNewline = Math.min(selectedText.length(), currNewline + 1);
        }

        if (selectedText != null && currNewline != selectedText.length()) {
          int offset = map.getElement(selectionEndLine).getEndOffset() - 1;
          document.insertString(offset, "\n", null);
          document.insertString(offset + 1, selectedText.substring(currNewline + 1), null);
        }
      } else {
        document.remove(selectionStart, selectionEnd - selectionStart);
        if (selectedText != null) {
          document.insertString(selectionStart, selectedText, null);
        }
      }
    } catch (BadLocationException bl) {
      bl.printStackTrace();
      throw new InternalError("Cannot replace" + " selection");
    }
    // No matter what happends... stops us from leaving document
    // in a bad state
    finally {
      document.endCompoundEdit();
    }

    setCaretPosition(selectionEnd);
  }