Shorten the line taking its length into account.

    The input is expected to be free of newlines except for inside
    multiline strings and at the end.
543116
def _shorten_line_at_tokens_new(tokens, source, indentation,
                                max_line_length):
    
    # Yield the original source so to see if it's a better choice than the
    # shortened candidate lines we generate here.
    yield indentation + source

    parsed_tokens = _parse_tokens(tokens)

    if parsed_tokens:
        # Perform two reflows. The first one starts on the same line as the
        # prefix. The second starts on the line after the prefix.
        fixed = _reflow_lines(parsed_tokens, indentation, max_line_length,
                              start_on_prefix_line=True)
        if fixed and check_syntax(normalize_multiline(fixed.lstrip())):
            yield fixed

        fixed = _reflow_lines(parsed_tokens, indentation, max_line_length,
                              start_on_prefix_line=False)
        if fixed and check_syntax(normalize_multiline(fixed.lstrip())):
            yield fixed
635994
def readline(self, length=None):
        
        if length == 0:
            return b''

        self._fillbuff()

        if self.empty():
            return b''

        linebuff = self.buff.readline(length)

        # we may be at a boundary
        while not linebuff.endswith(b'\n'):
            if length:
                length -= len(linebuff)
                if length <= 0:
                    break

            self._fillbuff()

            if self.empty():
                break

            linebuff += self.buff.readline(length)

        return linebuff
668227
def smart_truncate(value, max_length=0, word_boundaries=False, separator=' '):
    

    value = value.strip(separator)

    if not max_length:
        return value

    if len(value) < max_length:
        return value

    if not word_boundaries:
        return value[:max_length].strip(separator)

    if separator not in value:
        return value[:max_length]

    truncated = ''
    for word in value.split(separator):
        if word:
            next_len = len(truncated) + len(word) + len(separator)
            if next_len <= max_length:
                truncated += '{0}{1}'.format(word, separator)
    if not truncated:
        truncated = value[:max_length]
    return truncated.strip(separator)
1187078
def wrap(string, length, indent):
    
    newline = "\n" + " " * indent
    return newline.join((string[i : i + length] for i in range(0, len(string), length)))
619304
def shorten(original_chars, chars, length_without_trailing)
      truncated = []
      char_width = display_width(chars[0])
      while length_without_trailing - char_width > 0
        orig_char = original_chars.shift
        char = chars.shift
        break unless char
        while orig_char != char # consume ansi
          ansi = true
          truncated << orig_char
          orig_char = original_chars.shift
        end
        truncated << char
        char_width = display_width(char)
        length_without_trailing -= char_width
      end
      truncated << ["\e[0m"] if ansi
      truncated
    end
1308893
def shorten(string, max_length=80, trailing_chars=3):
    '''  '''
    assert type(string).__name__ in {'str', 'unicode'}, 'shorten needs string to be a string, not {}'.format(type(string))
    assert type(max_length) == int, 'shorten needs max_length to be an int, not {}'.format(type(max_length))
    assert type(trailing_chars) == int, 'shorten needs trailing_chars to be an int, not {}'.format(type(trailing_chars))
    assert max_length > 0, 'shorten needs max_length to be positive, not {}'.format(max_length)
    assert trailing_chars >= 0, 'shorten needs trailing_chars to be greater than or equal to 0, not {}'.format(trailing_chars)

    return (
        string
    ) if len(string) <= max_length else (
        '{before:}...{after:}'.format(
            before=string[:max_length-(trailing_chars+3)],
            after=string[-trailing_chars:] if trailing_chars>0 else ''
        )
    )
432687
def shorten(string, maxlen):
    """"""
    if 1 < maxlen < len(string):
        string = string[:maxlen - 1] + u'…'
    return string[:maxlen]
414763
function(text, length, moreText) {
    var t = text.split('</p>');
    return t.length < length ? text : t.slice(0, length).join('</p>') + '</p>' + moreText;
  }
872392
def truncate(input, max = 30)
      return input if input.nil? || input.length <= max

      input[0..max - 1].gsub(/\s\w+\s*$/, '...')
    end
187707
def normalize_multiline(line):
    
    if line.startswith('def ') and line.rstrip().endswith(':'):
        return line + ' pass'
    elif line.startswith('return '):
        return 'def _(): ' + line
    elif line.startswith('@'):
        return line + 'def _(): pass'
    elif line.startswith('class '):
        return line + ' pass'
    elif line.startswith(('if ', 'elif ', 'for ', 'while ')):
        return line + ' pass'
    else:
        return line
