Exemplo n.º 1
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.º 2
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.º 3
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.º 4
0
 public void appendToEnd(String text) {
   Element root = document.getDefaultRootElement();
   try {
     document.insertAfterEnd(root.getElement(root.getElementCount() - 1), text);
   } catch (BadLocationException e) {
     logger.error("Insert in the HTMLDocument failed.", e);
   } catch (IOException e) {
     logger.error("Insert in the HTMLDocument failed.", e);
   }
 }
Exemplo n.º 5
0
  public void insertAfterStart(String text) {
    Element root = this.document.getDefaultRootElement();

    try {
      this.document.insertBeforeStart(root.getElement(0), text);
    } catch (BadLocationException e) {
      logger.error("Insert in the HTMLDocument failed.", e);
    } catch (IOException e) {
      logger.error("Insert in the HTMLDocument failed.", e);
    }
  }
Exemplo n.º 6
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.º 7
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.º 8
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.º 9
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.º 10
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.º 11
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.º 12
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.º 13
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.º 14
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.º 15
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.º 16
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());
      }
    }