snapper-fmt 0.10.0

Semantic line break formatter for Org, LaTeX, Markdown, RST, and plaintext
Documentation
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Integration tests for the code-block comment-reflow path.
//!
//! Each test feeds a synthetic input through `format_text` with a
//! synthesised `FormatConfig` whose `code` table carries the relevant
//! language entry. We do not depend on `.snapperrc.toml` loading here; the
//! config-roundtrip path is covered by unit tests in `src/config.rs`.
//!
//! Idempotence is asserted alongside each functional assertion: the
//! `assert_round_trip!` macro applies `format_text` twice and requires the
//! second pass to be a byte-identical no-op.

use std::collections::HashMap;

use snapper_fmt::FormatConfig;
use snapper_fmt::config::CodeLang;
use snapper_fmt::format::Format;
use snapper_fmt::format_text;

/// Build a per-language map keyed by the language strings used on code
/// fences. Caller supplies (lang, line_comment, block_comment) tuples.
#[allow(clippy::type_complexity)]
fn code_map(entries: &[(&str, Option<&str>, Option<[&str; 2]>)]) -> HashMap<String, CodeLang> {
    let mut map = HashMap::new();
    for (lang, lc, bc) in entries {
        map.insert(
            (*lang).to_string(),
            CodeLang {
                line_comment: lc.map(|s| s.to_string()),
                block_comment: bc.map(|pair| [pair[0].to_string(), pair[1].to_string()]),
                ..Default::default()
            },
        );
    }
    map
}

fn config(format: Format, code: HashMap<String, CodeLang>) -> FormatConfig {
    FormatConfig {
        format,
        code,
        ..Default::default()
    }
    .without_safety_backstops()
}

/// Round-trip helper. Returns the once-formatted output and asserts the
/// twice-formatted output is byte-identical to it (idempotence).
fn round_trip(input: &str, cfg: &FormatConfig) -> String {
    let first = format_text(input, cfg).expect("first format pass succeeded");
    let second = format_text(&first, cfg).expect("second format pass succeeded");
    assert_eq!(
        first, second,
        "format_text(format_text(input)) must equal format_text(input)"
    );
    first
}

// ---------------------------------------------------------------------------
// R5: line-comment reflow on four languages
// ---------------------------------------------------------------------------

#[test]
fn rust_line_comment_reflows_two_sentences() {
    let input = "\
```rust
// Long comment with two sentences. Second sentence here.
fn main() {}
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    let expected = "\
```rust
// Long comment with two sentences.
// Second sentence here.
fn main() {}
```
";
    assert_eq!(out, expected);
}

#[test]
fn python_line_comment_reflows() {
    let input = "\
```python
# First sentence. Second sentence.
print('hi')
```
";
    let cfg = config(Format::Markdown, code_map(&[("python", Some("#"), None)]));
    let out = round_trip(input, &cfg);
    assert!(out.contains("# First sentence.\n# Second sentence.\n"));
}

#[test]
fn lua_line_comment_reflows() {
    let input = "\
```lua
-- First sentence. Second sentence.
print('hi')
```
";
    let cfg = config(Format::Markdown, code_map(&[("lua", Some("--"), None)]));
    let out = round_trip(input, &cfg);
    assert!(out.contains("-- First sentence.\n-- Second sentence.\n"));
}

#[test]
fn lisp_line_comment_reflows() {
    let input = "\
```lisp
; First sentence. Second sentence.
(print 1)
```
";
    let cfg = config(Format::Markdown, code_map(&[("lisp", Some(";"), None)]));
    let out = round_trip(input, &cfg);
    assert!(out.contains("; First sentence.\n; Second sentence.\n"));
}

// ---------------------------------------------------------------------------
// R7: block-comment reflow on at least three of {rust, python, lua, html}
// ---------------------------------------------------------------------------

#[test]
fn rust_block_comment_one_liner_splits() {
    let input = "\
```rust
/* Two sentences. Like this. */
fn x() {}
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    // Opening and closing markers stay on their own lines; interior
    // reflows as plaintext.
    assert!(out.contains("/*\n Two sentences.\n Like this.\n*/\n"));
}

#[test]
fn python_block_comment_one_liner_splits() {
    let input = "\
```python
\"\"\" First. Second. \"\"\"
def f(): pass
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("python", Some("#"), Some(["\"\"\"", "\"\"\""]))]),
    );
    let out = round_trip(input, &cfg);
    assert!(out.contains("\"\"\"\n First.\n Second.\n\"\"\"\n"));
}

#[test]
fn html_block_comment_one_liner_splits() {
    let input = "\
```html
<!-- First. Second. -->
<p>hi</p>
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("html", None, Some(["<!--", "-->"]))]),
    );
    let out = round_trip(input, &cfg);
    assert!(out.contains("<!--\n First.\n Second.\n-->\n"));
}

