8080# Useful constants and functions
8181#
8282
83- WSP = set (' \t ' )
83+ _WSP = ' \t '
84+ WSP = set (_WSP )
8485CFWS_LEADER = WSP | set ('(' )
8586SPECIALS = set (r'()<>@,:;.\"[]' )
8687ATOM_ENDS = SPECIALS | WSP
@@ -2858,6 +2859,12 @@ def _steal_all_trailing_WSP_if_exists(lines):
28582859 return '' .join (wsp_lines )
28592860
28602861
2862+ def _last_word_is_sill_ew (_last_word_is_ew , added_str ):
2863+ # If the last word is an encoded word, and the added string is all WSP,
2864+ # then (and only then) is the last word is still an encoded word.
2865+ return _last_word_is_ew and not bool (added_str .strip (_WSP ))
2866+
2867+
28612868def _refold_parse_tree (parse_tree , * , policy ):
28622869 """Return string of contents of parse_tree folded according to RFC rules.
28632870
@@ -2961,8 +2968,7 @@ def _refold_parse_tree(parse_tree, *, policy):
29612968
29622969 if len (tstr ) <= maxlen - len (lines [- 1 ]):
29632970 lines [- 1 ] += tstr
2964- if any (char not in WSP for char in tstr ):
2965- last_word_is_ew = False
2971+ last_word_is_ew = _last_word_is_sill_ew (last_word_is_ew , tstr )
29662972 continue
29672973
29682974 # This part is too long to fit. The RFC wants us to break at
@@ -2973,8 +2979,9 @@ def _refold_parse_tree(parse_tree, *, policy):
29732979 newline = _steal_trailing_WSP_if_exists (lines )
29742980 if newline or part .startswith_fws ():
29752981 lines .append (newline + tstr )
2976- if any (char not in WSP for char in lines [- 1 ]):
2977- last_word_is_ew = False
2982+ last_word_is_ew = _last_word_is_sill_ew (
2983+ last_word_is_ew , lines [- 1 ]
2984+ )
29782985 last_ew = None
29792986 continue
29802987 if not hasattr (part , 'encode' ):
@@ -3014,8 +3021,7 @@ def _refold_parse_tree(parse_tree, *, policy):
30143021 else :
30153022 # We can't fold it onto the next line either...
30163023 lines [- 1 ] += tstr
3017- if any (char not in WSP for char in tstr ):
3018- last_word_is_ew = False
3024+ last_word_is_ew = _last_word_is_sill_ew (last_word_is_ew , tstr )
30193025
30203026 return policy .linesep .join (lines ) + policy .linesep
30213027
0 commit comments