@@ -67,10 +67,71 @@ def parse
67
67
68
68
sections << section if section
69
69
70
+
71
+ ## pre-process sections
72
+ ## remove trailing empty lines
73
+ _strip_empty_leading_lines ( head )
74
+ _strip_empty_trailing_lines ( head )
75
+ _indent_code_block ( head )
76
+
77
+ sections . each do |heading , lines |
78
+ _strip_empty_leading_lines ( lines )
79
+ _strip_empty_trailing_lines ( lines )
80
+ _strip_code_block ( lines )
81
+ end
82
+
83
+
70
84
Document . new ( head , sections )
71
85
end
86
+
87
+
88
+ def _strip_code_block ( sect )
89
+ sect . reject! { |line | line . start_with? ( '```' ) }
90
+ end
91
+
92
+ def _indent_code_block ( sect )
93
+ ## step 1: indent code blocks
94
+ inside_block = false
95
+ sect . each_with_index do |line , i |
96
+ if line . start_with? ( '```' )
97
+ inside_block = !inside_block
98
+ elsif inside_block
99
+ sect [ i ] = ( ' ' *4 ) + sect [ i ]
100
+ else
101
+ ## regular line; keep going
102
+ end
103
+ end
104
+ ## step 2: remove all code block lines
105
+ _strip_code_block ( sect )
106
+ end
107
+
108
+
109
+ def _strip_empty_trailing_lines ( sect )
110
+ loop do
111
+ line = sect [ -1 ]
112
+ if line && line . empty?
113
+ sect . pop
114
+ else
115
+ break
116
+ end
117
+ end
118
+ sect
119
+ end
120
+
121
+ def _strip_empty_leading_lines ( sect )
122
+ loop do
123
+ line = sect [ 0 ]
124
+ if line && line . empty?
125
+ sect . shift
126
+ else
127
+ break
128
+ end
129
+ end
130
+ sect
131
+ end
72
132
end # class Parser
73
133
134
+
74
135
def self . read ( path )
75
136
Parser . new ( read_text ( path ) ) . parse
76
137
end
0 commit comments