public static String wordWrap()

in app/src/main/java/org/apache/roller/weblogger/ui/tags/WordWrapTag.java [160:246]


    public static String wordWrap(String str, int width, String delim,
                                  String split, boolean delimInside) {
        int sz = str.length();

        /// shift width up one. mainly as it makes the logic easier
        width++;

        // our best guess as to an initial size
        StringBuilder buffer = new StringBuilder(sz / width * delim.length() + sz);

        // every line might include a delim on the end
        if (delimInside) {
            width = width - delim.length();
        } else {
            width--;
        }

        int idx;
        String substr;

        // beware: i is rolled-back inside the loop
        for (int i = 0; i < sz; i += width) {

            // on the last line
            if (i > sz - width) {
                buffer.append(str.substring(i));
                break;
            }

            // the current line
            substr = str.substring(i, i + width);

            // is the delim already on the line
            idx = substr.indexOf(delim);
            if (idx != -1) {
                buffer.append(substr.substring(0, idx));
                buffer.append(delim);
                i -= width - idx - delim.length();

                // Erase a space after a delim. Is this too obscure?
                if (substr.length() > idx + 1 && (substr.charAt(idx + 1) != '\n') && Character.isWhitespace(substr.charAt(idx + 1))) {
                    i++;
                }
                continue;
            }

            idx = -1;

            // figure out where the last space is
            char[] chrs = substr.toCharArray();
            for (int j = width; j > 0; j--) {
                if (Character.isWhitespace(chrs[j - 1])) {
                    idx = j;
                    break;
                }
            }

            // idx is the last whitespace on the line.
            if (idx == -1) {
                for (int j = width; j > 0; j--) {
                    if (chrs[j - 1] == '-') {
                        idx = j;
                        break;
                    }
                }
                if (idx == -1) {
                    buffer.append(substr);
                    buffer.append(delim);
                } else {
                    if (idx != width) {
                        idx++;
                    }
                    buffer.append(substr.substring(0, idx));
                    buffer.append(delim);
                    i -= width - idx;
                }
            } else {
                // insert spaces
                buffer.append(substr.substring(0, idx));
                buffer.append(StringUtils.repeat(" ", width - idx));
                buffer.append(delim);
                i -= width - idx;
            }
        }

        return buffer.toString();
    }