1use std::{fmt::Write as _, ops::Range};
6
7use serde::{Deserialize, Serialize};
8
9use super::{Dialect, Marker, code, link_definitions};
10
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct Region {
15 pub target: String,
17 pub open_line: usize,
19 pub close_line: usize,
21 pub content: String,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct DefinitionBlock {
29 pub line: usize,
31 pub entries: Vec<(String, String)>,
34 pub trailing: bool,
37 pub text: String,
39}
40
41#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
43pub struct Segments {
44 pub regions: Vec<Region>,
46 pub definition: Option<DefinitionBlock>,
48 pub unclosed: Option<usize>,
50 pub stray_closes: Vec<usize>,
52}
53
54impl Segments {
55 pub fn in_region(&self, line: usize) -> bool {
57 self.regions
58 .iter()
59 .any(|i| i.open_line < line && line < i.close_line)
60 || self.unclosed.is_some_and(|open| line > open)
61 }
62
63 pub fn in_definition(&self, line: usize) -> bool {
65 self.definition.as_ref().is_some_and(|d| line >= d.line)
66 }
67
68 pub fn is_generated(&self, line: usize) -> bool {
70 self.in_region(line)
71 || self.in_definition(line)
72 || self
73 .regions
74 .iter()
75 .any(|i| i.open_line == line || i.close_line == line)
76 }
77}
78
79pub fn segments(body: &str, first_line: usize, dialect: &Dialect) -> Segments {
85 let mut out = Segments::default();
86 let lines: Vec<&str> = body.lines().collect();
87 let mut fences: Option<Vec<Range<usize>>> = None;
89 let mut open: Option<(String, usize, usize)> = None; let mut start = 0;
91 for (i, raw) in body.split_inclusive('\n').enumerate() {
92 let line = lines[i];
93 let file_line = first_line + i;
94 let at = start;
95 start += raw.len();
96 let marker = dialect.marker(line).filter(|_| {
97 let fences = fences.get_or_insert_with(|| code::fenced(body));
100 let k = fences.partition_point(|f| f.end <= at);
101 !fences.get(k).is_some_and(|f| f.contains(&at))
102 });
103 match marker {
104 Some(Marker::Open(target)) if open.is_none() => {
105 open = Some((target, file_line, i));
106 }
107 Some(Marker::Close) => match open.take() {
108 Some((target, open_line, open_index)) => {
109 let content: String =
110 lines[open_index + 1..i]
111 .iter()
112 .fold(String::new(), |mut out, l| {
113 let _ = writeln!(out, "{l}");
114 out
115 });
116 out.regions.push(Region {
117 target,
118 open_line,
119 close_line: file_line,
120 content,
121 });
122 }
123 None => out.stray_closes.push(file_line),
124 },
125 Some(Marker::Trailer) if open.is_none() => {
126 out.definition = Some(definition(&lines[i..], file_line));
127 return finish(out, open.as_ref());
128 }
129 Some(Marker::Open(_) | Marker::Trailer) | None => {}
130 }
131 }
132 finish(out, open.as_ref())
133}
134
135fn finish(mut out: Segments, open: Option<&(String, usize, usize)>) -> Segments {
136 if let Some(&(_, line, _)) = open {
137 out.unclosed = Some(line);
138 }
139 out
140}
141
142fn definition(lines: &[&str], line: usize) -> DefinitionBlock {
148 let after: Vec<&str> = lines[1..].iter().map(|l| l.trim_start()).collect();
151 let top: Vec<_> = link_definitions::read(&after)
152 .defs
153 .into_iter()
154 .filter(|d| after[d.first].starts_with('['))
155 .collect();
156 let taken = |i: usize| top.iter().any(|d| d.first <= i && i <= d.last);
159 let trailing = after
160 .iter()
161 .enumerate()
162 .any(|(i, l)| !l.trim().is_empty() && !taken(i));
163 let entries = top.into_iter().map(|d| (d.label, d.dest)).collect();
164 let text: String = lines.iter().fold(String::new(), |mut out, l| {
165 let _ = writeln!(out, "{l}");
166 out
167 });
168 DefinitionBlock {
169 line,
170 entries,
171 trailing,
172 text,
173 }
174}
175
176pub fn ref_def(line: &str) -> Option<(String, String)> {
179 let t = line.trim();
180 let rest = t.strip_prefix('[')?;
181 let end = rest.find("]:")?;
182 let label = &rest[..end];
183 if label.is_empty() || label.contains('[') {
184 return None;
185 }
186 let dest = rest[end + 2..].trim();
187 let dest = dest.split_whitespace().next()?;
188 Some((label.to_string(), dest.to_string()))
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194
195 const HOST: Dialect = Dialect {
196 namespace: "host",
197 region: Some("include"),
198 trailer: Some("links"),
199 scheme: Some("host"),
200 };
201
202 fn segments(body: &str, first_line: usize) -> Segments {
203 super::segments(body, first_line, &HOST)
204 }
205
206 #[test]
207 fn finds_includes_and_the_definition_block() {
208 let body = "intro\n\n<!-- host:include a -->\n\nbody a\n\n<!-- /host:include -->\n\n```\n<!-- host:include fenced -->\n```\n\n<!-- host:links -->\n\n[host:a]: /k/a.md\n[host:b#c]: /k/b.md#c\n";
209 let s = segments(body, 10);
210 assert_eq!(s.regions.len(), 1);
211 let inc = &s.regions[0];
212 assert_eq!(inc.target, "a");
213 assert_eq!((inc.open_line, inc.close_line), (12, 16));
214 assert_eq!(inc.content, "\nbody a\n\n");
215 let def = s.definition.clone().unwrap();
216 assert_eq!(def.line, 22);
217 assert_eq!(
218 def.entries,
219 vec![
220 ("host:a".to_string(), "/k/a.md".to_string()),
221 ("host:b#c".to_string(), "/k/b.md#c".to_string())
222 ]
223 );
224 assert!(!def.trailing);
225 assert!(def.text.starts_with("<!-- host:links -->\n"));
226 assert!(s.unclosed.is_none());
227 assert!(s.in_region(14));
228 assert!(!s.in_region(12));
229 assert!(s.in_definition(23));
230 assert!(s.is_generated(12));
231 assert!(!s.is_generated(11));
232 }
233
234 #[test]
235 fn unclosed_and_stray_markers() {
236 let s = segments(
237 "<!-- /host:include -->\n<!-- host:include a -->\nx\n<!-- host:include b -->\n",
238 1,
239 );
240 assert_eq!(s.stray_closes, vec![1]);
241 assert_eq!(s.unclosed, Some(2));
242 assert!(s.regions.is_empty(), "{:?}", s.regions);
243 assert!(s.in_region(3));
244 let s = segments(
246 "<!-- host:include a -->\n<!-- host:links -->\n<!-- /host:include -->\n",
247 1,
248 );
249 assert!(s.definition.is_none());
250 assert_eq!(s.regions.len(), 1);
251 }
252
253 #[test]
254 fn definition_block_with_trailing_content() {
255 let s = segments("x\n<!-- host:links -->\n[host:a]: /a.md\nnot a def\n", 1);
256 let def = s.definition.unwrap();
257 assert!(def.trailing);
258 assert_eq!(def.entries.len(), 1);
259 }
260
261 #[test]
267 fn a_wrapped_definition_of_the_trailer_is_one_entry() {
268 for after in [
269 "[host:a]: /k/a.md\n[host:b#c]: /k/b.md#c \"T\"\n",
270 "[host:a]:\n /k/a.md\n[host:b#c]:\n /k/b.md#c\n \"T\"\n",
271 "[host:a]: /k/a.md\n\n[host:b#c]: /k/b.md#c\n\"T\"\n",
272 " [host:a]: /k/a.md\n[host:b#c]: /k/b.md#c \"T\nU\"\n",
273 ] {
274 let s = segments(&format!("x\n\n<!-- host:links -->\n\n{after}"), 1);
275 let def = s.definition.unwrap();
276 assert!(!def.trailing, "{after:?}");
277 assert_eq!(
278 def.entries,
279 vec![
280 ("host:a".to_string(), "/k/a.md".to_string()),
281 ("host:b#c".to_string(), "/k/b.md#c".to_string())
282 ],
283 "{after:?}"
284 );
285 }
286 let s = segments("<!-- host:links -->\n[host:a]: <k a.md>\n", 1);
287 let def = s.definition.unwrap();
288 assert!(!def.trailing);
289 assert_eq!(
290 def.entries,
291 vec![("host:a".to_string(), "<k a.md>".to_string())]
292 );
293 for after in [
296 "[host:a]:\n",
297 "> [host:a]: /k/a.md\n",
298 "[host:a]: /k/a.md\n>\n",
299 "- [host:a]: /k/a.md\n",
300 "[host:a]: /k/a.md \"T\n",
301 ] {
302 let s = segments(&format!("<!-- host:links -->\n{after}"), 1);
303 assert!(s.definition.unwrap().trailing, "{after:?}");
304 }
305 }
306
307 #[test]
309 fn fences_hide_markers_including_tildes_and_longer_closers() {
310 let body = "~~~\n<!-- host:links -->\n~~~\n````md\n```\n<!-- host:include a -->\n````\n- ```\n <!-- host:include a -->\n ```\n<!-- host:links -->\n";
311 let s = segments(body, 1);
312 assert!(s.regions.is_empty(), "{:?}", s.regions);
313 assert_eq!(s.definition.unwrap().line, 11);
314 }
315
316 fn targets(body: &str) -> Vec<String> {
318 segments(body, 1)
319 .regions
320 .into_iter()
321 .map(|r| r.target)
322 .collect()
323 }
324
325 #[test]
327 fn a_fence_in_a_footnote_hides_a_marker() {
328 let body = "Text[^1].\n\n[^1]: Note.\n\n ```\n <!-- host:include a -->\n <!-- /host:include -->\n ```\n";
329 let found = targets(body);
330 assert!(found.is_empty(), "{found:?}");
331 }
332
333 #[test]
335 fn a_fence_ends_with_the_quote_or_the_item_that_holds_it() {
336 let region = "\n<!-- host:include a -->\nx\n<!-- /host:include -->\n";
337 for fence in [
338 "> - ```\n> code\n",
339 "- a\n - b\n\n > ```\n > code\n",
340 ">\t```\n>\tcode\n",
341 "- ```\n code\n",
342 ] {
343 assert_eq!(targets(&format!("{fence}{region}")), ["a"], "{fence:?}");
344 }
345 }
346
347 #[test]
349 fn only_a_fence_hides_a_marker() {
350 for text in [" ```\n", "``` a ` b\n", "``\n"] {
353 let body = format!("{text}\n<!-- host:include a -->\nx\n<!-- /host:include -->\n");
354 assert_eq!(targets(&body), ["a"], "{text:?}");
355 }
356 }
357
358 #[test]
359 fn ref_defs() {
360 assert_eq!(ref_def("[a]: /x"), Some(("a".into(), "/x".into())));
361 assert_eq!(
362 ref_def("[a]: /x \"title\""),
363 Some(("a".into(), "/x".into()))
364 );
365 assert_eq!(ref_def("[a]:"), None);
366 assert_eq!(ref_def("[]: x"), None);
367 assert_eq!(ref_def("[a][b]: x"), None);
368 assert_eq!(ref_def("text"), None);
369 }
370}