/**
   * Finds the next instance of the string/regular expression specified from the caret position. If
   * a match is found, it is selected in this text area.
   *
   * @param textArea The text area in which to search.
   * @param context What to search for and all search options.
   * @return Whether a match was found (and thus selected).
   * @throws PatternSyntaxException If this is a regular expression search but the search text is an
   *     invalid regular expression.
   * @see #replace(RTextArea, SearchContext)
   * @see #replaceAll(RTextArea, SearchContext)
   */
  public static boolean find(JTextArea textArea, SearchContext context) {

    String text = context.getSearchFor();
    if (text == null || text.length() == 0) {
      return false;
    }

    // Be smart about what position we're "starting" at.  We don't want
    // to find a match in the currently selected text (if any), so we
    // start searching AFTER the selection if searching forward, and
    // BEFORE the selection if searching backward.
    Caret c = textArea.getCaret();
    boolean forward = context.getSearchForward();
    int start = forward ? Math.max(c.getDot(), c.getMark()) : Math.min(c.getDot(), c.getMark());

    String findIn = getFindInText(textArea, start, forward);
    if (findIn == null || findIn.length() == 0) return false;

    // Find the next location of the text we're searching for.
    if (!context.isRegularExpression()) {
      int pos =
          getNextMatchPos(text, findIn, forward, context.getMatchCase(), context.getWholeWord());
      findIn = null; // May help garbage collecting.
      if (pos != -1) {
        // Without this, if JTextArea isn't in focus, selection
        // won't appear selected.
        c.setSelectionVisible(true);
        pos = forward ? start + pos : pos;
        selectAndPossiblyCenter(textArea, pos, pos + text.length());
        return true;
      }
    } else {
      // Regex matches can have varying widths.  The returned point's
      // x- and y-values represent the start and end indices of the
      // match in findIn.
      Point regExPos =
          getNextMatchPosRegEx(
              text, findIn, forward, context.getMatchCase(), context.getWholeWord());
      findIn = null; // May help garbage collecting.
      if (regExPos != null) {
        // Without this, if JTextArea isn't in focus, selection
        // won't appear selected.
        c.setSelectionVisible(true);
        if (forward) {
          regExPos.translate(start, start);
        }
        selectAndPossiblyCenter(textArea, regExPos.x, regExPos.y);
        return true;
      }
    }

    // No match.
    return false;
  }
Exemplo n.º 2
0
 /**
  * Replaces the currently selected content with new content represented by the given StyledText.
  * If there is no selection this amounts to an insert of the given text. If there is no
  * replacement text this amounts to a removal of the current selection. The replacement text will
  * have the attributes currently defined for input at the point of insertion. If the document is
  * not editable, beep and return
  *
  * @param content the content to replace the selection with
  * @see StyledText#insert
  */
 public static void replaceSelection(Word word, StyledText content) {
   Document doc = word.workspace.getDocument();
   String text;
   Caret caret = word.workspace.getCaret();
   int insertPos = 0;
   int i;
   int contentSize;
   if (doc != null) {
     try {
       int p0 = Math.min(caret.getDot(), caret.getMark());
       int p1 = Math.max(caret.getDot(), caret.getMark());
       // if there is any selection
       if (p0 != p1) {
         doc.remove(p0, p1 - p0);
       }
       // insert the content
       if (content != null) {
         content.insert(doc, p0);
       }
     } catch (BadLocationException ble) {
       javax.swing.UIManager.getLookAndFeel().provideErrorFeedback(word.workspace);
       return;
     }
   }
 }
Exemplo n.º 3
0
  @Override
  public void internalFrameActivated(InternalFrameEvent e) {
    super.internalFrameActivated(e);

    mainFrame.pasteItem.setEnabled(canPaste());

    Caret caret = sourceArea.getCaret();
    doCaretUpdate(caret.getDot(), caret.getMark());

    setUndoItem();
    setRedoItem();
  }
Exemplo n.º 4
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.º 5
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.º 6
0
 public int getCaretPosition() {
   Caret c = textView.getCaret();
   return c.getDot();
 }
