Code

Ticket #1919: truncate_words_preserving_whites.diff

File truncate_words_preserving_whites.diff, 962 bytes (added by didier Belot <dib@…>, 7 years ago)

patch against trunk rev. 5783, simplified

Line 
1Index: django/utils/text.py
2===================================================================
3--- django/utils/text.py        (revision 5783)
4+++ django/utils/text.py        (working copy)
5@@ -35,16 +35,17 @@
6     return u''.join(_generator())
7 wrap = allow_lazy(wrap, unicode)
8
9+word_re = re.compile(r'((?:\*|_)*\w+(?:\*|_)*)',re.UNICODE)
10 def truncate_words(s, num):
11-    "Truncates a string after a certain number of words."
12+    "Truncates a string after a certain number of words, preserving whites."
13     s = force_unicode(s)
14     length = int(num)
15-    words = s.split()
16-    if len(words) > length:
17-        words = words[:length]
18+    words = word_re.split(s,length)
19+    if len(words) > (2*length):
20+        words = words[:-1]
21         if not words[-1].endswith('...'):
22             words.append('...')
23-    return u' '.join(words)
24+    return u''.join(words)
25 truncate_words = allow_lazy(truncate_words, unicode)
26
27 def truncate_html_words(s, num):
28