Example #1
1
  // tokenizes a string for PBM and PGM headers and plain PBM and PGM data.  If oneChar is true,
  // then
  // rather than parsing a whole string, a single character is read (not including whitespace or
  // comments)
  static String tokenizeString(InputStream stream, boolean oneChar) throws IOException {
    final int EOF = -1;

    StringBuilder b = new StringBuilder();
    int c;
    boolean inComment = false;

    while (true) {
      c = stream.read();
      if (c == EOF)
        throw new IOException(
            "Stream ended prematurely, before table reading was completed."); // no more tokens
      else if (inComment) {
        if (c == '\r' || c == '\n') // escape the comment
        inComment = false;
        else {
        } // do nothing
      } else if (Character.isWhitespace((char) c)) {
      } // do nothing
      else if (c == '#') // start of a comment
      {
        inComment = true;
      } else // start of a string
      {
        b.append((char) c);
        break;
      }
    }

    if (oneChar) return b.toString();

    // at this point we have a valid string.  We read until whitespace or a #
    while (true) {
      c = stream.read();
      if (c == EOF) break;
      else if (c == '#') // start of comment, read until a '\n'
      {
        while (true) {
          c = stream.read(); // could hit EOF, which is fine
          if (c == EOF) break;
          else if (c == '\r' || c == '\n') break;
        }
        // break;   // comments are not delimiters
      } else if (Character.isWhitespace((char) c)) break;
      else b.append((char) c);
    }
    return b.toString();
  }
  /**
   * 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;
  }
  /**
   * Returns the end of the word at the given offset.
   *
   * @param textArea The text area.
   * @param offs The offset into the text area's content.
   * @return The end offset of the word.
   * @throws BadLocationException If <code>offs</code> is invalid.
   * @see #getWordStart(RSyntaxTextArea, int)
   */
  public static int getWordEnd(RSyntaxTextArea textArea, int offs) throws BadLocationException {

    Document doc = textArea.getDocument();
    int endOffs = textArea.getLineEndOffsetOfCurrentLine();
    int lineEnd = Math.min(endOffs, doc.getLength());
    if (offs == lineEnd) { // End of the line.
      return offs;
    }

    String s = doc.getText(offs, lineEnd - offs - 1);
    if (s != null && s.length() > 0) { // Should always be true
      int i = 0;
      int count = s.length();
      char ch = s.charAt(i);
      if (Character.isWhitespace(ch)) {
        while (i < count && Character.isWhitespace(s.charAt(i++))) ;
      } else if (Character.isLetterOrDigit(ch)) {
        while (i < count && Character.isLetterOrDigit(s.charAt(i++))) ;
      } else {
        i = 2;
      }
      offs += i - 1;
    }

    return offs;
  }
Example #4
0
 public void mouseMoved(MouseEvent e) {
   int k = html.viewToModel(e.getPoint());
   if (html.hasFocus() && html.getSelectionStart() <= k && k < html.getSelectionEnd()) {
     setMessage("(on selection)", MOVE);
     return;
   }
   String s = text.getText(); // "";
   int m = s.length(); // html.getDocument().getLength();
   /*try {
          s = html.getText(0, m);
      } catch (BadLocationException x) {
   setMessage("BadLocation "+m, TEXT); return;
      } */
   if (!Character.isLetter(s.charAt(k))) {
     setMessage("(not a letter)", TEXT);
     return;
   }
   selB = k;
   selE = k + 1;
   while (!Character.isWhitespace(s.charAt(selB - 1))) selB--;
   while (!Character.isWhitespace(s.charAt(selE))) selE++;
   setMessage(selB + "-" + selE, HAND);
   word = "";
   for (int i = selB; i < selE; i++) if (Character.isLetter(s.charAt(i))) word += s.charAt(i);
   html.setToolTipText(word);
 }
