1
0
mirror of https://github.com/django/django.git synced 2024-12-23 09:36:06 +00:00

Fixed #6668 -- Optimized utils.text wrap function

This fixes a failing test after applying an optimization of the
utils.text.wrap function by user SmileyChris.
This commit is contained in:
Markus Amalthea Magnuson 2014-05-16 18:39:03 +02:00 committed by Claude Paroz
parent b6b873d2ad
commit acb20016c0

View File

@ -34,30 +34,33 @@ re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))')
def wrap(text, width): def wrap(text, width):
""" """
A word-wrap function that preserves existing line breaks and most spaces in A word-wrap function that preserves existing line breaks. Expects that
the text. Expects that existing line breaks are posix newlines. existing line breaks are posix newlines.
All white space is preserved except added line breaks consume the space on
which they break the line.
Long words are not wrapped, so the output text may have lines longer than
``width``.
""" """
text = force_text(text) text = force_text(text)
def _generator(): def _generator():
it = iter(text.split(' ')) for line in text.splitlines(True): # True keeps trailing linebreaks
word = next(it) max_width = min((line.endswith('\n') and width + 1 or width), width)
yield word while len(line) > max_width:
pos = len(word) - word.rfind('\n') - 1 space = line[:max_width + 1].rfind(' ') + 1
for word in it: if space == 0:
if "\n" in word: space = line.find(' ') + 1
lines = word.split('\n') if space == 0:
else: yield line
lines = (word,) line = ''
pos += len(lines[0]) + 1 break
if pos > width: yield '%s\n' % line[:space - 1]
yield '\n' line = line[space:]
pos = len(lines[-1]) max_width = min((line.endswith('\n') and width + 1 or width), width)
else: if line:
yield ' ' yield line
if len(lines) > 1:
pos = len(lines[-1])
yield word
return ''.join(_generator()) return ''.join(_generator())
wrap = allow_lazy(wrap, six.text_type) wrap = allow_lazy(wrap, six.text_type)