예제 #1
1
  private String trim(final StringBuffer buffer, final TextPresentation presentation) {

    int length = buffer.length();

    int end = length - 1;
    while (end >= 0 && Character.isWhitespace(buffer.charAt(end))) {
      --end;
    }

    if (end == -1) {
      return ""; //$NON-NLS-1$
    }

    if (end < length - 1) {
      buffer.delete(end + 1, length);
    } else {
      end = length;
    }

    int start = 0;
    while (start < end && Character.isWhitespace(buffer.charAt(start))) {
      ++start;
    }

    buffer.delete(0, start);
    presentation.setResultWindow(new Region(start, buffer.length()));
    return buffer.toString();
  }
  /**
   * Returns the next character.
   *
   * @return the next character
   * @throws IOException in case reading the character fails
   */
  protected int nextChar() throws IOException {
    fReadFromBuffer = (fBuffer.length() > 0);
    if (fReadFromBuffer) {
      char ch = fBuffer.charAt(fIndex++);
      if (fIndex >= fBuffer.length()) {
        fBuffer.setLength(0);
        fIndex = 0;
      }
      return ch;
    }

    int ch = fCharAfterWhiteSpace;
    if (ch == -1) {
      ch = fReader.read();
    }
    if (fSkipWhiteSpace && Character.isWhitespace((char) ch)) {
      do {
        ch = fReader.read();
      } while (Character.isWhitespace((char) ch));
      if (ch != -1) {
        fCharAfterWhiteSpace = ch;
        return ' ';
      }
    } else {
      fCharAfterWhiteSpace = -1;
    }
    return ch;
  }
예제 #3
0
파일: cnp.java 프로젝트: ChiangC/FMTech
 public final void run() {
   if ((this.a.F) || (!this.a.i())) {
     return;
   }
   Spanned localSpanned = Html.fromHtml(this.a.az);
   if ((localSpanned instanceof SpannableStringBuilder)) {}
   int i;
   int j;
   for (SpannableStringBuilder localSpannableStringBuilder = (SpannableStringBuilder) localSpanned;
       ;
       localSpannableStringBuilder = new SpannableStringBuilder(localSpanned)) {
     i = localSpannableStringBuilder.length();
     for (j = 0;
         (j != i) && (Character.isWhitespace(localSpannableStringBuilder.charAt(j)));
         j++) {}
   }
   if (j != 0) {
     localSpannableStringBuilder.delete(0, j);
     i = localSpannableStringBuilder.length();
   }
   for (int k = i - 1;
       (k >= 0) && (Character.isWhitespace(localSpannableStringBuilder.charAt(k)));
       k--) {}
   if (k != i - 1) {
     localSpannableStringBuilder.delete(k + 1, i);
   }
   this.a.ax.setText(localSpannableStringBuilder);
   Linkify.addLinks(this.a.ax, 1);
   this.a.ax.setVisibility(0);
   this.a.ax.setMovementMethod(LinkMovementMethod.getInstance());
   this.a.ay.setVisibility(0);
 }
예제 #4
0
  /**
   * Trims a string with {@link String#trim()} and by removing any double whitespace
   *
   * @param string the string
   * @return the trimmed string
   */
  public String trim(String string) {
    string = string.trim(); // First trim using String#trim()
    boolean quotes = false;
    String builder = "";

    for (char c : string.toCharArray()) {
      if (c == '"') {
        if (!builder.endsWith("\\") || builder.endsWith("\\\\")) {
          quotes = !quotes;
        }
      }

      if (quotes
          || !Character.isWhitespace(c)
          || !builder.isEmpty()
              && !Character.isWhitespace(
                  builder.charAt(
                      builder.length()
                          - 1))) { // trim() should get rid of leading whitespace, but just in case
        builder += c;
      }
    }

    return builder;
  }
