Split into lines, pushing doublewidth characters at the end of a line to the next line.

        When a double-width character is pushed to the next line, a space is added to pad out the line.
4765
def width_aware_splitlines(self, columns):
        # type: (int) -> Iterator[FmtStr]
        
        if columns < 2:
            raise ValueError("Column width %s is too narrow." % columns)
        if wcswidth(self.s) == -1:
            raise ValueError('bad values for width aware slicing')
        return self._width_aware_splitlines(columns)
596565
function splitLongWord(word, options) {
  var wrapCharacters = options.longWordSplit.wrapCharacters || [];
  var forceWrapOnLimit = options.longWordSplit.forceWrapOnLimit || false;
  var max = options.wordwrap;

  var fuseWord = [];
  var idx = 0;
  while (word.length > max) {
    var firstLine = word.substr(0, max);
    var remainingChars = word.substr(max);

    var splitIndex = firstLine.lastIndexOf(wrapCharacters[idx]);

    if (splitIndex > -1) {
      // We've found a character to split on, store before the split then check if we
      // need to split again
      word = firstLine.substr(splitIndex + 1) + remainingChars;
      fuseWord.push(firstLine.substr(0, splitIndex + 1));
    } else {
      idx++;
      if (idx >= wrapCharacters.length) {
        // Cannot split on character, so either split at 'max' or preserve length
        if (forceWrapOnLimit) {
          fuseWord.push(firstLine);
          word = remainingChars;
          if (word.length > max) {
            continue;
          }
        } else {
          word = firstLine + remainingChars;
          if (!options.preserveNewlines) {
            word += '\n';
          }
        }
        break;
      } else {
        word = firstLine + remainingChars;
      }
    }
  }
  fuseWord.push(word);

  return fuseWord.join('\n');
}
271366
def line_width(line):
    
    if six.PY2:
        assert isinstance(line, unicode)
    _line = width_cal_preprocess(line)
    result = sum(map(get_char_width, _line))
    return result
1116534
function splitTickText(d, maxWidth) {
                    var tickText = textFormatted(d),
                        subtext, spaceIndex, textWidth, splitted = [];

                    if (Object.prototype.toString.call(tickText) === "[object Array]") {
                        return tickText;
                    }

                    if (!maxWidth || maxWidth <= 0) {
                        maxWidth = isVertical ? 95 : params.isCategory ? (Math.ceil(scale1(ticks[1]) - scale1(ticks[0])) - 12) : 110;
                    }

                    function split(splitted, text) {
                        spaceIndex = undefined;
                        for (var i = 1; i < text.length; i++) {
                            if (text.charAt(i) === ' ') {
                                spaceIndex = i;
                            }
                            subtext = text.substr(0, i + 1);
                            textWidth = sizeFor1Char.w * subtext.length;
                            // if text width gets over tick width, split by space index or crrent index
                            if (maxWidth < textWidth) {
                                return split(
                                    splitted.concat(text.substr(0, spaceIndex ? spaceIndex : i)),
                                    text.slice(spaceIndex ? spaceIndex + 1 : i)
                                );
                            }
                        }
                        return splitted.concat(text);
                    }

                    return split(splitted, tickText + "");
                }
130280
def _split_line(self, line):
        """"""
        line = line.rstrip('\r\n')
        flds = re.split('\t', line)
        assert len(flds) == self.exp_numcol, "EXPECTED({E}) COLUMNS, ACTUAL({A}): {L}".format(
            E=self.exp_numcol, A=len(flds), L=line)
        return flds
685034
def truncate(string, width, options={})
      trailing = options[:trailing] || '…'

      chars = string.to_s.chars.to_a
      if chars.length < width && chars.length > 3
        chars.join
      elsif chars.length > 3
        (chars[0, width - trailing.length].join) + trailing
      end
    end
478729
def line_break(s, length=76):
    
    x = '\n'.join(s[pos:pos + length] for pos in range(0, len(s), length))
    return x
