public void search() {
    hilit.removeAllHighlights();

    String s = entry.getText();
    if (s.length() <= 0) {
      message("Nothing to search");
      return;
    }

    String content = textArea.getText();
    int index = content.indexOf(s, 0);
    if (index >= 0) {
      try {
        int end = index + s.length();
        hilit.addHighlight(index, end, painter);
        textArea.setCaretPosition(end);
        entry.setBackground(entryBg);
        message("'" + s + "' found. Press ESC to end search");
      } catch (BadLocationException e) {
        e.printStackTrace();
      }
    } else {
      entry.setBackground(ERROR_COLOR);
      message("'" + s + "' found. Press ESC to start a new search");
    }
  }
Example #2
0
  /**
   * Similar to <code>setSelectedText()</code>, but overstrikes the appropriate number of characters
   * if overwrite mode is enabled.
   *
   * @param str The string
   * @see #setSelectedText(String)
   * @see #isOverwriteEnabled()
   */
  public void overwriteSetSelectedText(String str) {
    // Don't overstrike if there is a selection
    if (!overwrite || selectionStart != selectionEnd) {
      setSelectedText(str);
      return;
    }

    // Don't overstrike if we're on the end of
    // the line
    int caret = getCaretPosition();
    int caretLineEnd = getLineEndOffset(getCaretLine());
    if (caretLineEnd - caret <= str.length()) {
      setSelectedText(str);
      return;
    }

    document.beginCompoundEdit();

    try {
      document.remove(caret, str.length());
      document.insertString(caret, str, null);
    } catch (BadLocationException bl) {
      bl.printStackTrace();
    } finally {
      document.endCompoundEdit();
    }
  }
Example #3
0
    public void mousePressed(MouseEvent evt) {
      requestFocus();

      // Focus events not fired sometimes?
      setCaretVisible(true);
      focusedComponent = JEditTextArea.this;

      if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0 && popup != null) {
        popup.show(painter, evt.getX(), evt.getY());
        return;
      }

      int line = yToLine(evt.getY());
      int offset = xToOffset(line, evt.getX());
      int dot = getLineStartOffset(line) + offset;

      switch (evt.getClickCount()) {
        case 1:
          doSingleClick(evt, line, offset, dot);
          break;
        case 2:
          // It uses the bracket matching stuff, so
          // it can throw a BLE
          try {
            doDoubleClick(evt, line, offset, dot);
          } catch (BadLocationException bl) {
            bl.printStackTrace();
          }
          break;
        case 3:
          doTripleClick(evt, line, offset, dot);
          break;
      }
    }
Example #4
0
    // ----------------------------------------------------
    // return last location found
    public int searchBackward(String lastFindStr) {
      try { // backward
        if (isFindAgain) { // otherwise you find same string
          int foo = lastFindIndex; // begining of word
          if (foo >= 0) {
            editor1.setCaretPosition(foo);
          }
          // System.out.println("Debug:TextViewer:searchBackward: lastFindIndex: "+foo);
        }

        int carPos = editor1.getCaretPosition();
        // search backward
        // todo: should we use the getText(pos,len,segment);
        String chunk1 = editor1.getDocument().getText(0, carPos);
        int lastFindIndexTemp = chunk1.lastIndexOf(lastFindStr);
        if (lastFindIndexTemp == -1) {
          boolean okPressed = okCancelPopup.display("TextViewer:string not found. Try forward?");
          // handle forward
          if (okPressed) {
            forwardFindDirection = true;
            lastFindIndex = searchForward(lastFindStr);
          }
        } else {
          lastFindIndex = lastFindIndexTemp;
          editor1.setCaretPosition(lastFindIndex); // ready to type in body
          editor1.moveCaretPosition(lastFindIndex + lastFindStr.length()); // ready to type in body
        }
      } catch (BadLocationException badexception) {
        String errstr = "TextViewer:searchBackward: " + badexception.getMessage();
        warningPopup.display(errstr);
        return (-1);
      }
      return (lastFindIndex);
    }
Example #5
0
 /** Returns the entire text of this text area. */
 public String getText() {
   try {
     return document.getText(0, document.getLength());
   } catch (BadLocationException bl) {
     bl.printStackTrace();
     return null;
   }
 }
Example #6
0
 /**
  * Returns the specified substring of the document.
  *
  * @param start The start offset
  * @param len The length of the substring
  * @return The substring, or null if the offsets are invalid
  */
 public final String getText(int start, int len) {
   try {
     return document.getText(start, len);
   } catch (BadLocationException bl) {
     bl.printStackTrace();
     return null;
   }
 }
Example #7
0
 /**
  * Copies the specified substring of the document into a segment. If the offsets are invalid, the
  * segment will contain a null string.
  *
  * @param start The start offset
  * @param len The length of the substring
  * @param segment The segment
  */
 public final void getText(int start, int len, Segment segment) {
   try {
     document.getText(start, len, segment);
   } catch (BadLocationException bl) {
     bl.printStackTrace();
     segment.offset = segment.count = 0;
   }
 }