예제 #5
0
  private boolean checkHandlerWorkaround(
      String elementName, String handlerName, boolean writeHandler)
      throws ClickException, IOException {
    // If talking to an old ControlSocket, try the "handlers" handler
    // instead.
    String s = readString(elementName, "handlers");
    int pos = 0;

    // Find handler with same name.
    while (true) {
      pos = s.indexOf(handlerName, pos);
      if (pos < 0) // no such handler
      return false;
      if ((pos == 0 || s.charAt(pos - 1) == '\n')
          && Character.isWhitespace(s.charAt(pos + handlerName.length()))) break;
      pos++;
    }

    // we have a matching handler: will it be read/write suitable?
    char wantType = (writeHandler ? 'w' : 'r');
    for (pos += handlerName.length();
        pos < s.length() && Character.isWhitespace(s.charAt(pos));
        pos++) /* nada */ ;
    for (; pos < s.length(); pos++) {
      char c = s.charAt(pos);
      if (Character.toLowerCase(c) == wantType) return true;
      else if (Character.isWhitespace(c)) break;
    }
    return false;
  }
예제 #6
0
  /**
   * Gets the information about an element's handlers in the current router configuration.
   *
   * @param el The element name.
   * @return Vector of HandlerInfo structures.
   * @exception NoSuchElementException If there is no such element in the current configuration.
   * @exception HandlerErrorException If the handler returned an error.
   * @exception PermissionDeniedException If the router would not let us access the handler.
   * @exception IOException If there was some other error accessing the handler (e.g., there was a
   *     stream or socket error, the ControlSocket returned an unknwon unknown error code, or the
   *     response could otherwise not be understood).
   * @see #HandlerInfo
   * @see #getConfigElementNames
   * @see #getRouterConfig
   * @see #getRouterFlatConfig
   */
  public Vector getElementHandlers(String elementName) throws ClickException, IOException {
    Vector v = new Vector();
    Vector vh;

    try {
      char[] buf = read(elementName, "handlers");
      vh = StringUtils.split(buf, 0, '\n');
    } catch (ClickException.NoSuchHandlerException e) {
      return v;
    }

    for (int i = 0; i < vh.size(); i++) {
      String s = (String) vh.elementAt(i);
      int j;
      for (j = 0; j < s.length() && !Character.isWhitespace(s.charAt(j)); j++)
        ; // find record split
      if (j == s.length())
        throw new ClickException.HandlerFormatException(elementName + ".handlers");
      HandlerInfo hi = new HandlerInfo(elementName, s.substring(0, j).trim());
      while (j < s.length() && Character.isWhitespace(s.charAt(j))) j++;
      for (; j < s.length(); j++) {
        char c = s.charAt(j);
        if (Character.toLowerCase(c) == 'r') hi.canRead = true;
        else if (Character.toLowerCase(c) == 'w') hi.canWrite = true;
        else if (Character.isWhitespace(c)) break;
      }
      v.addElement(hi);
    }
    return v;
  }
 private int convertCharIfBraceLevelIsZero(char[] c, int i, StringBuffer sb, FORMAT_MODE format) {
   switch (format) {
     case TITLE_LOWERS:
       if (i == 0) {
         sb.append(c[i]);
       } else if (prevColon && Character.isWhitespace(c[i - 1])) {
         sb.append(c[i]);
       } else {
         sb.append(Character.toLowerCase(c[i]));
       }
       if (c[i] == ':') {
         prevColon = true;
       } else if (!Character.isWhitespace(c[i])) {
         prevColon = false;
       }
       break;
     case ALL_LOWERS:
       sb.append(Character.toLowerCase(c[i]));
       break;
     case ALL_UPPERS:
       sb.append(Character.toUpperCase(c[i]));
       break;
     default:
       LOGGER.info("convertCharIfBraceLevelIsZero - Unknown format: " + format);
       break;
   }
   i++;
   return i;
 }
예제 #8
0
 /**
  * Check to see if the ending tag is present.
  *
  * @param name The type of end tag being saught.
  * @return True if the ending tag was found.
  * @throws IOException Thrown if an IO error occurs.
  */
 private boolean peekEndTag(String name) throws IOException {
   int i = 0;
   // pass any whitespace
   while ((this.source.peek(i) != -1) && Character.isWhitespace(this.source.peek(i))) {
     i++;
   }
   // is a tag beginning
   if (this.source.peek(i) != '<') {
     return false;
   } else {
     i++;
   }
   // pass any whitespace
   while ((this.source.peek(i) != -1) && Character.isWhitespace(this.source.peek(i))) {
     i++;
   }
   // is it an end tag
   if (this.source.peek(i) != '/') {
     return false;
   } else {
     i++;
   }
   // pass any whitespace
   while ((this.source.peek(i) != -1) && Character.isWhitespace(this.source.peek(i))) {
     i++;
   }
   // does the name match
   for (int j = 0; j < name.length(); j++) {
     if (Character.toLowerCase(this.source.peek(i)) != Character.toLowerCase(name.charAt(j))) {
       return false;
     }
     i++;
   }
   return true;
 }
