From: Florian Heinle Date: Thu, 7 Sep 2017 09:21:11 +0000 (+0200) Subject: let wordwrap filter respect existing newlines X-Git-Tag: 2.11.0~26^2~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=4e7e45ab35db5ef68fc52b0ba936f12ad49cd12a;p=thirdparty%2Fjinja.git let wordwrap filter respect existing newlines textwrap.wrap() has unexpected behaviour where when wrapping multiple paragraphs it will not consider existing newlines. I.e. when your first paragraph ends on col 75, the next paragraph will be wrapped on col 5 already. This patch is wrapping each line individually and combining it back together. --- diff --git a/jinja2/filters.py b/jinja2/filters.py index 2b8e950c..feb00eb5 100644 --- a/jinja2/filters.py +++ b/jinja2/filters.py @@ -700,9 +700,23 @@ def do_wordwrap(environment, s, width=79, break_long_words=True, if not wrapstring: wrapstring = environment.newline_sequence import textwrap - return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False, - replace_whitespace=False, - break_long_words=break_long_words)) + # Work around textwrap.wrap()'s unexpected behaviour when wrapping multiple + # paragraphs. I.e. if your first paragraph ends on col 75, the next + # next paragraph would be wrapped on col 5 already, so we're going to wrap + # each paragraph individually. + paragraphs = str.splitlines(s) + paragraphs_wrapped = [] + for paragraph in paragraphs: + paragraph_wrapped = wrapstring.join( + textwrap.wrap(paragraph, + width=width, + expand_tabs=False, + replace_whitespace=False, + break_long_words=break_long_words + ) + ) + paragraphs_wrapped.append(paragraph_wrapped) + return wrapstring.join(paragraphs_wrapped) def do_wordcount(s):