silcrow 0.2.1

Deterministic CLI for a citable, checkable graph of laws in a git tree.
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! The markdown packet shows a changed law or clause on the structure its note writes: its
//! words, the rows of its tables, the items of its lists and each fenced block. Silcrow models
//! no language, so a fence, a mermaid diagram included, is shown as text before and after.

use super::aligned_lines;
use super::review::fence;

/// One step of a pairing of two sequences, a removed item beside an added one read as changed.
enum Step {
    Same(String),
    Changed(String, String),
    Gone(String),
    Came(String),
}

fn steps(old: &[String], new: &[String]) -> Vec<Step> {
    let mut out = Vec::new();
    let mut gone: Vec<String> = Vec::new();
    let mut came: Vec<String> = Vec::new();
    let flush = |gone: &mut Vec<String>, came: &mut Vec<String>, out: &mut Vec<Step>| {
        let mut came_all = came.drain(..);
        for old in gone.drain(..) {
            out.push(match came_all.next() {
                Some(new) => Step::Changed(old, new),
                None => Step::Gone(old),
            });
        }
        out.extend(came_all.map(Step::Came));
    };
    for line in aligned_lines(old, new) {
        let (sign, rest) = line.split_at(1);
        match sign {
            "-" => gone.push(rest.to_string()),
            "+" => came.push(rest.to_string()),
            _ => {
                flush(&mut gone, &mut came, &mut out);
                out.push(Step::Same(rest.to_string()));
            }
        }
    }
    flush(&mut gone, &mut came, &mut out);
    out
}

/// The words of `text`, a code span kept whole so a mark never lands inside one.
fn words(text: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut word = String::new();
    let mut ticks = 0;
    let chars: Vec<char> = text.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c == '`' {
            let run = chars[i..].iter().take_while(|&&c| c == '`').count();
            word.extend(&chars[i..i + run]);
            i += run;
            ticks = match ticks {
                0 => run,
                open if open == run => 0,
                open => open,
            };
            continue;
        }
        if c.is_whitespace() && ticks == 0 {
            if !word.is_empty() {
                out.push(std::mem::take(&mut word));
            }
        } else {
            word.push(c);
        }
        i += 1;
    }
    if !word.is_empty() {
        out.push(word);
    }
    out
}

/// `text` struck once: a text already struck whole keeps its one strike, since four tildes
/// at the start of a line open a code fence.
fn struck(text: &str) -> String {
    match text.strip_prefix("~~").and_then(|t| t.strip_suffix("~~")) {
        Some(inner) if !inner.is_empty() && !inner.contains("~~") => text.to_string(),
        _ => format!("~~{text}~~"),
    }
}

/// `text` without a strike around its first line: a struck law or clause reads as its words,
/// which the view strikes once where they go.
fn unstruck(text: &str) -> String {
    let first = text.lines().next().unwrap_or("");
    let inner = first
        .strip_prefix("~~")
        .and_then(|t| t.strip_suffix("~~"))
        .filter(|inner| !inner.is_empty() && !inner.contains("~~"));
    match inner {
        Some(inner) => format!("{inner}{}", &text[first.len()..]),
        None => text.to_string(),
    }
}

/// `new` with each changed run of words written `~~old~~ **new**`.
fn marked_words(old: &str, new: &str) -> String {
    // § t0jfkh0n1.b@cn2zj
    let mut out: Vec<String> = Vec::new();
    let mut gone: Vec<String> = Vec::new();
    let mut came: Vec<String> = Vec::new();
    let flush = |gone: &mut Vec<String>, came: &mut Vec<String>, out: &mut Vec<String>| {
        if !gone.is_empty() {
            out.push(struck(&gone.join(" ")));
            gone.clear();
        }
        if !came.is_empty() {
            out.push(format!("**{}**", came.join(" ")));
            came.clear();
        }
    };
    for line in aligned_lines(&words(old), &words(new)) {
        let (sign, rest) = line.split_at(1);
        match sign {
            "-" => gone.push(rest.to_string()),
            "+" => came.push(rest.to_string()),
            _ => {
                flush(&mut gone, &mut came, &mut out);
                out.push(rest.to_string());
            }
        }
    }
    flush(&mut gone, &mut came, &mut out);
    out.join(" ")
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
    Text,
    Table,
    List,
    Fence,
}

impl Kind {
    fn key(self) -> &'static str {
        match self {
            Kind::Text => "text",
            Kind::Table => "table",
            Kind::List => "list",
            Kind::Fence => "fence",
        }
    }
}

struct Block {
    kind: Kind,
    lines: Vec<String>,
}