예제 #9
0
  public static void writeEncodeLinks(XMLWriter xmlw, String line) {
    int linkpos = line.indexOf("://");
    if (linkpos == -1) {
      xmlw.write(line);
      return;
    }
    int backpos = linkpos - 1;
    for (; backpos >= 0; --backpos) {
      if (Character.isWhitespace(line.charAt(backpos))) break;
    }
    ++backpos;
    if (backpos == linkpos - 1) { // require non-empty protocol
      xmlw.write(line);
      return;
    }

    int frontpos = linkpos + 3;
    for (; frontpos < line.length(); ++frontpos) {
      if (Character.isWhitespace(line.charAt(backpos))) break;
    }
    String url = line.substring(backpos, frontpos);
    xmlw.write(line.substring(0, backpos));
    xmlw.writeRaw("<a target=\"_top\" href=\"");
    xmlw.write(url);
    xmlw.writeRaw("\">");
    xmlw.write(url);
    xmlw.writeRaw("</a>");
    xmlw.write(line.substring(frontpos));
  }
예제 #10
0
  /*
   * @see JavaElementHover
   */
  protected String getHoverInfo(String nature, IModelElement[] result) {
    int nResults = result.length;

    if (nResults > 1) return null;

    IModelElement curr = result[0];
    if ((curr instanceof IMember) && curr instanceof ISourceReference) {
      try {
        String source = ((ISourceReference) curr).getSource();
        if (source == null) return null;

        // source = removeLeadingComments(source);
        String delim = System.getProperty("line.separator", "\n"); // $NON-NLS-1$ //$NON-NLS-2$

        String[] sourceLines = Strings.convertIntoLines(source);
        String firstLine = sourceLines[0];
        if (!Character.isWhitespace(firstLine.charAt(0))) sourceLines[0] = ""; // $NON-NLS-1$

        if (!Character.isWhitespace(firstLine.charAt(0))) sourceLines[0] = firstLine;

        source = Strings.concatenate(sourceLines, delim);

        return source;

      } catch (ModelException ex) {
      }
    }

    return null;
  }
예제 #11
0
  /**
   * Convert a string to title case, where an initial alpha character, and any alpha character
   * following whitespace, is upper case. As the title of a book.
   */
  public static final String toTitleCase(String s) {
    if (null == s) return null;
    else {
      char[] cary = s.toCharArray();

      int len = cary.length;

      if (0 < len) {

        cary[0] = Character.toUpperCase(cary[0]);

        boolean next = false;

        for (int cc = 1; cc < len; cc++) {

          if (next) {
            if (!Character.isWhitespace(cary[cc])) {

              cary[cc] = Character.toUpperCase(cary[cc]);

              next = false;
            }
          } else if (Character.isWhitespace(cary[cc])) next = true;
          else continue;
        }
        return new String(cary);
      } else return s;
    }
  }
  private static boolean isWhitespace(String text) {
    if (text == null) return true;

    boolean isWhitespace = true;

    for (int i = text.length() - 1; i >= 0; i--) {
      char ch = text.charAt(i);

      if (!Character.isWhitespace(ch)) {
        // check for comment
        if (ch == '>' && text.indexOf("-->") + 2 == i) {
          int head = text.indexOf("<!--");

          if (head >= 0) {
            for (int j = 0; j < head; j++) {
              if (!Character.isWhitespace(text.charAt(j))) {
                return false;
              }
            }

            return true;
          }
        }

        return false;
      }
    }

    return true;
  }
예제 #13
0
파일: System.java 프로젝트: prasaadk/renjin
  @VisibleForTesting
  static List<String> parseArgs(String commandLine) {
    List<String> terms = Lists.newArrayList();
    boolean dquoted = false;
    boolean squoted = false;
    char lastChar = 0;
    StringBuilder currentTerm = new StringBuilder();
    for (int i = 0; i != commandLine.length(); ++i) {
      char c = commandLine.charAt(i);
      if (!dquoted && !squoted && Character.isWhitespace(c)) {
        if (!Character.isWhitespace(lastChar)) {
          terms.add(currentTerm.toString());
          currentTerm.setLength(0);
        }
      } else if (!squoted && c == '"') {
        dquoted = !dquoted;

      } else if (!dquoted && c == '\'') {
        squoted = !squoted;

      } else {
        currentTerm.append(c);
      }
      lastChar = c;
    }
    if (currentTerm.length() > 0) {
      terms.add(currentTerm.toString());
    }
    return terms;
  }