456410
def line_shortening_rank(candidate, indent_word, max_line_length,
                         experimental=False):
    
    if not candidate.strip():
        return 0

    rank = 0
    lines = candidate.rstrip().split('\n')

    offset = 0
    if (
        not lines[0].lstrip().startswith('#') and
        lines[0].rstrip()[-1] not in '([{'
    ):
        for (opening, closing) in ('()', '[]', '{}'):
            # Don't penalize empty containers that aren't split up. Things like
            # this "foo(\n    )" aren't particularly good.
            opening_loc = lines[0].find(opening)
            closing_loc = lines[0].find(closing)
            if opening_loc >= 0:
                if closing_loc < 0 or closing_loc != opening_loc + 1:
                    offset = max(offset, 1 + opening_loc)

    current_longest = max(offset + len(x.strip()) for x in lines)

    rank += 4 * max(0, current_longest - max_line_length)

    rank += len(lines)

    # Too much variation in line length is ugly.
    rank += 2 * standard_deviation(len(line) for line in lines)

    bad_staring_symbol = {
        '(': ')',
        '[': ']',
        '{': '}'}.get(lines[0][-1])

    if len(lines) > 1:
        if (
            bad_staring_symbol and
            lines[1].lstrip().startswith(bad_staring_symbol)
        ):
            rank += 20

    for lineno, current_line in enumerate(lines):
        current_line = current_line.strip()

        if current_line.startswith('#'):
            continue

        for bad_start in ['.', '%', '+', '-', '/']:
            if current_line.startswith(bad_start):
                rank += 100

            # Do not tolerate operators on their own line.
            if current_line == bad_start:
                rank += 1000

        if (
            current_line.endswith(('.', '%', '+', '-', '/')) and
            "': " in current_line
        ):
            rank += 1000

        if current_line.endswith(('(', '[', '{', '.')):
            # Avoid lonely opening. They result in longer lines.
            if len(current_line) <= len(indent_word):
                rank += 100

            # Avoid the ugliness of ", (\n".
            if (
                current_line.endswith('(') and
                current_line[:-1].rstrip().endswith(',')
            ):
                rank += 100

            # Avoid the ugliness of "something[\n" and something[index][\n.
            if (
                current_line.endswith('[') and
                len(current_line) > 1 and
                (current_line[-2].isalnum() or current_line[-2] in ']')
            ):
                rank += 300

            # Also avoid the ugliness of "foo.\nbar"
            if current_line.endswith('.'):
                rank += 100

            if has_arithmetic_operator(current_line):
                rank += 100

        # Avoid breaking at unary operators.
        if re.match(r'.*[(\[{]\s*[\-\+~]$', current_line.rstrip('\\ ')):
            rank += 1000

        if re.match(r'.*lambda\s*\*$', current_line.rstrip('\\ ')):
            rank += 1000

        if current_line.endswith(('%', '(', '[', '{')):
            rank -= 20

        # Try to break list comprehensions at the "for".
        if current_line.startswith('for '):
            rank -= 50

        if current_line.endswith('\\'):
            # If a line ends in \-newline, it may be part of a
            # multiline string. In that case, we would like to know
            # how long that line is without the \-newline. If it's
            # longer than the maximum, or has comments, then we assume
            # that the \-newline is an okay candidate and only
            # penalize it a bit.
            total_len = len(current_line)
            lineno += 1
            while lineno < len(lines):
                total_len += len(lines[lineno])

                if lines[lineno].lstrip().startswith('#'):
                    total_len = max_line_length
                    break

                if not lines[lineno].endswith('\\'):
                    break

                lineno += 1

            if total_len < max_line_length:
                rank += 10
            else:
                rank += 100 if experimental else 1

        # Prefer breaking at commas rather than colon.
        if ',' in current_line and current_line.endswith(':'):
            rank += 10

        # Avoid splitting dictionaries between key and value.
        if current_line.endswith(':'):
            rank += 100

        rank += 10 * count_unbalanced_brackets(current_line)

    return max(0, rank)
1026438
function(text, length, moreText) {
    return text.length > length ? text.slice(0, length).trim() + moreText : text;
  }
941269
public static int lengthWithoutLinefeed(CharSequence line) {
    int length = line.length();
    while(length > 0) {
      char last = line.charAt(length - 1);
      if(last != '\n' && last != '\r') {
        break;
      }
      --length;
    }
    return length;
  }
985496
private static Queue<String> removePrefix(final List<String> input) {
        if (input.size() < 2) {
            return new LinkedList<>(input);
        }
        String resultingPrefix = "";
        final String previousGreatestCommonPrefix = input.get(0).trim();
        String greatestCommonPrefix = "";
        for (int i = 1; i < input.size(); i++) {
            final String previousLine = input.get(i - 1).trim();
            final String currentLine = input.get(i).trim();
            greatestCommonPrefix = ExceptionParser.greatestCommonPrefix(previousLine, currentLine);
            resultingPrefix = ExceptionParser.greatestCommonPrefix(previousGreatestCommonPrefix, greatestCommonPrefix);
            if (resultingPrefix.length() == 0) {
                break;
            }
        }
        final int prefixLength = resultingPrefix.length();
        final boolean hasPrefix = prefixLength > 0;
        final Queue<String> result = new LinkedList<>();
        for (final String line : input) {
            final String line2 = line.trim();
            if (hasPrefix) {
                result.add(line2.substring(prefixLength));
            } else {
                result.add(line2);
            }
        }
        return result;
    }
534845
private List<String> wrapLines(String line, final int maxLength) {
    	List<String> rv = new ArrayList<String>();
        for (String restOfLine : line.split("\\n")) {
            while (restOfLine.length() > maxLength) {
                // try to wrap at space, but don't try too hard as some languages don't even have whitespaces.
                int lineLength;
                String candidate = restOfLine.substring(0, maxLength);
                int sp=candidate.lastIndexOf(' ');
                if(sp>maxLength*3/5)    lineLength=sp;
                else                    lineLength=maxLength;
                rv.add(restOfLine.substring(0, lineLength));
                restOfLine = restOfLine.substring(lineLength).trim();
            }
            rv.add(restOfLine);
        }
    	return rv;
    }
426670
function truncate(string) {
  if (string.length > SEG_LENGTH * 2 + 3) {
    return string.slice(0, SEG_LENGTH) + '...' + string.slice(-SEG_LENGTH);
  }

  return string;
}
761054
function truncate(str, len) {
        // Truncate text to specified length
        if (str.length > len) {
            str = str.substr(0, len);

            // To prevent awkwardly truncating in the middle of a word,
            // attempt to truncate at the end of the last whole word
            var lastSpaceChar = str.lastIndexOf(" ");
            if (lastSpaceChar < len && lastSpaceChar > -1) {
                str = str.substr(0, lastSpaceChar);
            }
            return str;
        }
    }