fn fence_open(line: &str) -> Option<(char, usize)> {
    let trimmed = line.trim_start();
    let c = trimmed.chars().next().filter(|&c| c == '`' || c == '~')?;
    let run = trimmed.chars().take_while(|&x| x == c).count();
    (run >= 3).then_some((c, run))
}

fn is_item(line: &str) -> bool {
    let trimmed = line.trim_start();
    if ["- ", "* ", "+ "].iter().any(|b| trimmed.starts_with(b)) {
        return true;
    }
    let digits = trimmed.chars().take_while(char::is_ascii_digit).count();
    digits > 0
        && [". ", ") "]
            .iter()
            .any(|b| trimmed[digits..].starts_with(b))
}

/// The blocks of `text` in order: paragraphs, tables, lists and fences.
fn blocks(text: &str) -> Vec<Block> {
    let mut out: Vec<Block> = Vec::new();
    let mut open: Option<(char, usize)> = None;
    let mut joined = true;
    for line in text.lines() {
        if let Some((c, run)) = open {
            out.last_mut()
                .expect("a fence is open")
                .lines
                .push(line.to_string());
            let trimmed = line.trim();
            if trimmed.chars().all(|x| x == c) && trimmed.len() >= run {
                open = None;
                joined = false;
            }
            continue;
        }
        if line.trim().is_empty() {
            joined = false;
            continue;
        }
        let kind = if let Some(fence) = fence_open(line) {
            open = Some(fence);
            Kind::Fence
        } else if line.trim_start().starts_with('|') {
            Kind::Table
        } else if is_item(line) {
            Kind::List
        } else if joined && out.last().is_some_and(|b| b.kind == Kind::List) {
            // An unmarked line right under an item continues that item.
            Kind::List
        } else {
            Kind::Text
        };
        match out.last_mut() {
            Some(last) if joined && last.kind == kind && kind != Kind::Fence => {
                last.lines.push(line.to_string());
            }
            _ => out.push(Block {
                kind,
                lines: vec![line.to_string()],
            }),
        }
        joined = open.is_none();
    }
    out
}

/// A text that did not change, each block apart so a table or a fence after a sentence still
/// reads as one.
pub(super) fn plain(text: &str) -> String {
    let shown: Vec<String> = blocks(text).iter().map(|b| b.lines.join("\n")).collect();
    shown.join("\n\n")
}

/// The structured view of a law or clause text that changed between `old` and `new`.
pub(super) fn view(old: Option<&str>, new: Option<&str>) -> String {
    let side = |text: Option<&str>| blocks(&unstruck(text.unwrap_or("")));
    let (old, new) = (side(old), side(new));
    let keys = |blocks: &[Block]| -> Vec<String> {
        blocks.iter().map(|b| b.kind.key().to_string()).collect()
    };
    let (mut at_old, mut at_new) = (0, 0);
    let mut out = String::new();
    let empty: Vec<String> = Vec::new();
    for line in aligned_lines(&keys(&old), &keys(&new)) {
        let (sign, key) = line.split_at(1);
        let (was, is) = match sign {
            "-" => {
                at_old += 1;
                (&old[at_old - 1].lines, &empty)
            }
            "+" => {
                at_new += 1;
                (&empty, &new[at_new - 1].lines)
            }
            _ => {
                at_old += 1;
                at_new += 1;
                (&old[at_old - 1].lines, &new[at_new - 1].lines)
            }
        };
        out.push_str(&match key {
            "table" => marked_table(was, is),
            "list" => marked_list(was, is),
            "fence" => marked_fence(was, is),
            _ => format!("{}\n\n", marked_words(&was.join(" "), &is.join(" "))),
        });
    }
    out
}

fn cells(row: &str) -> Vec<String> {
    let row = row.trim();
    let row = row.strip_prefix('|').unwrap_or(row);
    let row = row.strip_suffix('|').unwrap_or(row);
    row.split('|').map(|cell| cell.trim().to_string()).collect()
}

fn is_rule(row: &str) -> bool {
    cells(row).iter().all(|cell| {
        let dashes = cell.trim_matches(':');
        !dashes.is_empty() && dashes.chars().all(|c| c == '-')
    })
}

/// The rows of a table up to its rule, and the rows after it.
fn split_header(rows: &[String]) -> (Vec<String>, Vec<String>) {
    match rows.iter().position(|row| is_rule(row)) {
        Some(rule) => (rows[..rule].to_vec(), rows[rule + 1..].to_vec()),
        None => (Vec::new(), rows.to_vec()),
    }
}