예제 #14
0
  static String parseString(String stringCourse) {
    final int NUM_LETTERS_IN_COURSE_NAME = 3;
    final int NUM_NUMBERS_IN_COURSE_NAME = 4;

    char[] charCourse = stringCourse.toCharArray();
    char[] charParsed = new char[7];

    int courseIndex = 0, parsedIndex = 0;

    // Check to see if the next character is white space, if so then skip it
    while (Character.isWhitespace(charCourse[courseIndex])) {
      courseIndex++;
    }

    // Copy the first 3 letters of the course name
    for (int i = 0; i < NUM_LETTERS_IN_COURSE_NAME; i++)
      charParsed[parsedIndex++] = Character.toUpperCase(charCourse[courseIndex++]);

    // Check to see if the next character is white space, if so then skip it
    while (Character.isWhitespace(charCourse[courseIndex])) {
      courseIndex++;
    }

    // We dont care about the letter(s) after the next four numbers, so we only need the
    // For loop, then return
    for (int i = 0; i < NUM_NUMBERS_IN_COURSE_NAME; i++)
      charParsed[parsedIndex++] = charCourse[courseIndex++];

    return new String(charParsed);
  }
예제 #15
0
  /**
   * @return the current token and its initial offset for this token
   * @param the chars to be considered separators (note that whitespace chars are always considered
   *     separators and don't need to be in this set).
   * @throws BadLocationException
   */
  public Tuple<String, Integer> getCurrToken(Set<Character> separatorChars)
      throws BadLocationException {
    int offset = getAbsoluteCursorOffset();
    int i = offset;

    if (i > doc.getLength()) {
      return new Tuple<String, Integer>("", doc.getLength()); // $NON-NLS-1$
    }

    while (i > 0) {
      char ch = doc.getChar(i - 1);
      if (separatorChars.contains(ch) || Character.isWhitespace(ch)) {
        break;
      }
      i--;
    }

    Tuple<String, Integer> tup = new Tuple<String, Integer>(doc.get(i, offset - i), offset);

    String prefix = tup.o1;

    // ok, now, get the rest of the token, as we already have its prefix
    int start = tup.o2 - prefix.length();
    int end = start;
    while (doc.getLength() - 1 >= end) {
      char ch = doc.getChar(end);
      if (separatorChars.contains(ch) || Character.isWhitespace(ch)) {
        break;
      }
      end++;
    }
    String post = doc.get(tup.o2, end - tup.o2);
    return new Tuple<String, Integer>(prefix + post, start);
  }
예제 #16
0
  /**
   * Inserts a given string into another padding it with spaces. Is aware if the insertion point has
   * a space on either end and does not add extra spaces. If the string-to-insert is already present
   * (and not part of another word) we return the original string unchanged.
   *
   * @param s the string to insert into
   * @param insertAt the position to insert the string
   * @param stringToInsert the string to insert
   * @return the result of inserting the stringToInsert into the passed in string
   * @throws IndexOutOfBoundsException if the insertAt is negative, or insertAt is larger than the
   *     length of s String object
   */
  public static String insertPaddedIfNeeded(String s, int insertAt, String stringToInsert) {
    if (Strings.isEmptyOrNull(stringToInsert)) {
      return s;
    }

    boolean found = false;
    int startPos = 0;

    while ((startPos < s.length()) && (!found)) {
      int pos = s.indexOf(stringToInsert, startPos);

      if (pos < 0) break;

      startPos = pos + 1;
      int before = pos - 1;
      int after = pos + stringToInsert.length();

      if (((pos == 0) || (Character.isWhitespace(s.charAt(before))))
          && ((after >= s.length()) || (Character.isWhitespace(s.charAt(after))))) found = true;
    }

    if (found) {
      StringBuilder newText = new StringBuilder(s);

      if (newText.lastIndexOf(SINGLE_SPACE) != newText.length() - 1) {
        newText.append(SINGLE_SPACE);
      }

      return (newText.toString());
    } else return (Strings.insertPadded(s, insertAt, stringToInsert));
  }