Example #5
0
  private boolean isToStopAt(char toCheck, char former) {
    if (isInStopAtArray(former) || isInStopAtArray(toCheck)) {
      return true;
    } else if (false == Character.isWhitespace(former) && Character.isWhitespace(toCheck)
        || Character.isWhitespace(former) && false == Character.isWhitespace(toCheck))
    //     else if(Character.isWhitespace(former) && false == Character.isWhitespace(toCheck))
    {
      return true;
    }

    return false;
  }
Example #6
0
 /** Set the text of an XML element, safely encode it if needed. */
 @NotNull
 public static Element setSafeXmlText(@NotNull Element element, @NotNull String text) {
   final Character first = firstCharacter(text);
   final Character last = lastCharacter(text);
   if (!StringHelper.isXmlCharacterData(text)
       || first != null && Character.isWhitespace(first)
       || last != null && Character.isWhitespace(last)) {
     element.setAttribute("encoding", "base64");
     final String encoded = new String(Base64.encodeBase64(text.getBytes()));
     element.setText(encoded);
   } else {
     element.setText(text);
   }
   return element;
 }
Example #7
0
  String cleanupSource(String source) {
    if (source.isEmpty()) {
      return source.concat("\n");
    }

    int lastChIdx = source.length() - 1;
    if (source.charAt(lastChIdx) != '\n') {
      // Append a newline at the end
      source = source.concat("\n");
    } else {
      // Remove all newlines at the end but one
      while (lastChIdx >= 1) {
        Character ch1 = source.charAt(lastChIdx);
        if (ch1 == '\n' || Character.isWhitespace(ch1)) {
          source = source.substring(0, lastChIdx--);
        } else {
          break;
        }
      }

      source = source.concat("\n");
    }

    return source;
  }
 private static boolean hasWhitespace(String string) {
   int length = string.length();
   for (int i = 0; i < length; i++) {
     if (Character.isWhitespace(string.charAt(i))) {
       return true;
     }
   }
   return false;
 }