// ---------------------------------------------------------------------------
// R8: indentation preservation -- flush-left and 4-space-indented fences
// ---------------------------------------------------------------------------

#[test]
fn flush_left_fence_preserves_indent() {
    let input = "\
```rust
    // First sentence here. Second one too.
    fn x() {}
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    // 4-space body indent preserved on every output comment line.
    assert!(out.contains("    // First sentence here.\n    // Second one too.\n    fn x() {}\n"));
}

#[test]
fn indented_fence_preserves_body_indent() {
    // Markdown list-nested fence: the fence itself is 4-space-indented,
    // and so is the body. Markdown parser's fence detection trim_starts so
    // it still recognises the fence, and the body's leading whitespace
    // round-trips byte-identical.
    let input = "\
- An item:

    ```rust
    // First. Second.
    fn x() {}
    ```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    assert!(out.contains("    // First.\n    // Second.\n    fn x() {}\n"));
}

// ---------------------------------------------------------------------------
// R15: pragma respect inside code blocks for three languages
// ---------------------------------------------------------------------------

#[test]
fn rust_pragma_freezes_section() {
    let input = "\
```rust
// snapper:off
// Long.
// Off.
// snapper:on
// Reflow this. Now.
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    let expected_body = "\
// snapper:off
// Long.
// Off.
// snapper:on
// Reflow this.
// Now.
";
    assert!(out.contains(expected_body), "got:\n{out}");
}

#[test]
fn python_pragma_freezes_section() {
    let input = "\
```python
# snapper:off
# Long.
# Off.
# snapper:on
# Reflow this. Now.
```
";
    let cfg = config(Format::Markdown, code_map(&[("python", Some("#"), None)]));
    let out = round_trip(input, &cfg);
    let expected_body = "\
# snapper:off
# Long.
# Off.
# snapper:on
# Reflow this.
# Now.
";
    assert!(out.contains(expected_body));
}

#[test]
fn lua_pragma_freezes_section() {
    let input = "\
```lua
-- snapper:off
-- Long.
-- Off.
-- snapper:on
-- Reflow this. Now.
```
";
    let cfg = config(Format::Markdown, code_map(&[("lua", Some("--"), None)]));
    let out = round_trip(input, &cfg);
    let expected_body = "\
-- snapper:off
-- Long.
-- Off.
-- snapper:on
-- Reflow this.
-- Now.
";
    assert!(out.contains(expected_body));
}

// ---------------------------------------------------------------------------
// R6: the .> clipping matrix -- both broken-today shapes and regression
// guards. All eight forms must round-trip byte-identical when embedded in
// a Rust comment line at the bottom of a code block.
// ---------------------------------------------------------------------------

fn matrix_input(tail: &str) -> String {
    format!("```rust\nfn main() {{}}\n// e.g. {tail}\n```\n",)
}

#[test]
fn clipping_matrix_round_trips() {
    // Four BROKEN-today shapes.
    let broken = ["Vec<...>", "<.>", "<..>", "<a.>"];
    // Four WORKING-today shapes (regression guard).
    let working = ["<a.b>", "<.b>", "<a>", "<>"];

    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    for tail in broken.iter().chain(working.iter()) {
        let input = matrix_input(tail);
        let out = round_trip(&input, &cfg);
        assert_eq!(
            out, input,
            "shape {tail:?} must round-trip; got:\n{out}\n!=\n{input}",
        );
    }
}

// ---------------------------------------------------------------------------
// R2: org and rst parsers also produce Region::Code that the reflow path
// recognises. We assert end-to-end behaviour without inspecting the AST.
// ---------------------------------------------------------------------------

