@@ -28,20 +28,8 @@ function safe(context, input, config) {
28
28
expression = patternCompile ( pattern )
29
29
30
30
while ( ( match = expression . exec ( value ) ) ) {
31
- // Often, patterns which depend on a character before or after it, such
32
- // as `!` when followed by `[` (for an image), do not have to be escaped
33
- // when the other character has to be escaped as well.
34
- // But in the case of a backslash, such as `\` when followed by `*`, that
35
- // is not correct: both have to be escaped.
36
- // This is a naïve “fix” for that though, but this seems the simplest for
37
- // now.
38
- if ( pattern . collapse === false ) {
39
- before = false
40
- after = false
41
- } else {
42
- before = 'before' in pattern || pattern . atBreak
43
- after = 'after' in pattern
44
- }
31
+ before = 'before' in pattern || pattern . atBreak
32
+ after = 'after' in pattern
45
33
46
34
position = match . index + ( before ? match [ 1 ] . length : 0 )
47
35
@@ -91,7 +79,10 @@ function safe(context, input, config) {
91
79
}
92
80
93
81
if ( start !== position ) {
94
- result . push ( value . slice ( start , position ) )
82
+ // If we have to use a character reference, an ampersand would be more
83
+ // correct, but as backslashes only care about punctuation, either will
84
+ // do the trick
85
+ result . push ( escapeBackslashes ( value . slice ( start , position ) , '\\' ) )
95
86
}
96
87
97
88
start = position
@@ -111,11 +102,38 @@ function safe(context, input, config) {
111
102
}
112
103
}
113
104
114
- result . push ( value . slice ( start , end ) )
105
+ result . push ( escapeBackslashes ( value . slice ( start , end ) , config . after ) )
115
106
116
107
return result . join ( '' )
117
108
}
118
109
119
110
function numerical ( a , b ) {
120
111
return a - b
121
112
}
113
+
114
+ function escapeBackslashes ( value , after ) {
115
+ var expression = / \\ (? = [ ! - / : - @ [ - ` { - ~ ] ) / g
116
+ var positions = [ ]
117
+ var results = [ ]
118
+ var index = - 1
119
+ var start = 0
120
+ var whole = value + after
121
+ var match
122
+
123
+ while ( ( match = expression . exec ( whole ) ) ) {
124
+ positions . push ( match . index )
125
+ }
126
+
127
+ while ( ++ index < positions . length ) {
128
+ if ( start !== positions [ index ] ) {
129
+ results . push ( value . slice ( start , positions [ index ] ) )
130
+ }
131
+
132
+ results . push ( '\\' )
133
+ start = positions [ index ]
134
+ }
135
+
136
+ results . push ( value . slice ( start ) )
137
+
138
+ return results . join ( '' )
139
+ }
0 commit comments