@@ -23,24 +23,28 @@ function block(str::AbstractString, block_scalar::AbstractString="")
23
23
DEFAULT_STYLE, DEFAULT_CHOMP
24
24
end
25
25
26
+ # Append an additional character to force one more iteration of the style loop
27
+ str *= ' \0 '
28
+
26
29
out = IOBuffer ()
27
- num_newlines = 0
30
+ num_newlines = 0 # The number of newlines at the end of the string
31
+ prev = curr = ' \0 '
28
32
33
+ # Replace newlines with spaces (folded)
29
34
if style == ' f'
30
35
# The code below is equivalent to these two regexes:
31
36
# ```
32
37
# str = replace(str, r"(?<=\S)\n(?=\S)" => " ")
33
38
# str = replace(str, r"(?<=\n)\n(?=\S)" => "")
34
39
# ```
35
40
36
- prev = curr = ' \0 '
37
41
for next in str
38
-
39
42
if curr == ' \n '
40
43
if ! isspace (next)
41
44
if prev == ' \n '
42
- # Skip
45
+ # Skip last newline in a sequence of sequential blank lines
43
46
elseif ! isspace (prev)
47
+ # Replace a single newline with a space
44
48
write (out, ' ' )
45
49
else
46
50
num_newlines += 1
@@ -49,6 +53,7 @@ function block(str::AbstractString, block_scalar::AbstractString="")
49
53
num_newlines += 1
50
54
end
51
55
elseif curr != ' \0 '
56
+ # Insert newlines which were determined to not be at the end of the string
52
57
if num_newlines > 0
53
58
write (out, " \n " ^ num_newlines)
54
59
num_newlines = 0
@@ -61,22 +66,13 @@ function block(str::AbstractString, block_scalar::AbstractString="")
61
66
curr = next
62
67
end
63
68
64
- if curr == ' \n '
65
- num_newlines += 1
66
- elseif curr != ' \0 '
67
- if num_newlines > 0
68
- write (out, " \n " ^ num_newlines)
69
- num_newlines = 0
70
- end
71
-
72
- write (out, curr)
73
- end
69
+ # Keep newlines (literal)
74
70
elseif style == ' l'
75
- curr = ' \0 '
76
71
for next in str
77
72
if curr == ' \n '
78
73
num_newlines += 1
79
74
elseif curr != ' \0 '
75
+ # Insert newlines which were determined to not be at the end of the string
80
76
if num_newlines > 0
81
77
write (out, " \n " ^ num_newlines)
82
78
num_newlines = 0
@@ -87,26 +83,22 @@ function block(str::AbstractString, block_scalar::AbstractString="")
87
83
88
84
curr = next
89
85
end
90
-
91
- if curr == ' \n '
92
- num_newlines += 1
93
- elseif curr != ' \0 '
94
- if num_newlines > 0
95
- write (out, " \n " ^ num_newlines)
96
- num_newlines = 0
97
- end
98
-
99
- write (out, curr)
100
- end
101
86
else
102
87
throw (ArgumentError (" Unknown block style indicator: $(repr (style)) " ))
103
88
end
104
89
90
+ # Single newline at end (clip)
105
91
if chomp == ' c'
106
92
num_newlines > 0 && write (out, ' \n ' )
93
+
94
+ # No newline at end (strip)
95
+ elseif chomp == ' s'
96
+ # no-op
97
+
98
+ # All newlines from end (keep)
107
99
elseif chomp == ' k'
108
100
write (out, " \n " ^ num_newlines)
109
- elseif chomp != ' s '
101
+ else
110
102
throw (ArgumentError (" Unknown block chomping indicator: $(repr (chomp)) " ))
111
103
end
112
104
0 commit comments