348747
public static void wordWrap(String string, int width, Appendable out) throws IOException {
		width++;
		boolean useCR = false;
		do {
			int pos = string.indexOf('\n');
			if (!useCR && pos > 0 && string.charAt(pos - 1) == '\r') useCR = true;
			int linelength = pos == -1 ? string.length() : pos + 1;
			if ((pos==-1?linelength-1:pos) <= width) {
				// No wrap required
				out.append(string, 0, linelength);
				string = string.substring(linelength);
			} else {
				// Word wrap required

				// Search for the beginning of the first word that is past the <code>width</code> column
				// The wrap character must be on the same line as the outputted line.
				int lastBreakChar = 0;

				for (int c = 0; c < width; c++) {
					// Check to see if it is a break character
					char ch = string.charAt(c);
					boolean isBreak = false;
					for (int d = 0; d < wordWrapChars.length; d++) {
						if (ch == wordWrapChars[d]) {
							isBreak = true;
							break;
						}
					}
					if (isBreak) lastBreakChar = c + 1;
				}

				// If no break has been found, keep searching until a break is found
				if (lastBreakChar == 0) {
					for (int c = width; c < linelength; c++) {
						char ch = string.charAt(c);
						boolean isBreak = false;
						for (int d = 0; d < wordWrapChars.length; d++) {
							if (ch == wordWrapChars[d]) {
								isBreak = true;
								break;
							}
						}
						if (isBreak) {
							lastBreakChar = c + 1;
							break;
						}
					}
				}

				if (lastBreakChar == 0) {
					// Take the whole line
					out.append(string, 0, linelength);
					string = string.substring(linelength);
				} else {
					// Break out the section
					out.append(string, 0, lastBreakChar);
					if(useCR) out.append("\r\n");
					else out.append('\n');
					string = string.substring(lastBreakChar);
				}
			}
		} while (string.length() > 0);
	}
983837
def split_leading_trailing_indent(line, max_indents=None):
    """"""
    leading_indent, line = split_leading_indent(line, max_indents)
    line, trailing_indent = split_trailing_indent(line, max_indents)
    return leading_indent, line, trailing_indent
24516
function(str, indent) {
			var lines = str.split("\n");
			for (var i=0; i<lines.length; i++)
				lines[i] = indent + lines[i];
			return lines.join("\n");
		}
202601
void append(String s) throws IOException {
    if (closed) throw new IllegalStateException("closed");

    if (nextFlush != null) {
      int nextNewline = s.indexOf('\n');

      // If s doesn't cause the current line to cross the limit, buffer it and return. We'll decide
      // whether or not we have to wrap it later.
      if (nextNewline == -1 && column + s.length() <= columnLimit) {
        buffer.append(s);
        column += s.length();
        return;
      }

      // Wrap if appending s would overflow the current line.
      boolean wrap = nextNewline == -1 || column + nextNewline > columnLimit;
      flush(wrap ? FlushType.WRAP : nextFlush);
    }

    out.append(s);
    int lastNewline = s.lastIndexOf('\n');
    column = lastNewline != -1
        ? s.length() - lastNewline - 1
        : column + s.length();
  }
