108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
|
# File 'lib/latexmath/aggregator.rb', line 108
def environment(token, tokens)
env = if token.start_with?(LATEX_BEGIN)
token[7..-2]
else
token[1..token.size]
end
alignment = nil
content = []
row = []
has_rowline = false
loop do
begin
token = next_item_or_group(tokens)
raise StopIteration if token.nil?
if token.is_a? Array
begin
if env == 'array' && token.all? { |x| 'lcr|'.include?(x) }
alignment = token
else
row << process_row(token)
end
rescue TypeError
row << token
end
elsif token == "\\end{#{env}}"
break
elsif token == AMPERSAND
row << token
elsif token == BACKSLASH
row = group_columns(row) if row.include?(AMPERSAND)
row.insert(0, LATEX_HLINE) if has_rowline
content << row
row = []
has_rowline = false
elsif token == LATEX_HLINE
has_rowline = true
elsif token == OPENING_BRACKET && content.empty?
begin
alignment = group(tokens, opening: OPENING_BRACKET, closing: CLOSING_BRACKET)
rescue EmptyGroupError
next
end
elsif token == DASH
next_token = tokens.shift
raise StopIteration if next_token.nil?
row << if next_token == "\\end{#{env}}"
token
else
[token, next_token]
end
elsif SUB_SUP.include?(token)
row = process_sub_sup(row, token, tokens)
elsif token.start_with?(LATEX_BEGIN)
row += environment(token, tokens)
else
row << token
end
rescue EmptyGroupError
row << []
next
rescue StopIteration
break
end
end
if row.any?
row = group_columns(row) if row.include?(AMPERSAND)
row.insert(0, LATEX_HLINE) if has_rowline
content << row
end
content = content.pop while content.size == 1 && content.first.is_a?(Array)
return ["\\#{env}", alignment.join, content] if alignment
["\\#{env}", content]
end
|