@@ -268,6 +268,35 @@ def wrap_long_lines(text):
268268 filled += [ line .rstrip () ]
269269 return "\n " .join (filled )
270270
271+ @register .filter (name = "wrap_text" )
272+ def wrap_text (text , width = 72 ):
273+ """Wraps long lines without loosing the formatting and indentation
274+ of short lines"""
275+ if not isinstance (text , (types .StringType ,types .UnicodeType )):
276+ return text
277+ text = re .sub (" *\r \n " , "\n " , text ) # get rid of DOS line endings
278+ text = re .sub (" *\r " , "\n " , text ) # get rid of MAC line endings
279+ text = re .sub ("( *\n ){3,}" , "\n \n " , text ) # get rid of excessive vertical whitespace
280+ lines = text .split ("\n " )
281+ filled = []
282+ wrapped = False
283+ for line in lines :
284+ expanded = line .expandtabs ()
285+ indent = " " * (len (expanded ) - len (expanded .lstrip ()))
286+ if wrapped and line .strip () != "" and indent == prev_indent :
287+ line = filled [- 1 ] + " " + line .lstrip ()
288+ filled = filled [:- 1 ]
289+ else :
290+ wrapped = False
291+ while (len (line ) > width ) and (" " in line [:width ]):
292+ wrapped = True
293+ breakpoint = line .rfind (" " ,0 ,width )
294+ filled += [ line [:breakpoint ] ]
295+ line = indent + line [breakpoint + 1 :]
296+ filled += [ line .rstrip () ]
297+ prev_indent = indent
298+ return "\n " .join (filled )
299+
271300@register .filter (name = "id_index_file_types" )
272301def id_index_file_types (text ):
273302 r = ".txt"
0 commit comments