650183
function createPadding (width) {
  var result = ''
  var string = ' '
  var n = width
  do {
    if (n % 2) {
      result += string;
    }
    n = Math.floor(n / 2);
    string += string;
  } while (n);

  return result;
}
53556
private String expandLHS(final String lhs,
                             int lineOffset) {
        substitutions = new ArrayList<Map<String, String>>();

        //        logger.info( "*** LHS>" + lhs + "<" );
        final StringBuilder buf = new StringBuilder();
        
        final String[] lines = lhs.split( (lhs.indexOf("\r\n") >= 0 ? "\r\n":"\n"),
                                          -1 ); // since we assembled the string, we know line breaks are \n
        final String[] expanded = new String[lines.length]; // buffer for expanded lines
        int lastExpanded = -1;
        int lastPattern = -1;
        for ( int i = 0; i < lines.length - 1; i++ ) {
            final String trimmed = lines[i].trim();
            expanded[++lastExpanded] = lines[i];

            if ( trimmed.length() == 0 || trimmed.startsWith( "#" ) || trimmed.startsWith( "//" ) ) {
                // comments - do nothing
            } else if ( trimmed.startsWith( ">" ) ) {
                // passthrough code - simply remove the passthrough mark character
                expanded[lastExpanded] = lines[i].replaceFirst( ">",
                                                                " " );
                lastPattern = lastExpanded;
            } else {
                // regular expansion - expand the expression
                expanded[lastExpanded] =
                        substitute( expanded[lastExpanded],
                                    this.condition,
                                    i + lineOffset,
                                    useWhen,
                                    showSteps );

                // do we need to report errors for that?
                if ( lines[i].equals( expanded[lastExpanded] ) ) {
                    // report error
                    this.addError( new ExpanderException( "Unable to expand: " + lines[i].replaceAll( "[\n\r]",
                                                                                                      "" ).trim(),
                                                          i + lineOffset ) );
                }
                // but if the original starts with a "-", it means we need to add it
                // as a constraint to the previous pattern
                if ( trimmed.startsWith( "-" ) && (!lines[i].equals( expanded[lastExpanded] )) ) {
                    if ( lastPattern >= 0 ) {
                        ConstraintInformation c = ConstraintInformation.findConstraintInformationInPattern( expanded[lastPattern] );
                        if ( c.start > -1 ) {
                            // rebuilding previous pattern structure
                            expanded[lastPattern] = expanded[lastPattern].substring( 0,
                                                                                     c.start ) + c.constraints + ((c.constraints.trim().length() == 0) ? "" : ", ") + expanded[lastExpanded].trim() + expanded[lastPattern].substring( c.end );
                        } else {
                            // error, pattern not found to add constraint to
                            this.addError( new ExpanderException( "No pattern was found to add the constraint to: " + lines[i].trim(),
                                                                  i + lineOffset ) );
                        }
                    }
                    lastExpanded--;
                } else {
                    lastPattern = lastExpanded;
                }
            }
        }
        for ( int i = 0; i <= lastExpanded; i++ ) {
            buf.append( expanded[i] );
            buf.append( nl );
        }

        return buf.toString();
    }
1261601
def wrap_text(text, width):
        
        out = []
        for paragraph in text.splitlines():
            # Wrap returns an empty list when paragraph is a newline. In order
            # to preserve newlines we substitute a list containing an empty
            # string.
            lines = wrap(paragraph, width=width) or ['']
            out.extend(lines)
        return out
601284
def _line(self, text, indent=0):
        """"""
        leading_space = '  ' * indent
        while len(leading_space) + len(text) > self.width:
            # The text is too wide; wrap if possible.

            # Find the rightmost space that would obey our width constraint and
            # that's not an escaped space.
            available_space = self.width - len(leading_space) - len(' $')
            space = available_space
            while True:
                space = text.rfind(' ', 0, space)
                if (space < 0 or
                    self._count_dollars_before_index(text, space) % 2 == 0):
                    break

            if space < 0:
                # No such space; just use the first unescaped space we can find.
                space = available_space - 1
                while True:
                    space = text.find(' ', space + 1)
                    if (space < 0 or
                        self._count_dollars_before_index(text, space) % 2 == 0):
                        break
            if space < 0:
                # Give up on breaking.
                break

            self.output.write(leading_space + text[0:space] + ' $\n')
            text = text[space+1:]

            # Subsequent lines are continuations, so indent them.
            leading_space = '  ' * (indent+2)

        self.output.write(leading_space + text + '\n')
760631
def formatLine(self, line, indent=0, outcome_char=''):
        
        actual_spaces = (indent * self.indent_spaces) - len(outcome_char)
        return (outcome_char + ' ' * actual_spaces + line)