예제 #17
0
  /**
   * Segments the paragraph to sentences according to currently setup rules.
   *
   * <p>Bugfix for <a href="http://sourceforge.net/support/tracker.php?aid=1288742">issue
   * 1288742</a>: Sentences are returned without spaces in the beginning and at the end of a
   * sentence.
   *
   * <p>An additional list with space information is returned to be able to glue translation
   * together with the same spaces between them as in original paragraph.
   *
   * @param paragraph the paragraph text
   * @param spaces list to store information about spaces between sentences
   * @param brules list to store rules that account to breaks
   * @return list of sentences (String objects)
   */
  public static List<String> segment(
      Language lang, String paragraph, List<StringBuffer> spaces, List<Rule> brules) {
    List<String> segments = breakParagraph(lang, paragraph, brules);
    List<String> sentences = new ArrayList<String>(segments.size());
    if (spaces == null) spaces = new ArrayList<StringBuffer>();
    spaces.clear();
    for (String one : segments) {
      int len = one.length();
      int b = 0;
      StringBuffer bs = new StringBuffer();
      while (b < len && Character.isWhitespace(one.charAt(b))) {
        bs.append(one.charAt(b));
        b++;
      }

      int e = len - 1;
      StringBuffer es = new StringBuffer();
      while (e >= b && Character.isWhitespace(one.charAt(e))) {
        es.append(one.charAt(e));
        e--;
      }
      es.reverse();

      String trimmed = one.substring(b, e + 1);
      sentences.add(trimmed);
      if (spaces != null) {
        spaces.add(bs);
        spaces.add(es);
      }
    }
    return sentences;
  }
 private List getSubpaths(String paramString) {
   int i = 0;
   int j = paramString.length();
   ArrayList localArrayList = new ArrayList();
   while (i < j) {
     while ((i < j) && (Character.isWhitespace(paramString.charAt(i)))) i++;
     if (i >= j) continue;
     int k = i;
     int m = k;
     String str = null;
     while (i < j) {
       char c = paramString.charAt(i);
       if ((c == '\\') && (i + 1 < j) && (paramString.charAt(i + 1) == ' ')) {
         if (str == null) str = paramString.substring(m, i);
         else str = str + paramString.substring(m, i);
         i++;
         m = i;
       } else {
         if (Character.isWhitespace(c)) break;
       }
       i++;
     }
     if (m != i)
       if (str == null) str = paramString.substring(m, i);
       else str = str + paramString.substring(m, i);
     localArrayList.add(str);
   }
   return localArrayList;
 }
예제 #19
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);
 }
  private static void autoImport(final PsiFile file, int offset, final Editor editor) {
    final CharSequence text = editor.getDocument().getCharsSequence();
    while (offset > 0 && Character.isJavaIdentifierPart(text.charAt(offset))) offset--;
    if (offset <= 0) return;

    while (offset > 0 && Character.isWhitespace(text.charAt(offset))) offset--;
    if (offset <= 0 || text.charAt(offset) != '.') return;

    offset--;

    while (offset > 0 && Character.isWhitespace(text.charAt(offset))) offset--;
    if (offset <= 0) return;

    PsiJavaCodeReferenceElement element =
        extractReference(
            PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiExpression.class, false));
    if (element == null) return;

    while (true) {
      final PsiJavaCodeReferenceElement qualifier = extractReference(element.getQualifier());
      if (qualifier == null) break;

      element = qualifier;
    }
    if (!(element.getParent() instanceof PsiMethodCallExpression)
        && element.multiResolve(true).length == 0) {
      new ImportClassFix(element).doFix(editor, false, false);
    }
  }
예제 #21
0
  private static int[] parse1dArray(Reader in) throws IOException {
    int c;
    while (Character.isWhitespace(c = in.read())) {}
    if (c != '[') {
      throw new IOException();
    }
    int[] array = new int[4];
    int size = 0;

    StringBuilder item = new StringBuilder();
    while (true) {
      c = in.read();
      if (c == ',' || c == ']') {
        if (size == array.length) {
          array = Arrays.copyOf(array, array.length * 2);
        }
        array[size++] = Integer.parseInt(item.toString());
        if (c == ']') {
          return Arrays.copyOf(array, size);
        }
        item.setLength(0);
      } else if (!Character.isWhitespace(c)) {
        item.append((char) c);
      }
    }
  }
