mdtablefix 0.6.1

`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
//! Fenced code block helpers.
//!
//! Fence state is keyed by marker character, marker length, and blockquote
//! depth. Keeping those values together prevents a closing marker from a
//! shallower quote or a different marker family from ending the wrong block.

use regex::Regex;
use tracing::{debug, trace};

use super::{
    BlockquotePrefix,
    paragraph::{ParagraphState, ParagraphWriter},
};

/// Match indentation, a three-or-more marker run, and its complete info text.
///
/// The info string is retained verbatim because only a closing fence with
/// spaces or tabs after its marker may terminate an existing fenced block.
pub(super) static FENCE_RE: std::sync::LazyLock<Regex> =
    // Capture: indent, fence run of 3+ backticks/tilde, and the full info string (incl. leading
    // spaces)
    lazy_regex!(
        r"^(\s*)(`{3,}|~{3,})([^\r\n]*)$",
        "wrapping fence delimiter and info string pattern should compile",
    );

/// Return fence components if the line starts a fenced code block.
///
/// The function captures:
/// - the leading indentation,
/// - the fence marker itself (three or more backticks or tildes),
/// - the full trailing “info string” (including any leading spaces and attributes).
///
/// # Examples
///
/// ```rust
/// use mdtablefix::wrap::is_fence;
/// assert_eq!(is_fence("```rust"), Some(("", "```", "rust")));
/// assert_eq!(is_fence("``` rust"), Some(("", "```", " rust")));
/// assert_eq!(is_fence("``` rust linenums"), Some(("", "```", " rust linenums")));
/// assert_eq!(is_fence("> > ```rust"), Some(("> > ", "```", "rust")));
/// assert!(is_fence("not a fence").is_none());
/// ```
#[doc(hidden)]
#[must_use]
#[rustfmt::skip]
pub fn is_fence(line: &str) -> Option<(&str, &str, &str)> {
    let context = FenceLine::parse(line);
    is_inner_fence(context.inner).map(|(inner_indent, fence, info)| {
        let indent = &line[..context.prefix_len + inner_indent.len()];
        (indent, fence, info)
    })
}

/// Match a fence after any blockquote prefix has been removed.
///
/// Returning borrowed capture slices keeps the original info string available
/// for the closing-fence whitespace check.
#[rustfmt::skip]
fn is_inner_fence(line: &str) -> Option<(&str, &str, &str)> {
    FENCE_RE.captures(line).map(|cap| {
        let inner_indent = cap.get(1).map_or("", |m| m.as_str());
        let fence  = cap.get(2).map_or("", |m| m.as_str());
        let info   = cap.get(3).map_or("", |m| m.as_str());
        (inner_indent, fence, info)
    })
}

/// The prefix-stripped view needed while classifying a source fence line.
///
/// `prefix_len` lets the caller rebuild an indentation slice spanning both
/// blockquote and inner indentation without allocating a new prefix.
struct FenceLine<'a> {
    /// Content after the optional blockquote prefix.
    inner: &'a str,
    /// Blockquote nesting depth at which this line appears.
    depth: usize,
    /// Byte length of the source blockquote prefix.
    prefix_len: usize,
}

impl<'a> FenceLine<'a> {
    /// Parse the optional blockquote prefix while preserving source offsets.
    fn parse(line: &'a str) -> Self {
        BlockquotePrefix::parse(line).map_or(
            Self {
                inner: line,
                depth: 0,
                prefix_len: 0,
            },
            |prefix| Self {
                inner: prefix.inner(),
                depth: prefix.depth(),
                prefix_len: prefix.raw_prefix().len(),
            },
        )
    }
}
/// Handle a potential fence line, updating state and emitting the line when needed.
///
/// Returns `true` if the line was processed as a fence.
pub(crate) fn handle_fence_line(
    line: &str,
    inner_content: &str,
    depth: usize,
    writer: &mut ParagraphWriter<'_>,
    state: &mut ParagraphState,
    tracker: &mut FenceTracker,
) -> bool {
    if !tracker.observe_inner(inner_content, depth) {
        return false;
    }

    writer.push_verbatim(state, line);
    true
}

/// Opening-fence identity used to validate later closing markers.
#[derive(Clone, Copy, Debug)]
struct FenceState {
    /// Marker family used by the opener (backtick or tilde).
    marker: char,
    /// Marker run length required of a closing fence.
    marker_len: usize,
    /// Blockquote depth at which the fence was opened.
    open_depth: usize,
}

