@@ -102,31 +102,52 @@ def replace(input)
102
102
103
103
def parse_line ( line )
104
104
# 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
+ }
119
139
120
140
line
121
141
end
122
142
123
-
143
+ # match: String
124
144
def replace_matches_single ( line , match )
125
145
number = match [ /[0-9]+/ ]
126
146
short_ref = @parser . parse ( number , !@refs_used . key? ( number ) )
127
147
if not @refs_used . key? ( number )
128
148
@refs_used [ number ] = true
129
149
end
150
+ # Will always take the first match it finds
130
151
new_line = line . sub ( match ) { short_ref . strip }
131
152
132
153
other_match = new_line [ /\[ #[0-9]+\! \] / ]
@@ -207,6 +228,11 @@ def replace_matches_multiple_par(line, match)
207
228
end
208
229
end
209
230
231
+ # Reference match
232
+ # type
233
+ # string
234
+ Match = Struct . new ( :type , :match )
235
+
210
236
if __FILE__ == $0
211
237
stream = if s = ENV [ "STREAM" ]
212
238
s
0 commit comments