Exemplo n.º 7
0
  // latestAnnotationTask business logic
  @Override
  public void run() {
    // get resource bundle
    ResourceBundle loc = NbBundle.getBundle(AnnotationBar.class);
    // give status bar "wait" indication // NOI18N
    StatusBar statusBar = editorUI.getStatusBar();
    recentStatusMessage = loc.getString("CTL_StatusBar_WaitFetchAnnotation"); // NOI18N
    statusBar.setText(StatusBar.CELL_MAIN, recentStatusMessage);

    // determine current line
    int line = -1;
    int offset = caret.getDot();
    try {
      line = Utilities.getLineOffset(doc, offset);
    } catch (BadLocationException ex) {
      Mercurial.LOG.log(Level.SEVERE, "Can not get line for caret at offset ", offset); // NOI18N
      clearRecentFeedback();
      return;
    }

    // handle locally modified lines
    AnnotateLine al = getAnnotateLine(line);
    if (al == null) {
      AnnotationMarkProvider amp = AnnotationMarkInstaller.getMarkProvider(textComponent);
      if (amp != null) {
        amp.setMarks(Collections.<AnnotationMark>emptyList());
      }
      clearRecentFeedback();
      if (recentRevision != null) {
        recentRevision = null;
        repaint();
      }
      return;
    }

    // handle unchanged lines
    String revision = al.getRevision();
    if (revision.equals(recentRevision) == false) {
      recentRevision = revision;
      repositoryRoot = Mercurial.getInstance().getRepositoryRoot(getCurrentFile());
      repaint();

      AnnotationMarkProvider amp = AnnotationMarkInstaller.getMarkProvider(textComponent);
      if (amp != null) {

        List<AnnotationMark> marks = new ArrayList<AnnotationMark>(elementAnnotations.size());
        // I cannot affort to lock elementAnnotations for long time
        // it's accessed from editor thread too
        Iterator<Map.Entry<Element, AnnotateLine>> it2;
        synchronized (elementAnnotations) {
          it2 =
              new HashSet<Map.Entry<Element, AnnotateLine>>(elementAnnotations.entrySet())
                  .iterator();
        }
        while (it2.hasNext()) {
          Map.Entry<Element, AnnotateLine> next = it2.next();
          AnnotateLine annotateLine = next.getValue();
          if (revision.equals(annotateLine.getRevision())) {
            Element element = next.getKey();
            if (elementAnnotations.containsKey(element) == false) {
              continue;
            }
            int elementOffset = element.getStartOffset();
            int lineNumber = NbDocument.findLineNumber((StyledDocument) doc, elementOffset);
            AnnotationMark mark = new AnnotationMark(lineNumber, revision);
            marks.add(mark);
          }

          if (Thread.interrupted()) {
            clearRecentFeedback();
            return;
          }
        }
        amp.setMarks(marks);
      }
    }

    if (al.getCommitMessage() != null) {
      recentStatusMessage = al.getCommitMessage();
      statusBar.setText(
          StatusBar.CELL_MAIN,
          al.getRevision()
              + ":"
              + al.getId()
              + " - "
              + al.getAuthor()
              + ": "
              + recentStatusMessage); // NOI18N
    } else {
      clearRecentFeedback();
    }
  }
Exemplo n.º 8
0
    @Override
    public void actionPerformed(ActionEvent e) {
      JTextComponent textArea = (JTextComponent) e.getSource();

      Caret caret = textArea.getCaret();
      int dot = caret.getDot();

      /*
       * Move to the beginning/end of selection on a "non-shifted"
       * left- or right-keypress.  We shouldn't have to worry about
       * navigation filters as, if one is being used, it let us get
       * to that position before.
       */
      if (!select) {
        switch (direction) {
          case SwingConstants.EAST:
            int mark = caret.getMark();
            if (dot != mark) {
              caret.setDot(Math.max(dot, mark));
              return;
            }
            break;
          case SwingConstants.WEST:
            mark = caret.getMark();
            if (dot != mark) {
              caret.setDot(Math.min(dot, mark));
              return;
            }
            break;
          default:
        }
      }

      Position.Bias[] bias = new Position.Bias[1];
      Point magicPosition = caret.getMagicCaretPosition();

      try {

        if (magicPosition == null
            && (direction == SwingConstants.NORTH || direction == SwingConstants.SOUTH)) {
          Rectangle r = textArea.modelToView(dot);
          magicPosition = new Point(r.x, r.y);
        }

        NavigationFilter filter = textArea.getNavigationFilter();

        if (filter != null) {
          dot =
              filter.getNextVisualPositionFrom(
                  textArea, dot, Position.Bias.Forward, direction, bias);
        } else {
          if (direction == SwingConstants.NORTH || direction == SwingConstants.SOUTH) {
            dot = getNSVisualPosition((EditorPane) textArea, dot, direction);
          } else {
            dot =
                textArea
                    .getUI()
                    .getNextVisualPositionFrom(
                        textArea, dot, Position.Bias.Forward, direction, bias);
          }
        }
        if (select) {
          caret.moveDot(dot);
        } else {
          caret.setDot(dot);
        }

        if (magicPosition != null
            && (direction == SwingConstants.NORTH || direction == SwingConstants.SOUTH)) {
          caret.setMagicCaretPosition(magicPosition);
        }

      } catch (BadLocationException ble) {
        Debug.error(me + "Problem while trying to move caret\n%s", ble.getMessage());
      }
    }
 /**
  * Makes the caret's dot and mark the same location so that, for the next search in the specified
  * direction, a match will be found even if it was within the original dot and mark's selection.
  *
  * @param textArea The text area.
  * @param forward Whether the search will be forward through the document (<code>false</code>
  *     means backward).
  * @return The new dot and mark position.
  */
 private static int makeMarkAndDotEqual(JTextArea textArea, boolean forward) {
   Caret c = textArea.getCaret();
   int val = forward ? Math.min(c.getDot(), c.getMark()) : Math.max(c.getDot(), c.getMark());
   c.setDot(val);
   return val;
 }
Exemplo n.º 10
0
 @Override
 public void actionPerformed(ActionEvent e, JTextComponent target) {
   Caret caret = target.getCaret();
   int prev = getPreviousWordPosition(target.getDocument(), caret.getDot());
   caret.setDot(prev);
 }