mdtablefix 0.4.0

`mdtablefix` unb0rks and reflows Markdown tables so that each column has a uniform width. When the `--wrap` option is used, it also wraps paragraphs and list items to 80 columns.
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
//! Unit tests for text wrapping functionality.
//!
//! This module contains tests for the `wrap_text` function, verifying correct
//! behaviour with code spans, links, hyphenated words, and various line widths.

use rstest::rstest;

use super::{
    inline::{attach_punctuation_to_previous_line, determine_token_span, wrap_preserving_code},
    line_buffer::{LineBuffer, SplitContext},
    tokenize::segment_inline,
};
use crate::wrap::{BlockKind, classify_block, wrap_text};

#[rstest]
#[case("`code`!", "`code`!")]
#[case("[link](url).", "[link](url).")]
#[case("plain,", "plain,")]
#[case("`code`,", "`code`,")]
#[case("`code`!`more`", "`code`!`more`")]
#[case("`code` `more`", "`code`")]
#[case("`code` `more`,", "`code`")]
#[case("[link](url),", "[link](url),")]
#[case("[link](url)[another](url2)", "[link](url)[another](url2)")]
#[case("[link](url) [another](url2)", "[link](url) [another](url2)")]
#[case("`code` ,", "`code` ,")]
#[case("`code` !", "`code` !")]
#[case("[link](url) .", "[link](url) .")]
#[case("`code!`", "`code!`")]
#[case("[link!](url)", "[link!](url)")]
fn determine_token_span_groups_related_tokens(#[case] input: &str, #[case] expected_group: &str) {
    let tokens = segment_inline(input);
    let (end, width) = determine_token_span(&tokens, 0);
    let grouped = tokens[..end].join("");
    assert_eq!(grouped, expected_group);
    assert_eq!(width, unicode_width::UnicodeWidthStr::width(expected_group));
}

#[rstest]
#[case("word[link](url)", &["word", "[link](url)"])]
#[case(
    "word[link](url)[another](url2)",
    &["word", "[link](url)", "[another](url2)"]
)]
#[case("word![img](url)", &["word", "![img](url)"])]
fn segment_inline_splits_before_embedded_links(#[case] input: &str, #[case] expected: &[&str]) {
    let tokens = segment_inline(input);
    let actual: Vec<&str> = tokens.iter().map(String::as_str).collect();
    assert_eq!(actual, expected);
}

#[rstest]
#[case(r"\[link](url)")]
#[case(r"word\[link](url)")]
#[case(r"\![img](url)")]
#[case(r"word\![img](url)")]
fn segment_inline_preserves_escaped_link_literals(#[case] input: &str) {
    assert_eq!(segment_inline(input), vec![input.to_string()]);
}

#[test]
fn attach_punctuation_appends_to_previous_code_line() {
    let mut lines = vec!["wrap `code`".to_string()];
    let current = String::new();
    assert!(attach_punctuation_to_previous_line(
        lines.as_mut_slice(),
        &current,
        "!",
    ));
    assert_eq!(lines, vec!["wrap `code`!".to_string()]);
}

#[test]
fn attach_punctuation_requires_empty_current_buffer() {
    let mut lines = vec!["`code`".to_string()];
    let current = " pending".to_string();
    assert!(!attach_punctuation_to_previous_line(
        lines.as_mut_slice(),
        &current,
        "!",
    ));
    assert_eq!(lines, vec!["`code`".to_string()]);
}

#[test]
fn attach_punctuation_ignores_non_code_suffix() {
    let mut lines = vec!["plain text".to_string()];
    let current = String::new();
    assert!(!attach_punctuation_to_previous_line(
        lines.as_mut_slice(),
        &current,
        ".",
    ));
    assert_eq!(lines, vec!["plain text".to_string()]);
}