fn marked_cell(old: &str, new: &str) -> String {
    match (old.is_empty(), new.is_empty()) {
        _ if old == new => new.to_string(),
        (true, _) => format!("**{new}**"),
        (_, true) => struck(old),
        _ => format!("{} **{new}**", struck(old)),
    }
}

fn row(mark: &str, cells: &[String]) -> String {
    format!("| {mark} | {} |\n", cells.join(" | "))
}

/// A changed table as a table, a first column marking each row that changed, came or went.
fn marked_table(old: &[String], new: &[String]) -> String {
    // § t0jfkh0n1.c@x91zg
    let (old_head, old_body) = split_header(old);
    let (new_head, new_body) = split_header(new);
    let head: Vec<String> = match (old_head.first(), new_head.first()) {
        (Some(was), Some(is)) => {
            let (was, is) = (cells(was), cells(is));
            (0..was.len().max(is.len()))
                .map(|i| {
                    let at = |side: &[String]| side.get(i).cloned().unwrap_or_default();
                    marked_cell(&at(&was), &at(&is))
                })
                .collect()
        }
        (Some(one), None) | (None, Some(one)) => cells(one),
        (None, None) => {
            let width = old_body.iter().chain(&new_body).map(|r| cells(r).len());
            vec![String::new(); width.max().unwrap_or(1)]
        }
    };
    let mut out = row("", &head);
    out.push_str(&row("---", &vec!["---".to_string(); head.len()]));
    for step in steps(&old_body, &new_body) {
        out.push_str(&match step {
            Step::Same(r) => row("", &cells(&r)),
            Step::Changed(was, is) => {
                let (was, is) = (cells(&was), cells(&is));
                let marked: Vec<String> = (0..was.len().max(is.len()))
                    .map(|i| {
                        let at = |side: &[String]| side.get(i).cloned().unwrap_or_default();
                        marked_cell(&at(&was), &at(&is))
                    })
                    .collect();
                row("changed", &marked)
            }
            Step::Gone(r) => row(
                "removed",
                &cells(&r)
                    .iter()
                    .map(|c| marked_cell(c, ""))
                    .collect::<Vec<_>>(),
            ),
            Step::Came(r) => row(
                "added",
                &cells(&r)
                    .iter()
                    .map(|c| marked_cell("", c))
                    .collect::<Vec<_>>(),
            ),
        });
    }
    // § end t0jfkh0n1.c
    out.push('\n');
    out
}

/// The items of a list, each with its own continuation lines, as one flat list: a line of the
/// packet that opens with `-`, `+` or a space would read to delta as a line of a hunk.
fn items(lines: &[String]) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for line in lines {
        let line = line.trim();
        match out.last_mut() {
            Some(item) if !is_item(line) => {
                item.push(' ');
                item.push_str(line);
            }
            _ => out.push(line.to_string()),
        }
    }
    out
}

/// An item as its bullet, `*` for any unordered one, and its text.
fn bullet(item: &str) -> (&str, &str) {
    let mark = item.find(' ').unwrap_or(item.len());
    let text = item[mark..].trim_start();
    match &item[..mark] {
        "-" | "+" | "*" => ("*", text),
        ordered => (ordered, text),
    }
}

/// A changed list as a list, each item that changed, came or went marked.
fn marked_list(old: &[String], new: &[String]) -> String {
    // § t0jfkh0n1.d@v04jt
    let mut out = String::new();
    for step in steps(&items(old), &items(new)) {
        out.push_str(&match step {
            Step::Same(item) => {
                let (mark, text) = bullet(&item);
                format!("{mark} {text}\n")
            }
            Step::Changed(was, is) => {
                let (mark, text) = bullet(&is);
                format!("{mark} *changed:* {}\n", marked_words(bullet(&was).1, text))
            }
            Step::Gone(was) => {
                let (mark, text) = bullet(&was);
                format!("{mark} *removed:* {}\n", struck(text))
            }
            Step::Came(is) => {
                let (mark, text) = bullet(&is);
                format!("{mark} *added:* **{text}**\n")
            }
        });
    }
    // § end t0jfkh0n1.d
    out.push('\n');
    out
}