/// The state transition observed while processing one source line.
#[derive(Clone, Copy, Debug)]
pub(crate) struct FenceObservation {
    /// Whether the current depth was already inside a fence before this line.
    pub(crate) was_in_fence: bool,
    /// Whether this line matched a fence marker at the current depth.
    pub(crate) is_fence_marker: bool,
    /// Whether the current depth is inside a fence after this line.
    pub(crate) is_in_fence: bool,
}

/// A source-line fence observation paired with the structural fence parse of
/// that same line.
///
/// Callers that need the marker components (indentation, marker run, info
/// string) obtain them here rather than re-running [`is_fence`], keeping
/// [`FenceTracker`] the single authority for the line's fence classification.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ObservedFence<'a> {
    /// The tracker transition for the complete source line.
    pub(crate) observation: FenceObservation,
    /// The `(indent, marker, info)` components when the line is a fence marker,
    /// with `indent` spanning any blockquote prefix, as [`is_fence`] returns.
    pub(crate) fence: Option<(&'a str, &'a str, &'a str)>,
}

/// Tracks Markdown fenced code block state across lines.
///
/// The tracker centralises fence matching logic so that callers share the
/// same semantics for opening and closing blocks.
///
/// # Examples
///
/// ```
/// use mdtablefix::wrap::FenceTracker;
///
/// let mut tracker = FenceTracker::new();
/// assert!(!tracker.in_fence(0));
/// assert!(tracker.observe("```rust", 0));
/// assert!(tracker.in_fence(0));
/// assert!(tracker.observe("```", 0));
/// assert!(!tracker.in_fence(0));
/// ```
#[derive(Default, Debug)]
pub struct FenceTracker {
    /// The active opener, or `None` between fenced blocks.
    state: Option<FenceState>,
}

impl FenceTracker {
    /// Create a new tracker with no active fence.
    #[must_use]
    pub fn new() -> Self { Self::default() }

    /// Update the tracker with a potential fence line.
    ///
    /// Returns `true` when the line is treated as a fence marker and updates
    /// the internal state accordingly.
    ///
    /// # Panics
    ///
    /// Panics when the fence regular expression yields an empty marker, which
    /// would indicate the regex is inconsistent with Markdown fence rules.
    #[must_use]
    pub fn observe(&mut self, line: &str, depth: usize) -> bool {
        self.observe_inner(FenceLine::parse(line).inner, depth)
    }

    /// Observe a fence after its blockquote prefix has already been removed.
    ///
    /// The caller supplies `depth` separately because the inner text no longer
    /// carries enough information to recover the quote nesting.
    fn observe_inner(&mut self, line: &str, depth: usize) -> bool {
        self.observe_parsed(depth, is_inner_fence(line))
    }

    /// Update the tracker from an already-parsed inner fence, avoiding a second
    /// regex match when the caller has parsed the line itself.
    fn observe_parsed(&mut self, depth: usize, parsed: Option<(&str, &str, &str)>) -> bool {
        if let Some(open) = self.state
            && depth < open.open_depth
        {
            debug!(
                transition = "implicit_close",
                reason = "blockquote_depth_decreased",
                depth,
                open_depth = open.open_depth,
                open_marker_len = open.marker_len,
                "fence state changed"
            );
            self.state = None;
        }

        let Some((_indent, fence, info)) = parsed else {
            return false;
        };

        let mut chars = fence.chars();
        let marker_ch = chars.next().expect("FENCE_RE guarantees a non-empty fence");
        let marker_len = chars.count() + 1;
        // CommonMark forbids an info string on a closing fence: a same-marker
        // line carrying trailing text is literal content, not a close. Only
        // ASCII spaces and tabs may follow a closing marker, so avoid the
        // Unicode-aware `trim`, which would wrongly accept a no-break space
        // (U+00A0) or form feed (U+000C) as blank trailing whitespace.
        let closes_fence = info.bytes().all(|b| b == b' ' || b == b'\t');

        match self.state {
            Some(open)
                if depth == open.open_depth
                    && marker_ch == open.marker
                    && marker_len >= open.marker_len
                    && closes_fence =>
            {
                debug!(
                    transition = "matching_close",
                    depth,
                    open_depth = open.open_depth,
                    marker_len,
                    open_marker_len = open.marker_len,
                    "fence state changed"
                );
                self.state = None;
            }
            Some(open)
                if depth == open.open_depth
                    && marker_ch == open.marker
                    && marker_len >= open.marker_len =>
            {
                trace!(
                    transition = "unchanged",
                    reason = "closing_fence_has_info_string",
                    depth,
                    open_depth = open.open_depth,
                    marker_len,
                    open_marker_len = open.marker_len,
                    "fence marker did not change state"
                );
            }
            Some(open) => {
                trace!(
                    transition = "unchanged",
                    reason = "incompatible_active_opener",
                    depth,
                    open_depth = open.open_depth,
                    marker_len,
                    open_marker_len = open.marker_len,
                    "fence marker did not change state"
                );
            }
            None => {
                debug!(
                    transition = "open",
                    depth,
                    open_depth = depth,
                    marker_len,
                    open_marker_len = marker_len,
                    "fence state changed"
                );
                self.state = Some(FenceState {
                    marker: marker_ch,
                    marker_len,
                    open_depth: depth,
                });
            }
        }

        true
    }