Example #8
0
 private void moveCursorToTest(Test test) {
   if (test instanceof TestCase) {
     String func = ((TestCase) test).getName();
     try {
       SikuliIDE.getInstance().jumpTo(func);
     } catch (BadLocationException e) {
       e.printStackTrace();
     }
   }
 }
Example #9
0
 /**
  * Makes a <code>Segment</code> point to the text in our document between the given positions.
  * Note that the positions MUST be valid positions in the document.
  *
  * @param p0 The first position in the document.
  * @param p1 The second position in the document.
  * @param document The document from which you want to get the text.
  * @param seg The segment in which to load the text.
  */
 private void setSegment(int p0, int p1, Document document, Segment seg) {
   try {
     // System.err.println("... in setSharedSegment, p0/p1==" + p0 + "/" + p1);
     document.getText(p0, p1 - p0, seg);
     // System.err.println("... in setSharedSegment: s=='" + s + "'; line/numLines==" + line + "/"
     // + numLines);
   } catch (BadLocationException ble) { // Never happens
     ble.printStackTrace();
   }
 }
Example #10
0
 /** Sets the entire text of this text area. */
 public void setText(String text) {
   try {
     document.beginCompoundEdit();
     document.remove(0, document.getLength());
     document.insertString(0, text, null);
   } catch (BadLocationException bl) {
     bl.printStackTrace();
   } finally {
     document.endCompoundEdit();
   }
 }
Example #11
0
    @Override
    @SuppressWarnings("SleepWhileHoldingLock")
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum(doc.getLength());
        status.add(progress);
        status.revalidate();

        // start writing
        Writer out = new FileWriter(f);
        Segment text = new Segment();
        text.setPartialReturn(true);
        int charsLeft = doc.getLength();
        int offset = 0;
        while (charsLeft > 0) {
          doc.getText(offset, Math.min(4096, charsLeft), text);
          out.write(text.array, text.offset, text.count);
          charsLeft -= text.count;
          offset += text.count;
          progress.setValue(offset);
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e);
          }
        }
        out.flush();
        out.close();
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not save file: " + msg,
                    "Error saving file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();
    }
Example #12
0
    @Override
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum((int) f.length());
        status.add(progress);
        status.revalidate();

        // try to start reading
        Reader in = new FileReader(f);
        char[] buff = new char[4096];
        int nch;
        while ((nch = in.read(buff, 0, buff.length)) != -1) {
          doc.insertString(doc.getLength(), new String(buff, 0, nch), null);
          progress.setValue(progress.getValue() + nch);
        }
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not open file: " + msg,
                    "Error opening file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      doc.addUndoableEditListener(undoHandler);
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();

      resetUndoManager();

      if (elementTreePanel != null) {
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                elementTreePanel.setEditor(getEditor());
              }
            });
      }
    }
 public void actionPerformed(ActionEvent e) {
   ETextArea target = (ETextArea) getFocusedComponent();
   try {
     Document document = target.getDocument();
     int position = target.getCaretPosition();
     String whitespace = target.getIndentationOfLineAtOffset(position);
     String prefix = "{\n" + whitespace + Parameters.getParameter("indent.string");
     String suffix = "\n" + whitespace + "}";
     document.insertString(position, prefix + suffix, null);
     target.setCaretPosition(position + prefix.length());
   } catch (BadLocationException ex) {
     ex.printStackTrace();
   }
 }
Example #14
0
 /**
  * Returns a token list for the specified segment of text representing the specified line number.
  * This method is basically a wrapper for <code>tokenMaker.getTokenList</code> that takes into
  * account the last token on the previous line to assure token accuracy.
  *
  * @param line The line number of <code>text</code> in the document, >= 0.
  * @return A token list representing the specified line.
  */
 public final Token getTokenListForLine(int line) {
   Element map = getDefaultRootElement();
   Element elem = map.getElement(line);
   int startOffset = elem.getStartOffset();
   // int endOffset = (line==map.getElementCount()-1 ? elem.getEndOffset() - 1:
   //									elem.getEndOffset() - 1);
   int endOffset = elem.getEndOffset() - 1; // Why always "-1"?
   try {
     getText(startOffset, endOffset - startOffset, s);
   } catch (BadLocationException ble) {
     ble.printStackTrace();
     return null;
   }
   int initialTokenType = line == 0 ? Token.NULL : getLastTokenTypeOnLine(line - 1);
   return tokenMaker.getTokenList(s, initialTokenType, startOffset);
 }
Example #15
0
  protected void updateBracketHighlight(int newCaretPosition) {
    if (newCaretPosition == 0) {
      bracketPosition = bracketLine = -1;
      return;
    }

    try {
      int offset = TextUtilities.findMatchingBracket(document, newCaretPosition - 1);
      if (offset != -1) {
        bracketLine = getLineOfOffset(offset);
        bracketPosition = offset - getLineStartOffset(bracketLine);
        return;
      }
    } catch (BadLocationException bl) {
      bl.printStackTrace();
    }

    bracketLine = bracketPosition = -1;
  }