/// A changed fenced block before and after, each in a fence of its own, then the lines that
/// changed.
fn marked_fence(old: &[String], new: &[String]) -> String {
    // § t0jfkh0n1.e@8kqd6
    let dedent = |lines: &[String]| -> Vec<String> {
        let margin = lines.first().map_or(0, |l| l.len() - l.trim_start().len());
        lines
            .iter()
            .map(|l| {
                let cut = l.len() - l.trim_start().len();
                l[cut.min(margin)..].to_string()
            })
            .collect()
    };
    let (old, new) = (dedent(old), dedent(new));
    let mut out = String::new();
    for (label, side) in [("Before", &old), ("After", &new)] {
        if !side.is_empty() {
            out.push_str(&format!("{label}:\n\n{}\n\n", side.join("\n")));
        }
    }
    let changed: String = aligned_lines(&old, &new)
        .into_iter()
        .filter(|line| !line.starts_with(' '))
        .map(|line| format!("{line}\n"))
        .collect();
    if !old.is_empty() && !new.is_empty() && !changed.is_empty() {
        out.push_str(&format!("Changed lines:\n\n{}", fence(&changed)));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn an_unchanged_text_keeps_its_blocks_apart() {
        assert_eq!(
            plain("A refund follows its state.\n| Clause | State |\n|---|---|"),
            "A refund follows its state.\n\n| Clause | State |\n|---|---|"
        );
    }

    #[test]
    fn words_change_in_place_and_a_code_span_stays_whole() {
        assert_eq!(
            marked_words("A refund over 500 is paid.", "A refund over 1000 is paid."),
            "A refund over ~~500~~ **1000** is paid."
        );
        assert_eq!(
            marked_words("Holds when `a < b` today.", "Holds when `a > b` today."),
            "Holds when ~~`a < b`~~ **`a > b`** today."
        );
        assert_eq!(marked_words("", "New law."), "**New law.**");
    }

    /// Four tildes at the start of a line open a fence, which would swallow the rest of the
    /// packet: a text struck already is struck once.
    #[test]
    fn a_struck_text_is_struck_once() {
        assert_eq!(
            view(Some("~~A refund goes back.~~"), None),
            "~~A refund goes back.~~\n\n"
        );
        assert_eq!(
            view(Some("A refund goes back."), None),
            "~~A refund goes back.~~\n\n"
        );
        assert_eq!(
            view(Some("~~A refund.~~"), Some("A refund.\nRevives it.")),
            "A refund. **Revives it.**\n\n"
        );
        assert_eq!(marked_cell("~~paid~~", ""), "~~paid~~");
        assert_eq!(marked_cell("paid", ""), "~~paid~~");
        assert_eq!(marked_words("~~a b~~", ""), "~~a b~~");
    }

    #[test]
    fn a_changed_table_marks_its_row_and_each_changed_cell() {
        let old = "| Clause | State | Next |\n|---|---|---|\n| (a) | open | approved |\n| (b) | approved | paid |";
        let new = "| Clause | State | Next |\n|---|---|---|\n| (a) | open | approved |\n| (b) | approved | settled |\n| (c) | settled | closed |";
        assert_eq!(
            view(Some(old), Some(new)),
            "|  | Clause | State | Next |\n\
             | --- | --- | --- | --- |\n\
             |  | (a) | open | approved |\n\
             | changed | (b) | approved | ~~paid~~ **settled** |\n\
             | added | **(c)** | **settled** | **closed** |\n\n"
        );
    }

    #[test]
    fn a_changed_list_marks_each_item() {
        let old = "Five shapes:\n\n  - always;\n  - when;\n  - while.";
        let new = "Five shapes:\n\n  - always;\n  - when an event;\n  - where.";
        assert_eq!(
            view(Some(old), Some(new)),
            "Five shapes:\n\n* always;\n* *changed:* ~~when;~~ **when an event;**\n* *changed:* ~~while.~~ **where.**\n\n"
        );
        let added = view(Some("- one"), Some("- one\n- two"));
        assert_eq!(added, "* one\n* *added:* **two**\n\n");
        let ordered = view(Some("1. one"), None);
        assert_eq!(ordered, "1. *removed:* ~~one~~\n\n");
    }

    #[test]
    fn a_changed_fence_shows_before_after_and_the_changed_lines() {
        let old = "The flow:\n  ```mermaid\n  stateDiagram-v2\n    approved --> paid: pay\n  ```";
        let new =
            "The flow:\n  ```mermaid\n  stateDiagram-v2\n    approved --> settled: pay\n  ```";
        let shown = view(Some(old), Some(new));
        assert!(shown.starts_with("The flow:\n\n"), "{shown}");
        assert!(
            shown.contains(
                "Before:\n\n```mermaid\nstateDiagram-v2\n  approved --> paid: pay\n```\n\n"
            ),
            "{shown}"
        );
        assert!(
            shown.contains(
                "After:\n\n```mermaid\nstateDiagram-v2\n  approved --> settled: pay\n```\n\n"
            ),
            "{shown}"
        );
        assert!(
            shown.ends_with(
                "Changed lines:\n\n```diff\n-  approved --> paid: pay\n+  approved --> settled: pay\n```\n\n"
            ),
            "{shown}"
        );
    }
}