Skip to content

Commit 52adef8

Browse files
authored
Merge pull request #1 from Jomy10/fix_parse_line
refst now executes sorted
2 parents 2844a92 + 9f74655 commit 52adef8

File tree

1 file changed

+41
-15
lines changed

1 file changed

+41
-15
lines changed

template-engine/src/engine.rb

Lines changed: 41 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -102,31 +102,52 @@ def replace(input)
102102

103103
def parse_line(line)
104104
# Match all patterns
105-
# It's highly unlikely that the same referene will be cited more than once in one line,
106-
# but it's not 0. This does NOT account for that!
107-
if match = line[/\[#[0-9]+\!\]/]
108-
line = replace_matches_single(line, match)
109-
end
110-
if match = line[/\[#[0-9]+\]/]
111-
line = replace_matches_single_par(line, match)
112-
end
113-
if match = line[/\[#([0-9]+&)+[0-9]+\!\]/]
114-
line = replace_matches_multiple(line, match)
115-
end
116-
if match = line[/\[#([0-9]+&)+[0-9]+\]/]
117-
line = replace_matches_multiple_par(line, match)
118-
end
105+
matches = Hash.new
106+
line.gsub(/\[#[0-9]+\!\]/) {
107+
match = Regexp.last_match
108+
s = match.to_a[0]
109+
matches[Regexp.last_match.offset(0).first] = Match.new(:single_def, s)
110+
}
111+
line.gsub(/\[#[0-9]+\]/) {
112+
match = Regexp.last_match
113+
s = match.to_a[0]
114+
matches[Regexp.last_match.offset(0).first] = Match.new(:single_par, s)
115+
}
116+
line.gsub(/\[#([0-9]+&)+[0-9]+\!\]/) {
117+
match = Regexp.last_match
118+
s = match.to_a[0]
119+
matches[Regexp.last_match.offset(0).first] = Match.new(:multiple_def, s)
120+
}
121+
line.gsub(/\[#([0-9]+&)+[0-9]+\]/) {
122+
match = Regexp.last_match
123+
s = match.to_a[0]
124+
matches[Regexp.last_match.offset(0).first] = Match.new(:multiple_par, s)
125+
}
126+
# Sort matches and replace match for each
127+
matches.sort_by { |key, _| key }.each { |_, value|
128+
case value.type
129+
when :single_def
130+
line = replace_matches_single(line, value.match)
131+
when :single_par
132+
line = replace_matches_single_par(line, value.match)
133+
when :multiple_def
134+
line = replace_matches_multiple(line, value.match)
135+
when :multiple_par
136+
line = replace_matches_multiple_par(line, value.match)
137+
end
138+
}
119139

120140
line
121141
end
122142

123-
143+
# match: String
124144
def replace_matches_single(line, match)
125145
number = match[/[0-9]+/]
126146
short_ref = @parser.parse(number, !@refs_used.key?(number))
127147
if not @refs_used.key?(number)
128148
@refs_used[number] = true
129149
end
150+
# Will always take the first match it finds
130151
new_line = line.sub(match) { short_ref.strip }
131152

132153
other_match = new_line[/\[#[0-9]+\!\]/]
@@ -207,6 +228,11 @@ def replace_matches_multiple_par(line, match)
207228
end
208229
end
209230

231+
# Reference match
232+
# type
233+
# string
234+
Match = Struct.new(:type, :match)
235+
210236
if __FILE__ == $0
211237
stream = if s = ENV["STREAM"]
212238
s

0 commit comments

Comments
 (0)