Example #16
0
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum((int) f2.length());
        status.add(progress);
        status.revalidate();

        // try to start reading
        Reader in = new FileReader(f2);
        char[] buff = new char[4096];
        int nch;
        while ((nch = in.read(buff, 0, buff.length)) != -1) {
          doc2.insertString(doc2.getLength(), new String(buff, 0, nch), null);
          progress.setValue(progress.getValue() + nch);
        }

        // we are done... get rid of progressbar
        // doc2.addUndoableEditListener(undoHandler);
        status.removeAll();
        status.revalidate();

        // resetUndoManager();
      } catch (IOException e) {
        System.err.println("TextViewer:FileLoader " + e.toString());
      } catch (BadLocationException e) {
        System.err.println("TextViewer:FileLoader " + e.getMessage());
      }
      /* aa
         if (elementTreePanel != null) {
         SwingUtilities.invokeLater(new Runnable() {
         public void run() {
         elementTreePanel.setEditor(getEditor());
         }
         });
         }
      */
    }
Example #17
0
    // ----------------------
    // return last location found
    public int searchForward(String lastFindStr) {
      try { // forward
        // System.out.println("Debug:TextViewer:in searchForward");
        int carPos = editor1.getCaretPosition();
        // System.out.println("Debug:TextViewer: carPos "+carPos);
        // int strLength=editor1.getDocument().getEndPosition().getOffset();
        int strLength = editor1.getDocument().getLength();
        // if ((strLength-carPos)<0) {
        // System.out.println("Debug:TextViewer: carPos "+carPos);
        // System.out.println("Debug:TextViewer: strLength "+strLength);
        // }
        // search Forward
        // todo: should we use the getText(pos,len,segment);
        String chunk1 =
            editor1.getDocument().getText(carPos, (strLength - carPos)); // offset,length

        int lastFindIndexTemp = chunk1.indexOf(lastFindStr);

        if (lastFindIndexTemp == -1) {
          boolean okPressed = okCancelPopup.display("TextViewer:string not found. Try backward?");
          // handle backward
          if (okPressed) {
            forwardFindDirection = false;
            lastFindIndex = searchBackward(lastFindStr);
            // System.out.println("Debug:TextViewer: lastFindIndex "+lastFindIndex);
          }
        } else {
          lastFindIndex = carPos + lastFindIndexTemp;
          // System.out.println("Debug:TextViewer: lastFindIndex "+lastFindIndex);
          editor1.setCaretPosition(lastFindIndex); // ready to type in body
          editor1.moveCaretPosition(lastFindIndex + lastFindStr.length()); // ready to type in body
        }
      } catch (BadLocationException badexception) {
        String errstr = "TextViewer:searchForward: " + badexception.getMessage();
        warningPopup.display(errstr);
        return (-1);
      }
      return (lastFindIndex);
    }
Example #18
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);
  }
Example #19
0
    private void doDoubleClick(MouseEvent evt, int line, int offset, int dot)
        throws BadLocationException {
      // Ignore empty lines
      if (getLineLength(line) == 0) return;

      try {
        int bracket = TextUtilities.findMatchingBracket(document, Math.max(0, dot - 1));
        if (bracket != -1) {
          int mark = getMarkPosition();
          // Hack
          if (bracket > mark) {
            bracket++;
            mark--;
          }
          select(mark, bracket);
          return;
        }
      } catch (BadLocationException bl) {
        bl.printStackTrace();
      }

      // Ok, it's not a bracket... select the word
      String lineText = getLineText(line);
      char ch = lineText.charAt(Math.max(0, offset - 1));

      String noWordSep = (String) document.getProperty("noWordSep");
      if (noWordSep == null) noWordSep = "";

      // If the user clicked on a non-letter char,
      // we select the surrounding non-letters
      boolean selectNoLetter = (!Character.isLetterOrDigit(ch) && noWordSep.indexOf(ch) == -1);

      int wordStart = 0;

      for (int i = offset - 1; i >= 0; i--) {
        ch = lineText.charAt(i);
        if (selectNoLetter ^ (!Character.isLetterOrDigit(ch) && noWordSep.indexOf(ch) == -1)) {
          wordStart = i + 1;
          break;
        }
      }

      int wordEnd = lineText.length();
      for (int i = offset; i < lineText.length(); i++) {
        ch = lineText.charAt(i);
        if (selectNoLetter ^ (!Character.isLetterOrDigit(ch) && noWordSep.indexOf(ch) == -1)) {
          wordEnd = i;
          break;
        }
      }

      int lineStart = getLineStartOffset(line);
      select(lineStart + wordStart, lineStart + wordEnd);

      /*
      String lineText = getLineText(line);
      String noWordSep = (String)document.getProperty("noWordSep");
      int wordStart = TextUtilities.findWordStart(lineText,offset,noWordSep);
      int wordEnd = TextUtilities.findWordEnd(lineText,offset,noWordSep);

      int lineStart = getLineStartOffset(line);
      select(lineStart + wordStart,lineStart + wordEnd);
      */
    }