1use std::path::Path;
7
8pub const NOTES: &str = "Notes";
10
11pub fn split_front_matter(source: &str) -> Option<(&str, &str)> {
13 let rest = source
14 .strip_prefix("---\n")
15 .or_else(|| source.strip_prefix("---\r\n"))?;
16 let mut at = 0;
17 for line in rest.split_inclusive('\n') {
18 if line.trim_end() == "---" {
19 return Some((&rest[..at], &rest[at + line.len()..]));
20 }
21 at += line.len();
22 }
23 None
24}
25
26pub fn title(source: &str, path: &Path) -> String {
28 split_front_matter(source)
29 .map_or(source, |(_, page)| page)
30 .lines()
31 .find_map(|line| line.strip_prefix("# "))
32 .map(|heading| heading.trim().to_string())
33 .unwrap_or_else(|| {
34 path.file_stem()
35 .unwrap_or_default()
36 .to_string_lossy()
37 .into_owned()
38 })
39}
40
41#[derive(Debug, Clone, PartialEq)]
44pub struct Note {
45 pub line: usize,
46 pub text: String,
47 pub delivery: Option<String>,
48}
49
50pub fn notes(source: &str) -> Vec<Note> {
54 let code = code_ranges(source);
55 let in_code = |at: usize| code.iter().any(|r| r.contains(&at));
56 let open = format!("<{NOTES}");
57 let mut found = Vec::new();
58 let mut at = 0;
59 while let Some(offset) = source[at..].find(&open) {
60 let start = at + offset;
61 at = start + 1;
62 if in_code(start) {
63 continue;
64 }
65 let Some(tag) = parse_open(&source[start..])
66 .filter(|tag| tag.name == NOTES)
67 .or_else(|| {
68 unreadable_notes(&source[start..]).map(|len| OpenTag {
69 name: NOTES.to_string(),
70 props: "{}".to_string(),
71 len,
72 self_closing: false,
73 })
74 })
75 else {
76 continue;
77 };
78 let after_open = start + tag.len;
79 let (inner, end) = if tag.self_closing {
80 ("", after_open)
81 } else {
82 match find_close(source, after_open, NOTES, &in_code) {
83 Some((close_start, close_end)) => (&source[after_open..close_start], close_end),
84 None => (&source[after_open..], source.len()),
85 }
86 };
87 found.push(Note {
88 line: source[..start].matches('\n').count() + 1,
89 text: inner.trim().to_string(),
90 delivery: tag.string_prop("delivery"),
91 });
92 at = end;
93 }
94 found
95}
96
97pub(crate) struct OpenTag {
98 pub(crate) name: String,
99 pub(crate) props: String,
101 pub(crate) len: usize,
102 pub(crate) self_closing: bool,
103}
104
105pub(crate) const UNREADABLE_NOTES: &str =
107 "a <Notes> whose attributes can't be read: write delivery=\"…\" with no double quotes inside";
108
109pub(crate) fn unreadable_notes(text: &str) -> Option<usize> {
113 let rest = text.strip_prefix(&format!("<{NOTES}"))?;
114 if !rest.starts_with(char::is_whitespace) || parse_open(text).is_some() {
115 return None;
116 }
117 text.find('>').map(|end| end + 1)
118}
119
120impl OpenTag {
121 pub(crate) fn has_prop(&self, key: &str) -> bool {
123 self.props.contains(&format!("\"{key}\": "))
124 }
125
126 pub(crate) fn string_prop(&self, key: &str) -> Option<String> {
128 let at = self.props.find(&format!("\"{key}\": \""))? + key.len() + 4;
129 let mut strings =
130 serde_json::Deserializer::from_str(&self.props[at..]).into_iter::<String>();
131 strings.next()?.ok()
132 }
133}
134
135pub(crate) fn parse_open(text: &str) -> Option<OpenTag> {
137 let chars: Vec<(usize, char)> = text.char_indices().collect();
138 let mut i = 1;
139 let mut name = String::new();
140 while let Some(&(_, c)) = chars.get(i) {
141 if c.is_ascii_alphanumeric() {
142 name.push(c);
143 i += 1;
144 } else {
145 break;
146 }
147 }
148 let mut props = Vec::new();
149 loop {
150 while chars.get(i).is_some_and(|(_, c)| c.is_whitespace()) {
151 i += 1;
152 }
153 let &(_, c) = chars.get(i)?;
154 if c == '>' {
155 return Some(OpenTag {
156 name,
157 props: format!("{{{}}}", props.join(", ")),
158 len: chars.get(i + 1).map_or(text.len(), |(at, _)| *at),
159 self_closing: false,
160 });
161 }
162 if c == '/' && chars.get(i + 1).is_some_and(|(_, c)| *c == '>') {
163 return Some(OpenTag {
164 name,
165 props: format!("{{{}}}", props.join(", ")),
166 len: chars.get(i + 2).map_or(text.len(), |(at, _)| *at),
167 self_closing: true,
168 });
169 }
170 let mut attr = String::new();
171 while let Some(&(_, c)) = chars.get(i) {
172 if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
173 attr.push(c);
174 i += 1;
175 } else {
176 break;
177 }
178 }
179 if attr.is_empty() {
180 return None;
181 }
182 let key = serde_json::to_string(&attr).ok()?;
183 if chars.get(i).is_some_and(|(_, c)| *c == '=') {
184 i += 1;
185 match chars.get(i)?.1 {
186 quote @ ('"' | '\'') => {
187 let mut value = String::new();
188 i += 1;
189 while let Some(&(_, c)) = chars.get(i) {
190 i += 1;
191 if c == quote {
192 break;
193 }
194 value.push(c);
195 }
196 props.push(format!("{key}: {}", serde_json::to_string(&value).ok()?));
197 }
198 '{' => {
199 let mut depth = 0;
200 let mut expr = String::new();
201 let mut string: Option<char> = None;
202 while let Some(&(_, c)) = chars.get(i) {
203 i += 1;
204 if let Some(q) = string {
205 if c == q {
206 string = None;
207 }
208 } else if matches!(c, '"' | '\'' | '`') {
209 string = Some(c);
210 } else if c == '{' {
211 depth += 1;
212 if depth == 1 {
213 continue;
214 }
215 } else if c == '}' {
216 depth -= 1;
217 if depth == 0 {
218 break;
219 }
220 }
221 expr.push(c);
222 }
223 props.push(format!("{key}: ({expr})"));
224 }
225 _ => return None,
226 }
227 } else {
228 props.push(format!("{key}: true"));
229 }
230 }
231}
232
233pub(crate) fn find_close(
236 source: &str,
237 from: usize,
238 name: &str,
239 in_code: &dyn Fn(usize) -> bool,
240) -> Option<(usize, usize)> {
241 let open = format!("<{name}");
242 let close = format!("</{name}>");
243 let mut depth = 1;
244 let mut at = from;
245 loop {
246 let next_close = source[at..].find(&close).map(|o| at + o)?;
247 let next_open = source[at..]
248 .find(&open)
249 .map(|o| at + o)
250 .filter(|&o| o < next_close);
251 if let Some(o) = next_open {
252 at = o + open.len();
253 let boundary = source[at..].starts_with(|c: char| c.is_whitespace() || c == '>');
254 if !in_code(o) && boundary {
255 depth += 1;
256 }
257 continue;
258 }
259 at = next_close + close.len();
260 if in_code(next_close) {
261 continue;
262 }
263 depth -= 1;
264 if depth == 0 {
265 return Some((next_close, at));
266 }
267 }
268}
269
270pub(crate) fn code_ranges(source: &str) -> Vec<std::ops::Range<usize>> {
272 let mut ranges = Vec::new();
273 let mut fence: Option<(usize, String)> = None;
274 let mut offset = 0;
275 let mut previous_blank = true;
278 let mut in_list = false;
279 let mut indented: Option<usize> = None;
280 for line in source.split_inclusive('\n') {
281 let trimmed = line.trim_start();
282 let blank = trimmed.is_empty();
283 let is_indented = line.starts_with(" ") || line.starts_with('\t');
284 if fence.is_none() {
285 if let Some(start) = indented {
286 if !blank && !is_indented {
287 ranges.push(start..offset);
288 indented = None;
289 }
290 } else if is_indented && !blank && previous_blank && !in_list {
291 indented = Some(offset);
292 }
293 if indented.is_some() {
294 previous_blank = blank;
295 offset += line.len();
296 continue;
297 }
298 if !blank && !is_indented {
299 in_list = is_list_item(trimmed);
300 }
301 }
302 previous_blank = blank;
303 let marker: String = trimmed
304 .chars()
305 .take_while(|c| *c == '`' || *c == '~')
306 .collect();
307 match &fence {
308 Some((start, open)) => {
309 if marker.len() >= open.len() && marker.starts_with(&open[..1]) {
310 ranges.push(*start..offset + line.len());
311 fence = None;
312 }
313 }
314 None if marker.len() >= 3 => fence = Some((offset, marker)),
315 None => {
316 let mut i = 0;
318 let b = line.as_bytes();
319 while i < b.len() {
320 if b[i] == b'`' {
321 let run = b[i..].iter().take_while(|c| **c == b'`').count();
322 let ticks = "`".repeat(run);
323 if let Some(end) = line[i + run..].find(&ticks) {
324 let close = i + run + end + run;
325 ranges.push(offset + i..offset + close);
326 i = close;
327 continue;
328 }
329 i += run;
330 } else {
331 i += 1;
332 }
333 }
334 }
335 }
336 offset += line.len();
337 }
338 if let Some((start, _)) = fence {
339 ranges.push(start..source.len());
340 }
341 if let Some(start) = indented {
342 ranges.push(start..source.len());
343 }
344 let mut from = 0;
346 while let Some(open) = source[from..].find("<!--") {
347 let open = from + open;
348 if ranges.iter().any(|r| r.contains(&open)) {
349 from = open + 4;
350 continue;
351 }
352 let close = source[open + 4..]
353 .find("-->")
354 .map_or(source.len(), |end| open + 4 + end + 3);
355 ranges.push(open..close);
356 from = close;
357 }
358 ranges.sort_by_key(|r| r.start);
359 ranges
360}
361
362pub(crate) fn is_list_item(trimmed: &str) -> bool {
364 let bullet =
365 trimmed.starts_with("- ") || trimmed.starts_with("* ") || trimmed.starts_with("+ ");
366 let digits = trimmed.chars().take_while(|c| c.is_ascii_digit()).count();
367 bullet || (digits > 0 && matches!(trimmed[digits..].chars().next(), Some('.' | ')')))
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373
374 #[test]
375 fn notes_keep_their_text_without_its_indentation() {
376 let source = "# Title\n\n<Notes>\n Say **this**, word for word.\n</Notes>\n\nAfter.\n";
377 assert_eq!(
378 notes(source),
379 vec![Note {
380 line: 3,
381 text: "Say **this**, word for word.".to_string(),
382 delivery: None
383 }]
384 );
385 }
386
387 #[test]
388 fn unclosed_notes_run_to_the_end_of_the_page() {
389 let source = "# Title\n\nShown.\n\n<Notes>\nSay this.\n</Note>\n\nAfter.\n";
390 assert_eq!(
391 notes(source)[0].text,
392 "Say this.\n</Note>\n\nAfter.".to_string()
393 );
394 }
395
396 #[test]
397 fn a_notes_delivery_is_kept() {
398 let source = "<Notes delivery=\"Honest and a little teasing: you caught them.\">\nSay this.\n</Notes>\n";
399 assert_eq!(
400 notes(source)[0].delivery.as_deref(),
401 Some("Honest and a little teasing: you caught them.")
402 );
403 }
404
405 #[test]
406 fn a_notes_with_unreadable_attributes_keeps_its_text_and_no_delivery() {
407 for source in [
408 "<Notes delivery=\"the \"aha\" moment\">\nSAYTHIS\n</Notes>\n\nAfter.\n",
409 "<Notes delivery=\"say \\\"wow\\\" now\">\nSAYTHIS\n</Notes>\n\nAfter.\n",
410 "<Notes delivery={\"warm\"}>\nSAYTHIS\n</Notes>\n",
411 ] {
412 assert_eq!(notes(source)[0].text, "SAYTHIS");
413 assert_eq!(notes(source)[0].delivery, None);
414 }
415 }
416
417 #[test]
418 fn notes_inside_code_and_comments_are_not_notes() {
419 let source = "`<Notes>x</Notes>`\n\n```\n<Notes>fenced</Notes>\n```\n\n <Notes>indented</Notes>\n\n<!-- <Notes>hidden</Notes> -->\n";
420 assert!(notes(source).is_empty(), "{:?}", notes(source));
421 }
422
423 #[test]
424 fn every_notes_block_is_found_with_its_line() {
425 let found = notes("<Notes>one</Notes>\n\ntext\n\n<Notes>\ntwo\n</Notes>\n<Notes/>\n");
426 let found: Vec<(usize, String)> = found.into_iter().map(|n| (n.line, n.text)).collect();
427 assert_eq!(
428 found,
429 vec![
430 (1, "one".to_string()),
431 (5, "two".to_string()),
432 (8, String::new())
433 ]
434 );
435 }
436}