1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
use std::mem;
use crate::nodes::Attributes;
#[derive(Default)]
enum Kind {
#[default]
Id,
Class,
Pair(String),
}
pub fn parse(input: &str) -> Option<(Attributes, usize)> {
let mut ci = input.char_indices();
if ci.next()?.1 != '{' {
return None;
}
enum State {
Betwixt,
Value(Kind, String, Quote),
Key(String),
PostQuote,
}
enum Quote {
Bare,
Quoted,
QuotedEscaped,
}
let mut state = State::Betwixt;
let mut attrs = Attributes::default();
// We permit ' ' | '\t' | '\r' | '\n' between/around attributes in the braces.
// Is ASCII whitespace also '\v' | '\f'? Does anyone mind?
loop {
let (i, c) = ci.next()?;
loop {
match state {
State::Betwixt => match c {
'#' => {
state = State::Value(Kind::Id, String::new(), Quote::Bare);
break;
}
'.' => {
state = State::Value(Kind::Class, String::new(), Quote::Bare);
break;
}
'a'..='z' | 'A'..='Z' => {
state = State::Key(c.to_string());
break;
}
'}' => return Some((attrs, i + 1)),
' ' | '\t' | '\r' | '\n' => break,
_ => return None,
},
State::Value(ref mut kind, ref mut value, Quote::Bare) => match c {
'"' if value.is_empty() => {
state = State::Value(mem::take(kind), mem::take(value), Quote::Quoted);
break;
}
// An id can contain [literally anything] in HTML5, just so long as it's non-empty.
// Consider looking at how Pandoc parses this part.
// Per above, classes are also literally anything, *except* ASCII whitespace.
//
// [literally anything]: https://html.spec.whatwg.org/multipage/dom.html#the-id-attribute
//
// The below range of characters selected is arbitrary. Add to it if you like.
'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | ':' | '.' | '%' => {
value.push(c);
break;
}
' ' | '\t' | '\r' | '\n' | '}' => {
if value.is_empty() {
return None;
}
parse_attribute_value(kind, value, &mut attrs);
state = State::Betwixt;
// handle in loop
}
_ => return None,
},
State::Value(ref mut kind, ref mut value, Quote::Quoted) => match c {
'"' => {
parse_attribute_value(kind, value, &mut attrs);
state = State::PostQuote;
break;
}
'\\' => {
state =
State::Value(mem::take(kind), mem::take(value), Quote::QuotedEscaped);
break;
}
_ => {
value.push(c);
break;
}
},
State::Value(ref mut kind, ref mut value, Quote::QuotedEscaped) => {
value.push(c);
state = State::Value(mem::take(kind), mem::take(value), Quote::Quoted);
break;
}
State::Key(ref mut key) => match c {
// "Except where otherwise specified, attribute values on HTML elements may be any string value,
// including the empty string, and there is no restriction on what text can be specified in such
// attribute values."
// ¯\_(ツ)_/¯ I'm not driving
'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | ':' | '.' => {
key.push(c);
break;
}
'=' => {
state =
State::Value(Kind::Pair(mem::take(key)), String::new(), Quote::Bare);
break;
}
_ => return None,
},
State::PostQuote => match c {
// Require a space after quote before anything else.
' ' | '\t' | '\r' | '\n' | '}' => {
state = State::Betwixt;
// handle in loop
}
_ => return None,
},
}
}
}
}
fn parse_attribute_value(kind: &mut Kind, value: &mut String, attrs: &mut Attributes) {
match kind {
Kind::Id => attrs.id = Some(mem::take(value)),
Kind::Class => attrs.classes.push(mem::take(value)),
Kind::Pair(key) => attrs.pairs.push((mem::take(key), mem::take(value))),
};
}
/// Use this only in contexts where there can *not* be any following text
/// and the attribute set still valid; i.e. blocks are OK, inlines are not.
pub fn parse_off(content: &mut String) -> Option<Attributes> {
let mut ci = content.char_indices().rev();
enum State {
Pre,
Within,
Quoted,
/// We've hit an opening quote, but there could be a backslash behind it;
/// if there is, return to Quoted, otherwise go to Within and reparse.
MaybeQuoteEnd,
}
let mut state = State::Pre;
let mut end = None;
loop {
let (i, c) = ci.next()?;
loop {
match state {
State::Pre => match c {
'}' => {
end = Some(i + 1);
state = State::Within;
break;
}
_ if c.is_whitespace() => break,
_ => return None,
},
State::Within => match c {
'"' => {
state = State::Quoted;
break;
}
'{' => {
let (attrs, j) = parse(&content[i..])?;
// We can't transition into Within without setting `end`.
// If these don't match up, something is Bad.
if i + j != end.unwrap() {
return None;
}
// Either there's nothing left (fine!) ORRRRR there's *at least*
// one (but possibly multiple) whitespace, which we truncate.
let Some((mut i, c)) = ci.next() else {
content.truncate(i);
return Some(attrs);
};
if !c.is_whitespace() {
return None;
}
for (i2, c) in ci {
if !c.is_whitespace() {
break;
}
i = i2;
}
content.truncate(i);
return Some(attrs);
}
_ => break,
},
State::Quoted => match c {
'"' => {
state = State::MaybeQuoteEnd;
break;
}
_ => break,
},
State::MaybeQuoteEnd => match c {
'\\' => {
state = State::Quoted;
break;
}
_ => {
state = State::Within;
// handle in loop
}
},
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fundamentals() {
assert_eq!(parse(""), None);
assert_eq!(
parse("{#henlo} there"),
Some((
Attributes {
id: Some("henlo".to_string()),
..Default::default()
},
8
))
);
assert_eq!(
parse("{.oken}"),
Some((
Attributes {
classes: vec!["oken".to_string()],
..Default::default()
},
7
))
);
assert_eq!(
parse("{data-thingy=ya}"),
Some((
Attributes {
pairs: vec![("data-thingy".to_string(), "ya".to_string())],
..Default::default()
},
16
))
);
assert_eq!(
parse("{.oken #yip m=26 .sure x=3% #yap} oh!"),
Some((
Attributes {
id: Some("yap".to_string()),
classes: vec!["oken".to_string(), "sure".to_string()],
pairs: vec![
("m".to_string(), "26".to_string()),
("x".to_string(), "3%".to_string())
]
},
33
))
);
assert_eq!(
parse("{#\"has space, will travel\" .\"ok\\\"en\" title=\"是非 \\\"not\\\"\"}"),
Some((
Attributes {
id: Some("has space, will travel".to_string()),
classes: vec!["ok\"en".to_string(),],
pairs: vec![("title".to_string(), "是非 \"not\"".to_string())],
},
60
))
);
assert_eq!(parse("{#}"), None);
assert_eq!(parse("{}"), Some((Attributes::default(), 2)));
assert_eq!(parse("{.}"), None);
assert_eq!(parse("{uh"), None);
assert_eq!(
parse("{.why\n.not}"),
Some((
Attributes {
classes: vec!["why".to_string(), "not".to_string()],
..Default::default()
},
11
))
);
// Consistent with Pandoc's commonmark+attributes.
assert_eq!(parse("{hi}"), None);
assert_eq!(parse("{hi=}"), None);
assert_eq!(
parse("{hi=\"\"}"),
Some((
Attributes {
pairs: vec![("hi".to_string(), String::new())],
..Default::default()
},
7
))
);
}
fn assert_parse_off(input: &str, expected_str: &str, expected_attrs: Option<Attributes>) {
let mut s = input.to_string();
let attrs = parse_off(&mut s);
assert_eq!(s, expected_str);
assert_eq!(attrs, expected_attrs);
}
#[test]
fn parses_off() {
assert_parse_off("hi", "hi", None);
assert_parse_off(
"hi {#yay}",
"hi",
Some(Attributes {
id: Some("yay".to_string()),
..Default::default()
}),
);
assert_parse_off("Well!{#yay}", "Well!{#yay}", None);
assert_parse_off(
"Well! {#okay} {Not really.}",
"Well! {#okay} {Not really.}",
None,
);
assert_parse_off(
"Well!! {cool=\"Lest \\\"{#confusion}\\\" sets in.\" } \t",
"Well!!",
Some(Attributes {
pairs: vec![(
"cool".to_string(),
"Lest \"{#confusion}\" sets in.".to_string(),
)],
..Default::default()
}),
);
}
}