#[test]
fn line_buffer_trims_trailing_whitespace_before_punctuation() {
    let tokens = vec![
        "wrap".to_string(),
        " ".to_string(),
        "`code`".to_string(),
        "  ".to_string(),
    ];
    let mut buffer = LineBuffer::new();
    buffer.push_span(&tokens, 0, tokens.len());
    assert_eq!(buffer.text(), "wrap `code`  ");

    let punct = vec!["!".to_string()];
    buffer.push_span(&punct, 0, punct.len());
    assert_eq!(buffer.text(), "wrap `code`!");
}

#[test]
fn line_buffer_split_preserves_multi_space_lines() {
    let tokens = vec![
        "alpha".to_string(),
        "  ".to_string(),
        "beta".to_string(),
        "   ".to_string(),
    ];
    let mut buffer = LineBuffer::new();
    buffer.push_span(&tokens, 0, 2);

    let mut lines = Vec::new();
    let mut split = SplitContext {
        lines: &mut lines,
        width: 8,
    };
    assert!(buffer.split_with_span(&mut split, &tokens, 2..4));
    assert_eq!(lines, vec!["alpha  ".to_string()]);
    assert_eq!(buffer.text(), "beta   ");
    assert_eq!(
        buffer.width(),
        unicode_width::UnicodeWidthStr::width(buffer.text())
    );
}

#[test]
fn line_buffer_split_trims_single_trailing_space() {
    let tokens = vec!["alpha".to_string(), " ".to_string(), "beta".to_string()];
    let mut buffer = LineBuffer::new();
    buffer.push_span(&tokens, 0, 2);

    let mut lines = Vec::new();
    let mut split = SplitContext {
        lines: &mut lines,
        width: 5,
    };
    assert!(buffer.split_with_span(&mut split, &tokens, 2..3));
    assert_eq!(lines, vec!["alpha".to_string()]);
    assert_eq!(buffer.text(), "beta");
    assert_eq!(
        buffer.width(),
        unicode_width::UnicodeWidthStr::width(buffer.text())
    );
}

#[test]
fn line_buffer_split_tracks_multiple_whitespace_tokens() {
    let tokens = vec![
        "foo".to_string(),
        " ".to_string(),
        " ".to_string(),
        "bar".to_string(),
    ];
    let mut buffer = LineBuffer::new();
    buffer.push_span(&tokens, 0, 3);

    let mut lines = Vec::new();
    let mut split = SplitContext {
        lines: &mut lines,
        width: 4,
    };
    assert!(buffer.split_with_span(&mut split, &tokens, 3..4));
    assert_eq!(lines, vec!["foo  ".to_string()]);
    assert_eq!(buffer.text(), "bar");
}

#[test]
fn line_buffer_trailing_whitespace_flushes_line() {
    let mut buffer = LineBuffer::new();
    let words = vec!["foo".to_string()];
    buffer.push_span(&words, 0, words.len());

    let whitespace_tokens = vec!["  ".to_string()];
    let mut lines = Vec::new();
    assert!(buffer.flush_trailing_whitespace(
        &mut lines,
        &whitespace_tokens,
        0..whitespace_tokens.len()
    ));
    assert_eq!(lines, vec!["foo  ".to_string()]);
    assert!(buffer.text().is_empty());
}

#[test]
fn wrap_preserving_code_splits_after_consecutive_whitespace() {
    let lines = wrap_preserving_code("alpha  beta   gamma", 8);
    assert_eq!(
        lines,
        vec![
            "alpha  ".to_string(),
            "beta   ".to_string(),
            "gamma".to_string()
        ]
    );
}

#[test]
fn wrap_preserving_code_glues_punctuation_after_code() {
    let lines = wrap_preserving_code("line with `code` !", 80);
    assert_eq!(lines, vec!["line with `code`!".to_string()]);
}

#[test]
fn wrap_preserving_code_breaks_between_inline_code_spans() {
    let text = "Extensions (`.toml`, `.json`, `.json5`, `.yaml`, `.yml`).";
    // Width 35 sits between the width of the `.json` and `.json5` prefixes,
    // forcing the wrapper to decide whether it can break between separate
    // inline code spans that are spaced apart.
    let lines = wrap_preserving_code(text, 35);
    assert_eq!(
        lines,
        vec![
            "Extensions (`.toml`, `.json`,".to_string(),
            "`.json5`, `.yaml`, `.yml`).".to_string(),
        ]
    );
}

