From 4e7e45ab35db5ef68fc52b0ba936f12ad49cd12a Mon Sep 17 00:00:00 2001 From: Florian Heinle Date: Thu, 7 Sep 2017 11:21:11 +0200 Subject: [PATCH] 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. --- jinja2/filters.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) 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): -- 2.47.2