    /// Update the tracker from a source line, including any blockquote prefix.
    ///
    /// This compatibility boundary is intended for processing stages that
    /// receive raw Markdown rather than the prefix-stripped input used by
    /// `wrap_text`.
    ///
    /// # Examples
    ///
    /// ```
    /// use mdtablefix::wrap::FenceTracker;
    ///
    /// let mut tracker = FenceTracker::new();
    /// assert!(tracker.observe_line("> > ```rust"));
    /// assert!(tracker.in_fence(2));
    /// ```
    #[must_use]
    pub fn observe_line(&mut self, line: &str) -> bool {
        self.observe_source_line(line).is_fence_marker
    }

    /// Observe a complete source line and return only its state transition.
    ///
    /// This is the compact adapter used by callers that do not need the parsed
    /// marker components returned by [`Self::observe_source_fence`].
    pub(crate) fn observe_source_line(&mut self, line: &str) -> FenceObservation {
        self.observe_source_fence(line).observation
    }

    /// Observe a source line, returning the fence-state transition together with
    /// the structural fence parse of the line.
    ///
    /// The line's blockquote prefix and fence marker are parsed exactly once and
    /// reused for both the tracker update and the returned `fence` components, so
    /// callers need not run [`is_fence`] again.
    pub(crate) fn observe_source_fence<'a>(&mut self, line: &'a str) -> ObservedFence<'a> {
        let context = FenceLine::parse(line);
        let parsed_inner = is_inner_fence(context.inner);
        let was_in_fence = self.in_fence(context.depth);
        let is_fence_marker = self.observe_parsed(context.depth, parsed_inner);
        let is_in_fence = self.in_fence(context.depth);
        let fence = parsed_inner.map(|(inner_indent, marker, info)| {
            let indent = &line[..context.prefix_len + inner_indent.len()];
            (indent, marker, info)
        });
        ObservedFence {
            observation: FenceObservation {
                was_in_fence,
                is_fence_marker,
                is_in_fence,
            },
            fence,
        }
    }

    /// Check whether the tracker is currently inside a fenced block.
    #[must_use]
    pub fn in_fence(&self, current_depth: usize) -> bool {
        self.state
            .is_some_and(|open| current_depth >= open.open_depth)
    }

    /// Check fence state at the blockquote depth represented by a source line.
    ///
    /// # Examples
    ///
    /// ```
    /// use mdtablefix::wrap::FenceTracker;
    ///
    /// let mut tracker = FenceTracker::new();
    /// assert!(tracker.observe_line("> ```"));
    /// assert!(tracker.in_fence_for_line("> code"));
    /// assert!(!tracker.in_fence_for_line("outside the quote"));
    /// ```
    #[must_use]
    pub fn in_fence_for_line(&self, line: &str) -> bool {
        self.in_fence(FenceLine::parse(line).depth)
    }
}

#[cfg(test)]
mod property_tests {
    //! Property coverage for the capture contract shared by wrapping fences.

    use proptest::prelude::*;

    use super::is_fence;

    proptest! {
        #[test]
        fn fence_captures_round_trip_generated_delimiters(
            indent in "[ \\t]{0,4}",
            blockquote_depth in 0_usize..=4,
            marker in prop_oneof![Just('`'), Just('~')],
            marker_length in 3_usize..=12,
            info in "[^\\r\\n]{0,40}",
        ) {
            let blockquote = "> ".repeat(blockquote_depth);
            let prefix = format!("{indent}{blockquote}");
            let delimiter = marker.to_string().repeat(marker_length);
            let line = format!("{prefix}{delimiter}{info}");
            let absorbed_marker_count = info.chars().take_while(|character| *character == marker).count();
            let expected_delimiter = marker.to_string().repeat(marker_length + absorbed_marker_count);
            let expected_info = &info[absorbed_marker_count..];

            let captures = is_fence(&line);

            prop_assert_eq!(
                captures,
                Some((prefix.as_str(), expected_delimiter.as_str(), expected_info)),
            );
            let (captured_prefix, captured_delimiter, captured_info) =
                captures.expect("generated fence should match");
            prop_assert_eq!(
                format!("{captured_prefix}{captured_delimiter}{captured_info}"),
                line,
            );
        }
    }
}