Example #9
0
  public boolean searchAndReplace(
      @NotNull Editor editor, @NotNull LineRange range, @NotNull String excmd, String exarg) {
    boolean res = true;

    // Explicitly exit visual mode here, so that visual mode marks don't change when we move the
    // cursor to a match.
    if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) {
      VimPlugin.getMotion().exitVisual(editor);
    }

    CharPointer cmd = new CharPointer(new StringBuffer(exarg));
    // sub_nsubs = 0;
    // sub_nlines = 0;

    int which_pat;
    if (excmd.equals("~")) {
      which_pat = RE_LAST; /* use last used regexp */
    } else {
      which_pat = RE_SUBST; /* use last substitute regexp */
    }

    CharPointer pat;
    CharPointer sub;
    char delimiter;
    /* new pattern and substitution */
    if (excmd.charAt(0) == 's'
        && !cmd.isNul()
        && !Character.isWhitespace(cmd.charAt())
        && "0123456789cegriIp|\"".indexOf(cmd.charAt()) == -1) {
      /* don't accept alphanumeric for separator */
      if (CharacterClasses.isAlpha(cmd.charAt())) {
        VimPlugin.showMessage(MessageHelper.message(Msg.E146));
        return false;
      }
      /*
       * undocumented vi feature:
       *  "\/sub/" and "\?sub?" use last used search pattern (almost like
       *  //sub/r).  "\&sub&" use last substitute pattern (like //sub/).
       */
      if (cmd.charAt() == '\\') {
        cmd.inc();
        if ("/?&".indexOf(cmd.charAt()) == -1) {
          VimPlugin.showMessage(MessageHelper.message(Msg.e_backslash));
          return false;
        }
        if (cmd.charAt() != '&') {
          which_pat = RE_SEARCH; /* use last '/' pattern */
        }
        pat = new CharPointer(""); /* empty search pattern */
        delimiter = cmd.charAt(); /* remember delimiter character */
        cmd.inc();
      } else /* find the end of the regexp */ {
        which_pat = RE_LAST; /* use last used regexp */
        delimiter = cmd.charAt(); /* remember delimiter character */
        cmd.inc();
        pat = cmd.ref(0); /* remember start of search pat */
        cmd = RegExp.skip_regexp(cmd, delimiter, true);
        if (cmd.charAt() == delimiter) /* end delimiter found */ {
          cmd.set('\u0000').inc(); /* replace it with a NUL */
        }
      }

      /*
       * Small incompatibility: vi sees '\n' as end of the command, but in
       * Vim we want to use '\n' to find/substitute a NUL.
       */
      sub = cmd.ref(0); /* remember the start of the substitution */

      while (!cmd.isNul()) {
        if (cmd.charAt() == delimiter) /* end delimiter found */ {
          cmd.set('\u0000').inc(); /* replace it with a NUL */
          break;
        }
        if (cmd.charAt(0) == '\\' && cmd.charAt(1) != 0) /* skip escaped characters */ {
          cmd.inc();
        }
        cmd.inc();
      }
    } else /* use previous pattern and substitution */ {
      if (lastReplace == null) /* there is no previous command */ {
        VimPlugin.showMessage(MessageHelper.message(Msg.e_nopresub));
        return false;
      }
      pat = null; /* search_regcomp() will use previous pattern */
      sub = new CharPointer(lastReplace);
    }

    /*
     * Find trailing options.  When '&' is used, keep old options.
     */
    if (cmd.charAt() == '&') {
      cmd.inc();
    } else {
      do_all = Options.getInstance().isSet("gdefault");
      do_ask = false;
      do_error = true;
      // do_print = false;
      do_ic = 0;
    }
    while (!cmd.isNul()) {
      /*
       * Note that 'g' and 'c' are always inverted, also when p_ed is off.
       * 'r' is never inverted.
       */
      if (cmd.charAt() == 'g') {
        do_all = !do_all;
      } else if (cmd.charAt() == 'c') {
        do_ask = !do_ask;
      } else if (cmd.charAt() == 'e') {
        do_error = !do_error;
      } else if (cmd.charAt() == 'r') /* use last used regexp */ {
        which_pat = RE_LAST;
      } else if (cmd.charAt() == 'i') /* ignore case */ {
        do_ic = 'i';
      } else if (cmd.charAt() == 'I') /* don't ignore case */ {
        do_ic = 'I';
      } else if (cmd.charAt() != 'p') {
        break;
      }
      cmd.inc();
    }

    int line1 = range.getStartLine();
    int line2 = range.getEndLine();

    /*
     * check for a trailing count
     */
    cmd = CharHelper.skipwhite(cmd);
    if (CharacterClasses.isDigit(cmd.charAt())) {
      int i = CharHelper.getdigits(cmd);
      if (i <= 0 && do_error) {
        VimPlugin.showMessage(MessageHelper.message(Msg.e_zerocount));
        return false;
      }
      line1 = line2;
      line2 = EditorHelper.normalizeLine(editor, line1 + i - 1);
    }

    /*
     * check for trailing command or garbage
     */
    cmd = CharHelper.skipwhite(cmd);
    if (!cmd.isNul() && cmd.charAt() != '"') /* if not end-of-line or comment */ {
      VimPlugin.showMessage(MessageHelper.message(Msg.e_trailing));
      return false;
    }

    String pattern = "";
    if (pat == null || pat.isNul()) {
      switch (which_pat) {
        case RE_LAST:
          pattern = lastPattern;
          break;
        case RE_SEARCH:
          pattern = lastSearch;
          break;
        case RE_SUBST:
          pattern = lastSubstitute;
          break;
      }
    } else {
      pattern = pat.toString();
    }

    lastSubstitute = pattern;
    if (pattern != null) {
      setLastPattern(editor, pattern);
    }

    // int start = editor.logicalPositionToOffset(new LogicalPosition(line1, 0));
    // int end = editor.logicalPositionToOffset(new LogicalPosition(line2,
    // EditorHelper.getLineLength(editor, line2)));
    int start = editor.getDocument().getLineStartOffset(line1);
    int end = editor.getDocument().getLineEndOffset(line2);

    RegExp sp;
    RegExp.regmmatch_T regmatch = new RegExp.regmmatch_T();
    sp = new RegExp();
    regmatch.regprog = sp.vim_regcomp(pattern, 1);
    if (regmatch.regprog == null) {
      if (do_error) {
        VimPlugin.showMessage(MessageHelper.message(Msg.e_invcmd));
      }
      return false;
    }

    /* the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' */
    if (do_ic == 'i') {
      regmatch.rmm_ic = true;
    } else if (do_ic == 'I') {
      regmatch.rmm_ic = false;
    }

    /*
     * ~ in the substitute pattern is replaced with the old pattern.
     * We do it here once to avoid it to be replaced over and over again.
     * But don't do it when it starts with "\=", then it's an expression.
     */
    if (!(sub.charAt(0) == '\\' && sub.charAt(1) == '=') && lastReplace != null) {
      StringBuffer tmp = new StringBuffer(sub.toString());
      int pos = 0;
      while ((pos = tmp.indexOf("~", pos)) != -1) {
        if (pos == 0 || tmp.charAt(pos - 1) != '\\') {
          tmp.replace(pos, pos + 1, lastReplace);
          pos += lastReplace.length();
        }
        pos++;
      }
      sub = new CharPointer(tmp);
    }

    lastReplace = sub.toString();

    searchHighlight(false);

    if (logger.isDebugEnabled()) {
      logger.debug("search range=[" + start + "," + end + "]");
      logger.debug("pattern=" + pattern + ", replace=" + sub);
    }
    int lastMatch = -1;
    int lastLine = -1;
    int searchcol = 0;
    boolean firstMatch = true;
    boolean got_quit = false;
    int lcount = EditorHelper.getLineCount(editor);
    for (int lnum = line1; lnum <= line2 && !got_quit; ) {
      CharacterPosition newpos = null;
      int nmatch = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, searchcol);
      if (nmatch > 0) {
        if (firstMatch) {
          VimPlugin.getMark().saveJumpLocation(editor);
          firstMatch = false;
        }

        String match = sp.vim_regsub_multi(regmatch, lnum, sub, 1, false);
        // logger.debug("found match[" + spos + "," + epos + "] - replace " + match);

        int line = lnum + regmatch.startpos[0].lnum;
        CharacterPosition startpos =
            new CharacterPosition(lnum + regmatch.startpos[0].lnum, regmatch.startpos[0].col);
        CharacterPosition endpos =
            new CharacterPosition(lnum + regmatch.endpos[0].lnum, regmatch.endpos[0].col);
        int startoff = EditorHelper.characterPositionToOffset(editor, startpos);
        int endoff = EditorHelper.characterPositionToOffset(editor, endpos);
        int newend = startoff + match.length();

        if (do_all || line != lastLine) {
          boolean doReplace = true;
          if (do_ask) {
            // editor.getSelectionModel().setSelection(startoff, endoff);
            RangeHighlighter hl = highlightConfirm(editor, startoff, endoff);
            int choice = getConfirmChoice(match);
            // editor.getSelectionModel().removeSelection();
            editor.getMarkupModel().removeHighlighter(hl);
            switch (choice) {
              case 0: // Yes
                doReplace = true;
                break;
              case 1: // No
                doReplace = false;
                break;
              case 2: // All
                do_ask = false;
                break;
              case JOptionPane.CLOSED_OPTION:
              case 3: // Quit
                doReplace = false;
                got_quit = true;
                break;
              case 4: // Last
                do_all = false;
                line2 = lnum;
                doReplace = true;
                break;
            }
          }

          if (doReplace) {
            editor.getDocument().replaceString(startoff, endoff, match);
            lastMatch = startoff;
            newpos = EditorHelper.offsetToCharacterPosition(editor, newend);

            lnum += newpos.line - endpos.line;
            line2 += newpos.line - endpos.line;
          }
        }

        lastLine = line;

        lnum += nmatch - 1;
        if (do_all && startoff != endoff) {
          if (newpos != null) {
            lnum = newpos.line;
            searchcol = newpos.column;
          } else {
            searchcol = endpos.column;
          }
        } else {
          searchcol = 0;
          lnum++;
        }
      } else {
        lnum++;
        searchcol = 0;
      }
    }

    if (lastMatch != -1) {
      MotionGroup.moveCaret(
          editor,
          VimPlugin.getMotion()
              .moveCaretToLineStartSkipLeading(
                  editor, editor.offsetToLogicalPosition(lastMatch).line));
    } else {
      VimPlugin.showMessage(MessageHelper.message(Msg.e_patnotf2, pattern));
    }

    return res;
  }
  public void keyTyped(KeyEvent e) {
    if (debug) {
      System.out.println(
          "--- RecordingModule: key typed = "
              + e
              + "\n  > Key char->int = "
              + (int) e.getKeyChar());
      System.out.println(" -- isActionKey() = " + e.isActionKey());
      System.out.println(" -- isISOControl() = " + Character.isISOControl(e.getKeyChar()));
      System.out.println(" -- isWhitespace() = " + Character.isWhitespace(e.getKeyChar()));
    }

    if (isKeyReserved(e)) {
      return;
    }

    if (enabled && !readOnly && lastKeyPressEvent != null) {

      if (enableKeyboard) {
        boolean replace = false;
        String text = "";
        if (isControl(e)) {
          if (lastKeyPressEvent.getKeyCode() == KeyEvent.VK_ENTER) {

            // Change the Type cmd prior to Typeline if the delay from the last type key is less
            // than 1 sec
            if (useTypeline && e.getModifiers() == 0 && lastElement != null) {
              String s = DocumentUtils.getElementText(lastElement);
              if (s.startsWith("Type ")
                  && (System.currentTimeMillis() - lastInsertTime) < typelineDelay) {
                replace = true;
                text = s.replaceFirst("Type", "Typeline");
              }
            }
          }

          if ("".equals(text)) {
            int count = 1;
            KeyEvent e2;

            long lastEventTime = e.getWhen();

            // We go through the vector of events and check whether there are events corresponding
            // to a typed text.
            for (int i = 0; i < events.size() && events.get(i) instanceof KeyEvent; i++) {
              e2 = (KeyEvent) events.get(i);
              if (e.getID() == e2.getID()
                  && e.getKeyChar() == e2.getKeyChar()
                  && e.getKeyCode() == e2.getKeyCode()
                  && e.getModifiers() == e2.getModifiers()
                  && (lastEventTime - e2.getWhen() < keyMutiDelay)) {
                count++;
                replace = true;
                lastEventTime = e2.getWhen();
              } else {
                break;
              }
            }

            text = "Press ";
            //                    String modifiers = KeyEvent.getKeyModifiersText(e.getModifiers());
            String modifiers = parser.modifiersToString(e.getModifiers());
            if (!"".equals(modifiers)) {
              text += modifiers + "+";
            }
            String charText = KeyEvent.getKeyText(lastKeyPressEvent.getKeyCode());
            if (charText == null) {
              charText = "<unknown>";
            }
            text += charText;
            if (count > 1) {
              text += " " + PressCommand.PARAM_COUNT + "=" + count;
            }

            if (debug) {
              System.out.println("--- RecordingModule: Inserting '" + text + "'");
            }
          }

        } else {
          text = "" + e.getKeyChar();
          KeyEvent e2;

          // We go through the vector of events and check whether there are events corresponding to
          // a typed text.
          for (int i = 0; i < events.size() && events.get(i) instanceof KeyEvent; i++) {
            e2 = (KeyEvent) events.get(i);
            if (!isControl(e2) && !e2.isActionKey()) {
              text = e2.getKeyChar() + text;
              replace = true;
            } else {
              break;
            }
          }

          text = "Type \"" + Utils.escapeUnescapedDoubleQuotes(text) + "\"";
        }

        // Insert the command to the current editor
        insertLine(text, replace, true, false);
      }
      insertEvent(e);
    }
  }