예제 #22
0
파일: HTMLChars.java 프로젝트: kifetew/SWAT
  private IntAndString getPart(String text, int i, boolean terminateOnEndBraceOnly) {
    char c;
    int count = 0;

    StringBuffer part = new StringBuffer();

    // advance to first char and skip wihitespace
    i++;
    while (i < text.length() && Character.isWhitespace(text.charAt(i))) {
      i++;
    }

    // then grab whathever is the first token (counting braces)
    while (i < text.length()) {
      c = text.charAt(i);
      if (!terminateOnEndBraceOnly && count == 0 && Character.isWhitespace(c)) {
        i--; // end argument and leave whitespace for further
        // processing
        break;
      }
      if (c == '}' && --count < 0) break;
      else if (c == '{') count++;
      part.append(c);
      i++;
    }
    return new IntAndString(part.length(), format(part.toString()));
  }
예제 #23
0
 /**
  * Examines the string and returns whether we're inside a double quote.
  *
  * <p>This is used to decide whether we should put an automatic space before or after a double
  * quote character. If we're inside a quotation, then we want to close it, so we want a space
  * after and not before. Otherwise, we want to open the quotation, so we want a space before and
  * not after. Exception: after a digit, we never want a space because the "inch" or "minutes" use
  * cases is dominant after digits. In the practice, we determine whether we are in a quotation or
  * not by finding the previous double quote character, and looking at whether it's followed by
  * whitespace. If so, that was a closing quotation mark, so we're not inside a double quote. If
  * it's not followed by whitespace, then it was an opening quotation mark, and we're inside a
  * quotation.
  *
  * @param text the text to examine.
  * @return whether we're inside a double quote.
  */
 public static boolean isInsideDoubleQuoteOrAfterDigit(final CharSequence text) {
   int i = text.length();
   if (0 == i) return false;
   int codePoint = Character.codePointBefore(text, i);
   if (Character.isDigit(codePoint)) return true;
   int prevCodePoint = 0;
   while (i > 0) {
     codePoint = Character.codePointBefore(text, i);
     if (Constants.CODE_DOUBLE_QUOTE == codePoint) {
       // If we see a double quote followed by whitespace, then that
       // was a closing quote.
       if (Character.isWhitespace(prevCodePoint)) return false;
     }
     if (Character.isWhitespace(codePoint) && Constants.CODE_DOUBLE_QUOTE == prevCodePoint) {
       // If we see a double quote preceded by whitespace, then that
       // was an opening quote. No need to continue seeking.
       return true;
     }
     i -= Character.charCount(codePoint);
     prevCodePoint = codePoint;
   }
   // We reached the start of text. If the first char is a double quote, then we're inside
   // a double quote. Otherwise we're not.
   return Constants.CODE_DOUBLE_QUOTE == codePoint;
 }
  /**
   * 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;
  }
예제 #25
0
  public static String toPublicID(String value) {
    char[] buffer = value.toCharArray();
    int write = 0;
    int lastWrite = 0;
    boolean wroteOne = false;

    int read = 0;
    while (read < buffer.length && Character.isWhitespace(buffer[read])) {
      read++;
    }

    int len = buffer.length;
    while (len < read && Character.isWhitespace(buffer[read])) len--;

    while (read < len) {
      if (Character.isWhitespace(buffer[read])) {
        if (wroteOne) buffer[write++] = ' ';

        do {
          read++;
        } while (read < len && Character.isWhitespace(buffer[read]));
      } else {
        buffer[write++] = buffer[read++];
        wroteOne = true;
        lastWrite = write;
      }
    }

    value = new String(buffer, 0, lastWrite);
    return value;
  }
  /**
   * 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;
  }
예제 #27
0
 /**
  * Get the next token or string. This is used in parsing HTTP headers.
  *
  * @throws JSONException this will be thrown if there is an error parsing the JSON
  * @return A String.
  */
 public String nextToken() throws JSONException {
   char c;
   char q;
   StringBuffer sb = new StringBuffer();
   do {
     c = next();
   } while (Character.isWhitespace(c));
   if (c == '"' || c == '\'') {
     q = c;
     for (; ; ) {
       c = next();
       if (c < ' ') {
         throw syntaxError("Unterminated string.");
       }
       if (c == q) {
         return sb.toString();
       }
       sb.append(c);
     }
   }
   for (; ; ) {
     if (c == 0 || Character.isWhitespace(c)) {
       return sb.toString();
     }
     sb.append(c);
     c = next();
   }
 }