1330778
PdfChunk split(float width) {
        newlineSplit = false;
        if (image != null) {
            if (image.getScaledWidth() > width) {
                PdfChunk pc = new PdfChunk(Chunk.OBJECT_REPLACEMENT_CHARACTER, this);
                value = "";
                attributes = new HashMap();
                image = null;
                font = PdfFont.getDefaultFont();
                return pc;
            }
            else
                return null;
        }
        HyphenationEvent hyphenationEvent = (HyphenationEvent)noStroke.get(Chunk.HYPHENATION);
        int currentPosition = 0;
        int splitPosition = -1;
        float currentWidth = 0;
        
        // loop over all the characters of a string
        // or until the totalWidth is reached
        int lastSpace = -1;
        float lastSpaceWidth = 0;
        int length = value.length();
        char valueArray[] = value.toCharArray();
        char character = 0;
        BaseFont ft = font.getFont();
        boolean surrogate = false;
        if (ft.getFontType() == BaseFont.FONT_TYPE_CJK && ft.getUnicodeEquivalent(' ') != ' ') {
            while (currentPosition < length) {
                // the width of every character is added to the currentWidth
                char cidChar = valueArray[currentPosition];
                character = (char)ft.getUnicodeEquivalent(cidChar);
                // if a newLine or carriageReturn is encountered
                if (character == '\n') {
                    newlineSplit = true;
                    String returnValue = value.substring(currentPosition + 1);
                    value = value.substring(0, currentPosition);
                    if (value.length() < 1) {
                        value = "\u0001";
                    }
                    PdfChunk pc = new PdfChunk(returnValue, this);
                    return pc;
                }
                currentWidth += font.width(cidChar);
                if (character == ' ') {
                    lastSpace = currentPosition + 1;
                    lastSpaceWidth = currentWidth;
                }
                if (currentWidth > width)
                    break;
                // if a split-character is encountered, the splitPosition is altered
                if (splitCharacter.isSplitCharacter(0, currentPosition, length, valueArray, thisChunk))
                    splitPosition = currentPosition + 1;
                currentPosition++;
            }
        }
        else {
            while (currentPosition < length) {
                // the width of every character is added to the currentWidth
                character = valueArray[currentPosition];
                // if a newLine or carriageReturn is encountered
                if (character == '\r' || character == '\n') {
                    newlineSplit = true;
                    int inc = 1;
                    if (character == '\r' && currentPosition + 1 < length && valueArray[currentPosition + 1] == '\n')
                        inc = 2;
                    String returnValue = value.substring(currentPosition + inc);
                    value = value.substring(0, currentPosition);
                    if (value.length() < 1) {
                        value = " ";
                    }
                    PdfChunk pc = new PdfChunk(returnValue, this);
                    return pc;
                }
                surrogate = Utilities.isSurrogatePair(valueArray, currentPosition);
                if (surrogate)
                    currentWidth += font.width(Utilities.convertToUtf32(valueArray[currentPosition], valueArray[currentPosition + 1]));
                else
                    currentWidth += font.width(character);
                if (character == ' ') {
                    lastSpace = currentPosition + 1;
                    lastSpaceWidth = currentWidth;
                }
                if (surrogate)
                    currentPosition++;
                if (currentWidth > width)
                    break;
                // if a split-character is encountered, the splitPosition is altered
                if (splitCharacter.isSplitCharacter(0, currentPosition, length, valueArray, null))
                    splitPosition = currentPosition + 1;
                currentPosition++;
            }
        }
        
        // if all the characters fit in the total width, null is returned (there is no overflow)
        if (currentPosition == length) {
            return null;
        }
        // otherwise, the string has to be truncated
        if (splitPosition < 0) {
            String returnValue = value;
            value = "";
            PdfChunk pc = new PdfChunk(returnValue, this);
            return pc;
        }
        if (lastSpace > splitPosition && splitCharacter.isSplitCharacter(0, 0, 1, singleSpace, null))
            splitPosition = lastSpace;
        if (hyphenationEvent != null && lastSpace >= 0 && lastSpace < currentPosition) {
            int wordIdx = getWord(value, lastSpace);
            if (wordIdx > lastSpace) {
                String pre = hyphenationEvent.getHyphenatedWordPre(value.substring(lastSpace, wordIdx), font.getFont(), font.size(), width - lastSpaceWidth);
                String post = hyphenationEvent.getHyphenatedWordPost();
                if (pre.length() > 0) {
                    String returnValue = post + value.substring(wordIdx);
                    value = trim(value.substring(0, lastSpace) + pre);
                    PdfChunk pc = new PdfChunk(returnValue, this);
                    return pc;
                }
            }
        }
        String returnValue = value.substring(splitPosition);
        value = trim(value.substring(0, splitPosition));
        PdfChunk pc = new PdfChunk(returnValue, this);
        return pc;
    }