-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.rs
More file actions
375 lines (345 loc) · 9.99 KB
/
Copy pathprocess.rs
File metadata and controls
375 lines (345 loc) · 9.99 KB
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
//! High-level Markdown stream processing.
mod buffer;
use buffer::ProcessBuffer;
use crate::{
ellipsis::replace_ellipsis,
fences::{attach_orphan_specifiers, compress_fences},
footnotes::convert_footnotes,
frontmatter::split_leading_yaml_frontmatter,
html::convert_html_tables,
wrap::{FenceTracker, wrap_text},
};
/// Column width used when wrapping text.
pub const WRAP_COLS: usize = 80;
/// Processing options controlling the behaviour of [`process_stream_inner`].
///
/// # Examples
///
/// ```
/// use mdtablefix::process::{Options, process_stream_opts};
///
/// let lines = vec!["example".to_string()];
/// let opts = Options {
/// wrap: false,
/// ellipsis: false,
/// fences: false,
/// footnotes: false,
/// code_emphasis: false,
/// headings: false,
/// };
/// let out = process_stream_opts(&lines, opts);
/// assert_eq!(out, vec!["example"]);
/// ```
#[expect(
clippy::struct_excessive_bools,
reason = "Options map directly to CLI flags"
)]
#[derive(Clone, Copy, Default)]
pub struct Options {
/// Enable paragraph wrapping.
pub wrap: bool,
/// Replace `...` with `…`.
pub ellipsis: bool,
/// Normalise code block fences.
pub fences: bool,
/// Convert bare numeric references into GitHub-flavoured footnote links (default: `false`).
pub footnotes: bool,
/// Fix emphasis markers adjacent to inline code.
pub code_emphasis: bool,
/// Convert Setext-style headings into ATX (`#`) headings.
pub headings: bool,
}
/// Processes a stream of Markdown lines using the provided [`Options`].
///
/// The function normalizes code fences, converts HTML tables, detects
/// Markdown tables and optionally wraps paragraphs. The exact behaviour is
/// controlled by `opts`.
///
/// # Examples
///
/// ```
/// use mdtablefix::process::{Options, process_stream_inner};
///
/// let lines = vec![
/// "| a | b |".to_string(),
/// "|---|---|".to_string(),
/// "| 1 | 2 |".to_string(),
/// ];
/// let out = process_stream_inner(
/// &lines,
/// Options {
/// wrap: false,
/// ellipsis: false,
/// fences: false,
/// footnotes: false,
/// code_emphasis: false,
/// headings: false,
/// },
/// );
/// assert_eq!(
/// out,
/// vec![
/// "| a | b |".to_string(),
/// "| --- | --- |".to_string(),
/// "| 1 | 2 |".to_string(),
/// ]
/// );
/// ```
#[must_use]
pub fn process_stream_inner(lines: &[String], opts: Options) -> Vec<String> {
let lines = if opts.fences {
let tmp = compress_fences(lines);
attach_orphan_specifiers(&tmp)
} else {
lines.to_vec()
};
let pre = convert_html_tables(&lines);
let mut state = ProcessBuffer::new(opts.ellipsis);
// Track fences so subsequent logic respects shared semantics.
let mut fence_tracker = FenceTracker::default();
for line in pre {
let fence = fence_tracker.observe_source_line(&line);
if state.handle_fence_line(&line, fence.is_fence_marker) {
continue;
}
if fence.is_in_fence {
state.push_out(line);
continue;
}
let Some(line) = state.handle_table_line(line) else {
continue;
};
state.flush();
state.push_out(line);
}
state.flush();
let mut out = state.into_out();
if opts.headings {
out = crate::headings::convert_setext_headings(&out);
}
if opts.code_emphasis {
out = crate::code_emphasis::fix_code_emphasis(&out);
}
let mut out = if opts.wrap {
wrap_text(&out, WRAP_COLS)
} else {
out
};
if opts.ellipsis {
out = replace_ellipsis(&out);
}
if opts.footnotes {
out = convert_footnotes(&out);
}
out
}
/// Processes a Markdown stream with all default options enabled.
///
/// This is the primary convenience function used by the command-line
/// interface. Paragraphs are wrapped and tables are reflowed.
///
/// # Examples
///
/// ```
/// use mdtablefix::process::process_stream;
///
/// let lines = vec![
/// "| a | b |".to_string(),
/// "|---|---|".to_string(),
/// "| 1 | 2 |".to_string(),
/// ];
/// let out = process_stream(&lines);
/// assert_eq!(
/// out,
/// vec![
/// "| a | b |".to_string(),
/// "| --- | --- |".to_string(),
/// "| 1 | 2 |".to_string(),
/// ]
/// );
/// ```
#[must_use]
pub fn process_stream(lines: &[String]) -> Vec<String> {
process_stream_opts(
lines,
Options {
wrap: true,
..Default::default()
},
)
}
/// Processes Markdown without wrapping paragraphs.
///
/// Useful when only table reflow and code fence normalization are required.
///
/// # Examples
///
/// ```
/// use mdtablefix::process::process_stream_no_wrap;
/// let lines = vec![
/// "| a | b |".to_string(),
/// "|---|---|".to_string(),
/// "| 1 | 2 |".to_string(),
/// ];
/// let out = process_stream_no_wrap(&lines);
/// assert_eq!(
/// out,
/// vec![
/// "| a | b |".to_string(),
/// "| --- | --- |".to_string(),
/// "| 1 | 2 |".to_string(),
/// ]
/// );
/// ```
#[must_use]
pub fn process_stream_no_wrap(lines: &[String]) -> Vec<String> {
process_stream_opts(lines, Options::default())
}
/// Runs [`process_stream_inner`] with custom [`Options`].
///
/// This is exposed for advanced use cases where callers want precise
/// control over the processing pipeline. Set `footnotes: true` in `opts`
/// to convert bare numeric references into GitHub-flavoured footnote
/// links. The flag defaults to `false`.
///
/// # Examples
///
/// ```
/// use mdtablefix::process::{Options, process_stream_opts};
/// let lines = vec!["text".to_string()];
/// let opts = Options {
/// wrap: false,
/// ellipsis: false,
/// fences: false,
/// footnotes: false,
/// code_emphasis: false,
/// headings: false,
/// };
/// let out = process_stream_opts(&lines, opts);
/// assert_eq!(out, vec!["text"]);
/// ```
#[must_use]
pub fn process_stream_opts(lines: &[String], opts: Options) -> Vec<String> {
process_with_frontmatter(lines, |body| process_stream_inner(body, opts))
}
/// Processes a Markdown body while preserving leading YAML frontmatter verbatim.
///
/// This is the canonical frontmatter split/rejoin boundary. `body_fn` receives
/// only the post-frontmatter body slice; the leading frontmatter prefix is never
/// passed to it and is prepended verbatim to the closure's output.
///
/// # Examples
///
/// ```
/// use mdtablefix::process::process_with_frontmatter;
///
/// let lines = vec![
/// "---".to_string(),
/// "title: Example".to_string(),
/// "---".to_string(),
/// "markdown body".to_string(),
/// ];
/// let mut received = Vec::new();
/// let output = process_with_frontmatter(&lines, |body| {
/// received = body.to_vec();
/// body.iter().map(|line| line.to_uppercase()).collect()
/// });
///
/// assert_eq!(received, vec!["markdown body"]);
/// assert_eq!(
/// output,
/// vec!["---", "title: Example", "---", "MARKDOWN BODY"]
/// );
/// ```
#[must_use]
pub fn process_with_frontmatter<F>(lines: &[String], body_fn: F) -> Vec<String>
where
F: FnOnce(&[String]) -> Vec<String>,
{
let (frontmatter_prefix, body) = split_leading_yaml_frontmatter(lines);
let mut result = frontmatter_prefix.to_vec();
result.extend(body_fn(body));
result
}
#[cfg(test)]
mod tests {
//! Unit tests for Markdown processing.
use super::*;
#[test]
fn processes_html_and_tables() {
let input = vec![
"<table><tr><td>A</td><td>B</td></tr></table>".to_string(),
"| X | Y |".to_string(),
"|---|---|".to_string(),
"| 1 | 2 |".to_string(),
];
let output = process_stream(&input);
assert!(output.iter().any(|l| l.contains("| A | B |")));
assert!(output.iter().any(|l| l.contains("| X | Y |")));
}
#[test]
fn no_wrap_option() {
let input = vec!["| a | b |".to_string(), "| 1 | 2 |".to_string()];
let out = process_stream_no_wrap(&input);
assert_eq!(out, vec!["| a | b |", "| 1 | 2 |"]);
}
#[test]
fn integrates_code_emphasis_flag() {
let input = vec!["`X`** Y (in **`Z`**)**".to_string()];
let out = process_stream_inner(
&input,
Options {
code_emphasis: true,
..Default::default()
},
);
assert_eq!(out, vec!["**`X` Y (in `Z`)**"]);
}
#[test]
fn converts_headings_when_enabled() {
let input = vec![
"Heading".to_string(),
"====".to_string(),
"Paragraph".to_string(),
];
let disabled = process_stream_inner(
&input,
Options {
headings: false,
..Default::default()
},
);
assert_eq!(disabled, input);
let enabled = process_stream_inner(
&input,
Options {
headings: true,
..Default::default()
},
);
assert_eq!(
enabled,
vec!["# Heading".to_string(), "Paragraph".to_string()]
);
}
#[test]
fn process_stream_inner_applies_table_ellipsis_before_reflow() {
let input = vec![
"| example | value |".to_string(),
"| ------- | ----- |".to_string(),
"| ... | tail |".to_string(),
];
let with_ellipsis = process_stream_inner(
&input,
Options {
ellipsis: true,
..Default::default()
},
);
let without_ellipsis = process_stream_inner(&input, Options::default());
assert!(with_ellipsis.iter().any(|line| line.contains('…')));
assert!(!with_ellipsis.iter().any(|line| line.contains("...")));
assert!(without_ellipsis.iter().any(|line| line.contains("...")));
assert!(!without_ellipsis.iter().any(|line| line.contains('…')));
}
}