예제 #28
0
 /* (non-Javadoc)
  * @see org.eclipse.jdt.internal.compiler.parser.AbstractCommentParser#pushText(int, int)
  */
 protected void pushText(int start, int end) {
   // In case of previous return tag, verify that text make it not empty
   if (this.currentAstPtr != -2 && this.returnStatement != null) {
     int position = this.index;
     this.index = start;
     boolean empty = true;
     boolean star = false;
     char ch = readChar();
     // Look for first character other than white or '*'
     if (Character.isWhitespace(ch) || start > (this.tagSourceEnd + 1)) {
       while (this.index <= end && empty) {
         if (!star) {
           empty = Character.isWhitespace(ch) || ch == '*';
           star = ch == '*';
         } else if (ch != '*') {
           empty = false;
           break;
         }
         ch = readChar();
       }
     }
     // Store result in previous return tag
     ((JavadocReturnStatement) this.returnStatement).empty = empty;
     // Reset position and current ast ptr if we are on a different tag than previous return one
     this.index = position;
     if (this.currentAstPtr != this.astPtr) {
       this.currentAstPtr = -2;
     }
   }
 }
예제 #29
0
 /**
  * Compare two string, skipping all white spaces.
  *
  * @param first first string to be compared
  * @param second second string to be compared
  * @return if first string is smaller second string, return {@code -1}, if first string is larger
  *     than second string, return {@code 1}, otherwise return {@code 0}.
  */
 public static int compareSkipSpaces(String first, String second) {
   char[] firstCharArray = first.toCharArray();
   char[] secondCharArray = second.toCharArray();
   for (int i = 0, j = 0; ; ) {
     if (i < firstCharArray.length && Character.isWhitespace(firstCharArray[i])) {
       ++i;
     } else if (j < secondCharArray.length && Character.isWhitespace(secondCharArray[j])) {
       ++j;
     } else if (i == firstCharArray.length) {
       if (j == secondCharArray.length) {
         return 0;
       } else {
         return -1;
       }
     } else if (j == secondCharArray.length) {
       return 1;
     } else {
       if (firstCharArray[i] != secondCharArray[j]) {
         return firstCharArray[i] < secondCharArray[j] ? -1 : 1;
       } else {
         ++i;
         ++j;
       }
     }
   }
 }
예제 #30
0
  /** This method is used to parse the bibtex key for an entry. */
  private String parseKey() throws IOException, NoLabelException {
    StringBuffer token = new StringBuffer(20);

    while (true) {
      int c = read();
      // Util.pr(".. '"+(char)c+"'\t"+c);
      if (c == -1) {
        _eof = true;

        return token.toString();
      }

      // Ikke: #{}\uFFFD~\uFFFD
      //
      // G\uFFFDr: $_*+.-\/?"^
      if (!Character.isWhitespace((char) c)
          && (Character.isLetterOrDigit((char) c)
              || ((c != '#')
                  && (c != '{')
                  && (c != '}')
                  && (c != '\uFFFD')
                  && (c != '~')
                  && (c != '\uFFFD')
                  && (c != ',')
                  && (c != '=')))) {
        token.append((char) c);
      } else {

        if (Character.isWhitespace((char) c)) {
          // We have encountered white space instead of the comma at
          // the end of
          // the key. Possibly the comma is missing, so we try to
          // return what we
          // have found, as the key and try to restore the rest in fixKey().
          return token.toString() + fixKey();
        } else if (c == ',') {
          unread(c);
          return token.toString();
          // } else if (Character.isWhitespace((char)c)) {
          // throw new NoLabelException(token.toString());
        } else if (c == '=') {
          // If we find a '=' sign, it is either an error, or
          // the entry lacked a comma signifying the end of the key.

          return token.toString();
          // throw new NoLabelException(token.toString());

        } else
          throw new IOException(
              "Error in line "
                  + line
                  + ":"
                  + "Character '"
                  + (char) c
                  + "' is not "
                  + "allowed in bibtex keys.");
      }
    }
  }