Ticket #1919: truncate_words_preserving_whitespace.diff

File truncate_words_preserving_whitespace.diff, 1.2 KB (added by Tom Tobin <korpios@…>, 18 years ago)

patch against r2991 (trunk); cause truncatewords filter to preserve whitespace

  • django/utils/text.py

     
    2020                  text.split(' ')
    2121                 )
    2222
     23whitespace_re = re.compile(r'(\s+)')
    2324def truncate_words(s, num):
    2425    "Truncates a string after a certain number of words."
    2526    length = int(num)
    26     words = s.split()
    27     if len(words) > length:
    28         words = words[:length]
    29         if not words[-1].endswith('...'):
    30             words.append('...')
    31     return ' '.join(words)
     27    words = whitespace_re.split(s)
     28    outwords = []
     29    wordcount = 0
     30    for word in words:
     31        if word == '':
     32            continue
     33        if whitespace_re.search(word):
     34            outwords.append(word)
     35            continue # don't count towards length
     36        if wordcount >= length:
     37            break
     38        outwords.append(word)
     39        cutoff_word = word
     40        wordcount += 1
     41    else:
     42        cutoff_word = None
     43    if cutoff_word is not None and not cutoff_word.endswith('...'):
     44        outwords.append('...')
     45    return ''.join(outwords)
    3246
    3347def get_valid_filename(s):
    3448    """
Back to Top