#[test]
fn org_src_block_comment_reflows() {
    let input = "\
#+BEGIN_SRC rust
// First sentence. Second sentence.
fn main() {}
#+END_SRC
";
    let cfg = config(
        Format::Org,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    assert!(out.contains("// First sentence.\n// Second sentence.\nfn main() {}"));
}

#[test]
fn rst_code_block_comment_reflows() {
    let input = "\
.. code-block:: python

   # First sentence. Second sentence.
   print('hi')
";
    let cfg = config(Format::Rst, code_map(&[("python", Some("#"), None)]));
    let out = round_trip(input, &cfg);
    // RST body indent (3 spaces) is preserved on every reflowed comment line.
    assert!(
        out.contains("   # First sentence.\n   # Second sentence."),
        "got:\n{out}"
    );
}

// ---------------------------------------------------------------------------
// Single language passthrough when [code] entry is absent: the block body
// must be byte-identical to the input. Idempotence assertion is implicit.
// ---------------------------------------------------------------------------

#[test]
fn unknown_lang_passes_through_unchanged() {
    let input = "\
```ocaml
(* Two sentences. They stay together. *)
let x = 1
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    assert_eq!(out, input);
}

#[test]
fn no_lang_on_fence_passes_through_unchanged() {
    let input = "\
```
// looks like rust but no fence lang -> verbatim. Stays together.
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    assert_eq!(out, input);
}

// ---------------------------------------------------------------------------
// Grammar-backed discovery: comments that do not open their line, and
// markers that only look like comments. Both need a parse to tell apart.
// ---------------------------------------------------------------------------

#[test]
#[cfg(feature = "treesitter")]
fn rust_trailing_comment_reflows_aligned_under_itself() {
    let input = "\
```rust
fn main() {
    let n = 1; // Trailing note. Second sentence here.
}
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    let expected = "\
```rust
fn main() {
    let n = 1; // Trailing note.
               // Second sentence here.
}
```
";
    assert_eq!(out, expected);
}

#[test]
fn rust_block_comment_close_inside_string_does_not_end_comment() {
    // A `*/` sitting inside a string must not close the comment. The rest of
    // the comment is still prose and must reflow as such.
    let input = "\
```rust
/*
let s = \"*/\";
This is still the comment. Second sentence.
*/
fn x() {}
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    let expected = "\
```rust
/*
 let s = \"*/\"; This is still the comment.
 Second sentence.
*/
fn x() {}
```
";
    assert_eq!(out, expected);
}

#[test]
fn rust_marker_inside_string_literal_is_not_a_comment() {
    let input = "\
```rust
fn main() {
    let s = \"// not a comment. Really not one.\";
}
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    assert_eq!(out, input);
}

#[test]
#[cfg(feature = "treesitter")]
fn rust_doc_comment_keeps_its_own_marker() {
    let input = "\
```rust
/// Doc line one. Doc line two.
fn x() {}
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    assert!(
        out.contains("/// Doc line one.\n/// Doc line two.\n"),
        "doc marker must survive the split, got:\n{out}"
    );
}

#[test]
#[cfg(feature = "treesitter")]
fn python_trailing_comment_reflows() {
    let input = "\
```python
x = 1  # First sentence. Second sentence.
```
";
    let cfg = config(Format::Markdown, code_map(&[("python", Some("#"), None)]));
    let out = round_trip(input, &cfg);
    assert!(
        out.contains("x = 1  # First sentence.\n       # Second sentence.\n"),
        "trailing python comment must align under itself, got:\n{out}"
    );
}

#[test]
#[cfg(feature = "treesitter")]
fn pragma_freezes_a_trailing_comment() {
    let input = "\
```rust
// snapper:off
fn main() {
    let n = 1; // Frozen note. Stays on one line.
}
// snapper:on
```
";
    let cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let out = round_trip(input, &cfg);
    assert_eq!(out, input);
}

#[test]
fn language_without_a_grammar_reflows_trailing_comments_too() {
    let input = "\
```lua
-- First sentence. Second sentence.
local x = 1 -- Trailing one. Trailing two.
```
";
    let cfg = config(Format::Markdown, code_map(&[("lua", Some("--"), None)]));
    let out = round_trip(input, &cfg);
    assert!(
        out.contains("-- First sentence.\n-- Second sentence.\n"),
        "own-line comment splits on the scanner path, got:\n{out}"
    );
    assert!(
        out.contains("local x = 1 -- Trailing one.\n            -- Trailing two.\n"),
        "lua has no grammar, so the scanner must handle the trailing comment, got:\n{out}"
    );
}

#[test]
fn scanner_path_leaves_a_marker_inside_a_string_alone() {
    let input = "\
```lua
local s = \"-- not a comment. Really not one.\"
```
";
    let cfg = config(Format::Markdown, code_map(&[("lua", Some("--"), None)]));
    let out = round_trip(input, &cfg);
    assert_eq!(
        out, input,
        "quote tracking must keep a marker inside a literal out of the reflow"
    );
}

#[test]
fn scanner_and_grammar_agree_on_a_plain_trailing_comment() {
    // The wasm builds behind the Obsidian and Word integrations carry no
    // grammar, so the two engines have to produce the same text for code
    // this ordinary.
    let rust_input = "\
```rust
let n = 1; // Trailing one. Trailing two.
```
";
    let lua_input = "\
```lua
local n = 1 -- Trailing one. Trailing two.
```
";
    let rust_cfg = config(
        Format::Markdown,
        code_map(&[("rust", Some("//"), Some(["/*", "*/"]))]),
    );
    let lua_cfg = config(Format::Markdown, code_map(&[("lua", Some("--"), None)]));

    let rust_out = round_trip(rust_input, &rust_cfg);
    let lua_out = round_trip(lua_input, &lua_cfg);

    assert!(
        rust_out.contains("let n = 1; // Trailing one.\n           // Trailing two.\n"),
        "grammar path, got:\n{rust_out}"
    );
    assert!(
        lua_out.contains("local n = 1 -- Trailing one.\n            -- Trailing two.\n"),
        "scanner path, got:\n{lua_out}"
    );
}