]> git.ipfire.org Git - thirdparty/jinja.git/commitdiff
let wordwrap filter respect existing newlines
authorFlorian Heinle <florian.heinle@makandra.de>
Thu, 7 Sep 2017 09:21:11 +0000 (11:21 +0200)
committerDavid Lord <davidism@gmail.com>
Fri, 1 Nov 2019 14:56:03 +0000 (07:56 -0700)
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

index 2b8e950c117be64fcb59d1142710b2ceedacc897..feb00eb5caad399d94b9cfa4be4f2e6fff170eb5 100644 (file)
@@ -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):