Code

Ticket #1919: truncate_words_preserving_whitespace.diff

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

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

Line 
1Index: django/utils/text.py
2===================================================================
3--- django/utils/text.py        (revision 2991)
4+++ django/utils/text.py        (working copy)
5@@ -20,15 +20,29 @@
6                   text.split(' ')
7                  )
8 
9+whitespace_re = re.compile(r'(\s+)')
10 def truncate_words(s, num):
11     "Truncates a string after a certain number of words."
12     length = int(num)
13-    words = s.split()
14-    if len(words) > length:
15-        words = words[:length]
16-        if not words[-1].endswith('...'):
17-            words.append('...')
18-    return ' '.join(words)
19+    words = whitespace_re.split(s)
20+    outwords = []
21+    wordcount = 0
22+    for word in words:
23+        if word == '':
24+            continue
25+        if whitespace_re.search(word):
26+            outwords.append(word)
27+            continue # don't count towards length
28+        if wordcount >= length:
29+            break
30+        outwords.append(word)
31+        cutoff_word = word
32+        wordcount += 1
33+    else:
34+        cutoff_word = None
35+    if cutoff_word is not None and not cutoff_word.endswith('...'):
36+        outwords.append('...')
37+    return ''.join(outwords)
38 
39 def get_valid_filename(s):
40     """