#[test]
fn wrap_preserving_code_retains_punctuation_after_separate_spans() {
    let text = "Alpha `code` `more`, trailing.";
    let lines = wrap_preserving_code(text, 18);
    assert_eq!(
        lines,
        vec!["Alpha `code`".to_string(), "`more`, trailing.".to_string(),]
    );
}

#[rstest]
#[case("alpha beta", 5, &["alpha", " beta"])]
#[case("alpha  beta", 5, &["alpha", "  beta"])]
#[case("alpha `beta`", 5, &["alpha", " `beta`"])]
fn wrap_preserving_code_preserves_carry_whitespace(
    #[case] input: &str,
    #[case] width: usize,
    #[case] expected: &[&str],
) {
    let lines = wrap_preserving_code(input, width);
    assert_eq!(
        lines,
        expected.iter().map(|&s| s.to_string()).collect::<Vec<_>>()
    );
    assert_eq!(lines.concat(), input);
}

#[test]
fn wrap_text_preserves_hyphenated_words() {
    let input = vec!["A word that is very-long-word indeed".to_string()];
    let wrapped = wrap_text(&input, 20);
    assert_eq!(
        wrapped,
        vec![
            "A word that is".to_string(),
            "very-long-word".to_string(),
            "indeed".to_string(),
        ]
    );
}

#[test]
fn wrap_text_does_not_insert_spaces_in_hyphenated_words() {
    let input = vec![
        concat!(
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt ",
            "elit-sed fermentum congue. Vivamus dictum nulla sed consectetur ",
            "volutpat.",
        )
        .to_string(),
    ];
    let wrapped = wrap_text(&input, 80);
    assert_eq!(
        wrapped,
        vec![
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt".to_string(),
            "elit-sed fermentum congue. Vivamus dictum nulla sed consectetur volutpat.".to_string(),
        ]
    );
}

#[test]
fn wrap_text_preserves_code_spans() {
    let input = vec![
        "with their own escaping rules. On Windows, scripts default to `powershell -Command` \
         unless the manifest's `interpreter` field overrides the setting."
            .to_string(),
    ];
    let wrapped = wrap_text(&input, 60);
    assert_eq!(
        wrapped,
        vec![
            "with their own escaping rules. On Windows, scripts default".to_string(),
            "to `powershell -Command` unless the manifest's".to_string(),
            "`interpreter` field overrides the setting.".to_string(),
        ]
    );
}

#[test]
fn wrap_text_multiple_code_spans() {
    let input = vec!["combine `foo bar` and `baz qux` in one line".to_string()];
    let wrapped = wrap_text(&input, 25);
    assert_eq!(
        wrapped,
        vec![
            "combine `foo bar` and".to_string(),
            "`baz qux` in one line".to_string(),
        ]
    );
}

#[test]
fn wrap_text_nested_backticks() {
    let input = vec!["Use `` `code` `` to quote backticks".to_string()];
    let wrapped = wrap_text(&input, 20);
    assert_eq!(
        wrapped,
        vec![
            "Use `` `code` `` to".to_string(),
            "quote backticks".to_string()
        ],
    );
}

#[test]
fn wrap_text_unmatched_backticks() {
    let input = vec!["This has a `dangling code span.".to_string()];
    let wrapped = wrap_text(&input, 20);
    assert_eq!(
        wrapped,
        vec!["This has a".to_string(), "`dangling code span.".to_string()],
    );
}

