1use std::ops::Range;
9
10use comrak::{Arena, nodes::NodeValue};
11use serde::{Deserialize, Serialize};
12
13use super::parse;
14
15const LEAD: &str = "\u{E000} ";
20
21#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Reading {
28 pub text: String,
30 pub map: Vec<usize>,
34}
35impl Reading {
38 pub fn written(text: &str) -> Reading {
41 Reading {
42 text: text.to_string(),
43 map: (0..=text.len()).collect(),
44 }
45 }
46
47 pub fn or_written<'a>(&'a self, text: &str) -> std::borrow::Cow<'a, Reading> {
51 if self.map.is_empty() {
52 std::borrow::Cow::Owned(Reading::written(text))
53 } else {
54 std::borrow::Cow::Borrowed(self)
55 }
56 }
57
58 pub fn original(&self, i: usize) -> usize {
60 self.map
61 .get(i)
62 .or(self.map.last())
63 .copied()
64 .unwrap_or_default()
65 }
66
67 pub(crate) fn drops_backslash(&self, text: &str, at: usize) -> bool {
70 text.as_bytes().get(at) == Some(&b'\\') && self.map.binary_search(&at).is_err()
71 }
72
73 pub(crate) fn span_of(&self, text: &str, start: usize, end: usize) -> Range<usize> {
80 let start = if start > 0 && self.drops_backslash(text, start - 1) {
81 start - 1
82 } else {
83 start
84 };
85 let end = if end > start && self.drops_backslash(text, end - 1) {
86 end - 1
87 } else {
88 end
89 };
90 start..end.max(start)
91 }
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
98pub(crate) struct Change {
99 pub range: Range<usize>,
101 pub with: String,
103}
104
105pub fn reading(text: &str) -> Reading {
111 apply(text, &changes(text))
112}
113
114pub fn plain_text(text: &str) -> String {
119 if !text.bytes().any(|b| b"*_`\\[]<>&!".contains(&b)) {
121 return text.to_string();
122 }
123 let arena = Arena::new();
124 let root = comrak::parse_document(&arena, &lead(text), &parse::options());
125 let collected = root.collect_text();
126 let plain = collected.strip_prefix('\u{E000}').unwrap_or(&collected);
127 plain.strip_prefix(' ').unwrap_or(plain).to_string()
128}
129
130fn lead(text: &str) -> String {
134 format!("{LEAD}{}", text.replace(['\n', '\r'], " "))
135}
136
137pub(crate) fn changes(text: &str) -> Vec<Change> {
148 if !text
149 .bytes()
150 .any(|b| matches!(b, b'*' | b'_' | b'`' | b'\\'))
151 {
152 return Vec::new();
153 }
154 let source = lead(text);
155 let (in_word, respellings, escapes) = proposed(text, &source);
156 if respellings.is_empty() && escapes.is_empty() {
157 return in_word;
158 }
159 let options = parse::options();
160 let html = |changes: &[Change]| {
161 let mut sorted = changes.to_vec();
162 sorted.sort_by_key(|c| c.range.start);
163 comrak::markdown_to_html(&lead(&apply(text, &sorted).text), &options)
164 };
165 let meaning = comrak::markdown_to_html(&source, &options);
166 let mut kept: Vec<Change> = Vec::new();
167 let all: Vec<Change> = respellings.iter().flatten().cloned().collect();
170 if !respellings.is_empty() && html(&all) == meaning {
171 kept = all;
172 } else {
173 for node in respellings {
174 let with: Vec<Change> = kept.iter().chain(&node).cloned().collect();
175 if html(&with) == meaning {
176 kept = with;
177 }
178 }
179 }
180 for at in escapes {
181 let mut with = kept.clone();
182 with.push(Change {
183 range: at..at + 1,
184 with: String::new(),
185 });
186 if html(&with) == meaning {
187 kept = with;
188 }
189 }
190 kept.extend(in_word);
193 kept.sort_by_key(|c| c.range.start);
194 kept
195}
196
197fn proposed(text: &str, source: &str) -> (Vec<Change>, Vec<Vec<Change>>, Vec<usize>) {
203 let flat = &source[LEAD.len()..];
206 let arena = Arena::new();
207 let root = comrak::parse_document(&arena, source, &parse::options());
208 let mut in_word = Vec::new();
209 let mut respellings = Vec::new();
210 let mut escapes = Vec::new();
211 for node in root.descendants() {
212 let ast = node.data();
213 let sp = ast.sourcepos;
214 if sp.start.line != 1 || sp.end.line != 1 || sp.start.column <= LEAD.len() {
217 continue;
218 }
219 let span = sp.start.column - 1 - LEAD.len()..sp.end.column.saturating_sub(LEAD.len());
220 if span.end > text.len() || span.start >= span.end {
221 continue;
222 }
223 let mut node = Vec::new();
224 match &ast.value {
225 NodeValue::Emph(_) => delimiters(flat, &span, 1, "_", &mut node),
226 NodeValue::Strong(_) => delimiters(flat, &span, 2, "**", &mut node),
227 NodeValue::Code(_) => code(flat, &span, &mut node),
228 NodeValue::Escaped
231 if text.as_bytes()[span.start] == b'\\'
232 && text.as_bytes().get(span.start + 1) != Some(&b'|') =>
233 {
234 escapes.push(span.start);
235 }
236 _ => {}
237 }
238 if node.is_empty() {
239 continue;
240 }
241 if matches!(ast.value, NodeValue::Emph(_)) && inside_word(flat, &span) {
242 in_word.extend(node);
243 } else {
244 respellings.push(node);
245 }
246 }
247 in_word.sort_by_key(|c: &Change| c.range.start);
250 escapes.sort_unstable();
251 (in_word, respellings, escapes)
252}
253
254fn inside_word(text: &str, span: &Range<usize>) -> bool {
261 let word = |c: char| c.is_alphanumeric() || ('\u{E000}'..='\u{F8FF}').contains(&c);
265 let before = text[..span.start].chars().next_back();
266 let after = text[span.end..].chars().next();
267 before.is_some_and(word) || after.is_some_and(word)
268}
269
270fn delimiters(text: &str, span: &Range<usize>, n: usize, with: &str, out: &mut Vec<Change>) {
273 let bytes = text.as_bytes();
274 let delimiter = |r: Range<usize>| bytes[r].iter().all(|b| matches!(b, b'*' | b'_'));
275 if span.len() < 2 * n
276 || !delimiter(span.start..span.start + n)
277 || !delimiter(span.end - n..span.end)
278 {
279 return;
280 }
281 for range in [span.start..span.start + n, span.end - n..span.end] {
282 if &text[range.clone()] != with {
283 out.push(Change {
284 range,
285 with: with.to_string(),
286 });
287 }
288 }
289}
290
291fn code(text: &str, span: &Range<usize>, out: &mut Vec<Change>) {
298 let written = &text[span.clone()];
299 let n = written.bytes().take_while(|&b| b == b'`').count();
300 if n == 0
301 || written.len() < 2 * n + 1
302 || !written[written.len() - n..].bytes().all(|b| b == b'`')
303 {
304 return;
305 }
306 let content = &written[n..written.len() - n];
307 let stripped = content.len() >= 2
308 && content.starts_with(' ')
309 && content.ends_with(' ')
310 && content.bytes().any(|b| b != b' ');
311 let inner = if stripped {
312 &content[1..content.len() - 1]
313 } else {
314 content
315 };
316 let (m, pad) = crate::text::code_fence(inner);
317 let ticks = "`".repeat(m);
318 let space = if pad { " " } else { "" };
319 let strip = usize::from(stripped);
320 let open = span.start..span.start + n + strip;
321 let close = span.end - n - strip..span.end;
322 for (range, with) in [
323 (open, format!("{ticks}{space}")),
324 (close, format!("{space}{ticks}")),
325 ] {
326 if text[range.clone()] != with {
327 out.push(Change { range, with });
328 }
329 }
330}
331
332pub(crate) fn apply(text: &str, changes: &[Change]) -> Reading {
335 let mut out = String::with_capacity(text.len());
336 let mut map = Vec::with_capacity(text.len() + 1);
337 let mut at = 0;
338 for c in changes {
339 if c.range.start < at || c.range.end > text.len() {
340 continue;
341 }
342 out.push_str(&text[at..c.range.start]);
343 map.extend(at..c.range.start);
344 out.push_str(&c.with);
345 let last = c.range.end.saturating_sub(1).max(c.range.start);
346 map.extend((0..c.with.len()).map(|k| (c.range.start + k).min(last)));
347 at = c.range.end;
348 }
349 out.push_str(&text[at..]);
350 map.extend(at..=text.len());
351 Reading { text: out, map }
352}
353
354#[cfg(test)]
355mod tests {
356 use proptest::prelude::*;
357
358 use super::*;
359
360 fn read(text: &str) -> String {
362 reading(text).text
363 }
364
365 #[test]
367 fn emphasis_reads_in_the_fixed_spelling() {
368 assert_eq!(read("*x* and _x_"), "_x_ and _x_");
369 assert_eq!(read("__x__ and **x**"), "**x** and **x**");
370 assert_eq!(read("foo*bar*baz"), "foo_bar_baz");
371 assert_eq!(read("***x*** and **_y_**"), "_**x**_ and **_y_**");
372 assert_eq!(read("a * b and 2*3"), "a * b and 2*3");
373 assert_eq!(read("snake_case_name"), "snake_case_name");
374 assert_eq!(read("Use *the* tool"), "Use _the_ tool");
375 assert_eq!(read("Ünï *x* é"), "Ünï _x_ é");
376 assert_eq!(read("a*b *c*d*"), "a_b _c_d_");
379 assert_eq!(read("a*b *c*d* snake\\_case"), "a_b _c_d_ snake_case");
380 assert_eq!(read("a*x*__y__"), read("a*x***y**"));
381 assert_eq!(read("“*_init_*”"), "“*_init_*”");
384 assert_eq!(read("“*x*” and —*y*—"), "“_x_” and —_y_—");
385 }
386
387 #[test]
390 fn a_code_span_reads_in_its_shortest_backticks() {
391 assert_eq!(read("``#user``"), "`#user`");
392 assert_eq!(read("` | `"), "`|`");
393 assert_eq!(read("`` ` ``"), "`` ` ``");
394 assert_eq!(read("`` `x` ``"), "`` `x` ``");
395 assert_eq!(read("` two `"), "` two `");
396 assert_eq!(read("``x`y``"), "``x`y``");
397 assert_eq!(read("`*x*` and `snake\\_case`"), "`*x*` and `snake\\_case`");
398 assert_eq!(read("` `"), "` `");
399 assert_eq!(read("``\nfoo\n``"), "`foo`");
402 }
403
404 #[test]
406 fn an_escape_reads_as_the_character_where_it_changes_nothing() {
407 assert_eq!(read("snake\\_case"), "snake_case");
408 assert_eq!(read("a \\* b"), "a * b");
409 assert_eq!(read("\\*x\\*"), "*x\\*");
410 assert_eq!(read("*x\\*"), "*x\\*");
411 assert_eq!(read("\\[x]"), "\\[x]");
412 assert_eq!(read("1\\. two"), "1. two");
413 assert_eq!(read("a \\\\ b"), "a \\ b");
414 assert_eq!(read("a\\|b"), "a\\|b");
415 }
416
417 #[test]
419 fn a_link_reads_its_text_and_keeps_its_destination() {
420 assert_eq!(read("[*the* guide](u_v)"), "[_the_ guide](u_v)");
421 assert_eq!(read("[*a*](u) and "), "[_a_](u) and ");
422 assert_eq!(read("<b>*h*</b>"), "<b>_h_</b>");
423 assert_eq!(read("[x](<a b> 'T')"), "[x](<a b> 'T')");
424 }
425
426 #[test]
427 fn a_reading_maps_each_byte_to_the_text() {
428 let r = reading("a \\_ ``b``");
429 assert_eq!(r.text, "a _ `b`");
430 assert_eq!(r.map, vec![0, 1, 3, 4, 5, 7, 8, 10]);
431 assert_eq!(reading("plain").map, vec![0, 1, 2, 3, 4, 5]);
432 }
433
434 #[test]
435 fn the_plain_text_drops_the_markers() {
436 assert_eq!(plain_text("Title *x*"), "Title x");
437 assert_eq!(plain_text("See [the guide](x)"), "See the guide");
438 assert_eq!(plain_text("What's `this`? (v2)"), "What's this? (v2)");
439 assert_eq!(plain_text("_Short_"), "Short");
440 assert_eq!(plain_text("1. Intro"), "1. Intro");
441 assert_eq!(plain_text("CLI-1_AC-2"), "CLI-1_AC-2");
442 assert_eq!(plain_text(""), "");
443 }
444
445 proptest! {
446 #![proptest_config(ProptestConfig::with_cases(256))]
447
448 #[test]
451 fn a_reading_maps_in_order(text in "[ a-c*_`\\\\\\[\\]]{0,16}") {
452 let r = reading(&text);
453 prop_assert!(r.text.len() <= text.len());
454 prop_assert_eq!(r.map.len(), r.text.len() + 1);
455 prop_assert!(r.map.windows(2).all(|w| w[0] < w[1] || w[1] == text.len()));
456 prop_assert_eq!(*r.map.last().unwrap(), text.len());
457 }
458 }
459}