#[test]
fn wrap_text_preserves_links() {
    let input = vec![
        "`falcon-pachinko` is an extension library for the".to_string(),
        "[Falcon](https://falcon.readthedocs.io) web framework. It adds a structured".to_string(),
        "approach to asynchronous WebSocket routing and background worker integration.".to_string(),
    ];
    let wrapped = wrap_text(&input, 80);
    let joined = wrapped.join("\n");
    assert_eq!(joined.matches("https://").count(), 1);
    assert!(
        wrapped
            .iter()
            .any(|l| l.contains("https://falcon.readthedocs.io"))
    );
}

#[rstest]
#[case("trail  ", 80, &["trail  "])]
#[case("`code span`  ", 12, &["`code span`  "])]
#[case("foo  ", 3, &["foo  "])]
#[case("x  ", 1, &["x  "])]
fn preserves_trailing_spaces(#[case] input: &str, #[case] width: usize, #[case] expected: &[&str]) {
    let out = wrap_preserving_code(input, width);
    assert_eq!(
        out,
        expected.iter().map(|&s| s.to_string()).collect::<Vec<_>>()
    );
}

#[rstest]
#[case("aaaaaaaaaaaa", 5, &["aaaaaaaaaaaa"])] // forced flush without split
#[case("abcde", 3, &["abcde"])]
#[case("`codespan`", 6, &["`codespan`"])]
fn no_split_forced_flush_no_trim(
    #[case] input: &str,
    #[case] width: usize,
    #[case] expected: &[&str],
) {
    let out = wrap_preserving_code(input, width);
    assert_eq!(
        out,
        expected.iter().map(|&s| s.to_string()).collect::<Vec<_>>()
    );
}

#[test]
fn wrap_text_keeps_trailing_spaces_for_blockquote_final_line() {
    // "> " is the prefix; available width = 10 - 2 = 8.
    let input = vec!["> word1 word2  ".to_string()];
    let wrapped = wrap_text(&input, 10);
    assert_eq!(
        wrapped,
        vec!["> word1".to_string(), "> word2  ".to_string()]
    );
}

#[test]
fn wrap_text_keeps_trailing_spaces_for_bullet_final_line() {
    // "- " is the prefix; continuation lines are indented with two spaces.
    let input = vec!["- word1 word2  ".to_string()];
    let wrapped = wrap_text(&input, 10);
    assert_eq!(
        wrapped,
        vec!["- word1".to_string(), "  word2  ".to_string()]
    );
}

#[test]
fn wrap_text_preserves_indented_hash_as_text() {
    let input = vec![
        "Paragraph intro.".to_string(),
        "    # code".to_string(),
        "Continuation.".to_string(),
    ];
    let wrapped = wrap_text(&input, 40);
    assert_eq!(
        wrapped,
        vec![
            "Paragraph intro.".to_string(),
            "    # code".to_string(),
            "Continuation.".to_string(),
        ]
    );
}

#[test]
fn wrap_text_flushes_before_heading() {
    let input = vec![
        "Paragraph intro.".to_string(),
        "# Heading".to_string(),
        "Continuation.".to_string(),
    ];
    let wrapped = wrap_text(&input, 40);
    assert_eq!(
        wrapped,
        vec![
            "Paragraph intro.".to_string(),
            "# Heading".to_string(),
            "Continuation.".to_string(),
        ]
    );
}

#[rstest(
    line,
    expected,
    case("# Heading", Some(BlockKind::Heading)),
    case("   # Heading", Some(BlockKind::Heading)),
    case("    # Heading", None),
    case("	# Heading", None),
    case("- item", Some(BlockKind::Bullet)),
    case("1. item", Some(BlockKind::Bullet)),
    case("> quote", Some(BlockKind::Blockquote)),
    case("[^1]: footnote", Some(BlockKind::FootnoteDefinition)),
    case(
        "<!-- markdownlint-disable -->",
        Some(BlockKind::MarkdownlintDirective)
    ),
    case("2024 revenue", Some(BlockKind::DigitPrefix)),
    case("a | b", None),
    case("plain text", None)
)]
fn classify_block_detects_markdown_prefixes(line: &str, expected: Option<BlockKind>) {
    assert_eq!(classify_block(line), expected);
}

mod fence_tracker;