markdown-formatter 0.0.13

Flavored Markdown (ZH) content formatter
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
pub mod builder;
pub mod split;

use std::{cmp::max, process};

use crate::args::builder::{print_doc, print_help, CommandLineOption};

/// 根据命令行的输入内容,生成相应的配置选项,用于调整 Markdowon Formatter 的行为。
#[derive(Debug)]
pub struct Args {
    /// 需要处理的 Markdown 源文件路径
    pub input: String,

    /// 调试标志位,将输出每一个可能的中间值
    pub debug: bool,

    /// 中文冒号转为英文冒号+空格,“:” => “: ”
    pub flag_colon: bool,

    /// 表格的每一行两端使用 |
    pub flag_enclose_table: bool,

    /// 从段落提取链接用于填充在段末或文章结尾
    pub flag_extract_links: bool,

    /// 提取链接时去掉锚点部分
    pub flag_extract_links_without_anchor: bool,

    /// 使用 Google 风格的 List 缩进,参见
    /// <https://google.github.io/styleguide/docguide/style.html>
    pub flag_google_list_style: bool,

    /// 中文分号转为英文分号+空格,“;” => “; ”
    pub flag_semicolon: bool,

    /// 中文括号转为英文括号+空格,“()” => “ () ”,将根据上下文去除多余的空格
    pub flag_parenthesis: bool,

    /// 以相同列宽展示表格中的每一列
    pub flag_pretty_table: bool,

    /// 去除 <url> 内部的非必要空格
    pub flag_strip_enclosed_url: bool,

    /// 加粗文字前后使用空格,“a**b**c” => “a **b** c”,将根据上下文去除多余的空格
    pub flag_whitespace_around_bold_font: bool,

    /// 斜体字更改为加粗文字,“a*b*c” => “a**b**c”
    pub flag_italic_to_bold_font: bool,

    /// 是否需要在开始格式化之前输出相应的配置
    pub print_config: bool,

    /// 输出配置时使用紧凑的布局
    pub compact_output: bool,

    /// 执行 Markdown 模块的函数时输出成对的 Tag
    pub debug_markdown_tag_pair: bool,
}

impl Args {
    fn new() -> Self {
        Self {
            input: String::from(""),
            debug: false,
            flag_colon: false,
            flag_enclose_table: false,
            flag_semicolon: false,
            flag_parenthesis: false,
            flag_pretty_table: false,
            flag_extract_links: false,
            flag_extract_links_without_anchor: false,
            flag_whitespace_around_bold_font: false,
            flag_italic_to_bold_font: false,
            flag_strip_enclosed_url: false,
            print_config: false,
            compact_output: false,
            flag_google_list_style: false,
            debug_markdown_tag_pair: false,
        }
    }

    /// 解析命令行选项和参数
    ///
    /// # Arguments
    /// - `args` - 来自命令行或认为构建的选项
    pub fn parse(args: Vec<String>) -> Option<Self> {
        if args.len() > 1 {
            let mut val = Self::new();
            val.input = args.last().unwrap().to_string();

            let mut options = vec![];

            for arg in args {
                let mut should_explain = true;

                match arg.as_str() {
                    // Help
                    "--help" => {
                        print_help_info(Some(true), Some(options));
                        process::exit(0)
                    }
                    "-h" => {
                        print_help_info(None, None);
                        process::exit(0)
                    }
                    "--print" | "-p" => val.print_config = true,
                    "--print-compact" => {
                        val.compact_output = true;
                        val.print_config = true
                    }
                    // Flags
                    "--colon" => val.flag_colon = true,
                    "--extract-links" => val.flag_extract_links = true,
                    "--enclose-table" => val.flag_enclose_table = true,
                    "--extract-no-anchor" => val.flag_extract_links_without_anchor = true,
                    "--google-list-style" => val.flag_google_list_style = true,
                    "--italic-to-bold" => val.flag_italic_to_bold_font = true,
                    "--parenthesis" => val.flag_parenthesis = true,
                    "--semicolon" => val.flag_semicolon = true,
                    "--pretty-table" => {
                        val.flag_pretty_table = true;
                        panic!("Unimplemented style")
                    }
                    "--whitespace-around-bold" => val.flag_whitespace_around_bold_font = true,
                    "--strip-enclosed-url" => val.flag_strip_enclosed_url = true,
                    // Flavors
                    "--flavor-hugging-face-wechat" => val.set_flavor_hugging_face_wechat(),
                    // Debug
                    "--debug-markdown-tag-pair" => val.debug_markdown_tag_pair = true,

                    _ => {
                        if arg.starts_with("-") {
                            panic!("无法识别的选项 `{}`", arg);
                        } else {
                            should_explain = false;
                        }
                    }
                }

                if should_explain {
                    options.push(arg.clone());
                }
            }
            Some(val)
        } else {
            None
        }
    }

    /// 使用 Hugging Face 微信公众号的风格
    pub fn set_flavor_hugging_face_wechat(&mut self) {
        self.flag_colon = true;
        self.flag_enclose_table = true;
        self.flag_semicolon = true;
        self.flag_parenthesis = true;
        self.flag_whitespace_around_bold_font = true;
        self.flag_italic_to_bold_font = false; // Updated since 20230425
        self.flag_extract_links = false; // Updated since 20230417
        self.flag_extract_links_without_anchor = false; // Updated since 20230417
        self.flag_strip_enclosed_url = true;
        self.flag_google_list_style = false;
    }

    /// 打印所有风格选项
    pub fn print_config(&self) {
        println!("渲染选项启用状态");
        let mut results: Vec<(&str, bool)> = vec![];
        let mut max_width = 0;
        results.push((
            "Colon conversion",
            if self.flag_colon { true } else { false },
        ));
        results.push((
            "Extract links",
            if self.flag_extract_links { true } else { false },
        ));
        results.push((
            "Extract links without anchor",
            if self.flag_extract_links_without_anchor {
                true
            } else {
                false
            },
        ));
        results.push((
            "Semicolon conversion",
            if self.flag_semicolon { true } else { false },
        ));
        results.push((
            "List using Google style",
            if self.flag_google_list_style {
                true
            } else {
                false
            },
        ));
        results.push((
            "Parenthesis conversion",
            if self.flag_parenthesis { true } else { false },
        ));
        results.push((
            "Prettify table",
            if self.flag_pretty_table { true } else { false },
        ));

        results.push((
            "Italic to bold font conversion",
            if self.flag_italic_to_bold_font {
                true
            } else {
                false
            },
        ));
        results.push((
            "Whitespace around bold font",
            if self.flag_whitespace_around_bold_font {
                true
            } else {
                false
            },
        ));
        results.push((
            "Strip whitespace around enclosed URL",
            if self.flag_strip_enclosed_url {
                true
            } else {
                false
            },
        ));
        results.sort_by(|item_a, item_b| {
            max_width = max(max_width, max(item_a.0.len(), item_b.0.len()));
            if item_a.1 == item_b.1 {
                item_a.0.cmp(&item_b.0)
            } else {
                if item_a.1 {
                    std::cmp::Ordering::Less
                } else {
                    std::cmp::Ordering::Greater
                }
            }
        });
        let mut counter: usize = 1;
        let digits = if results.len() < 10 {
            1
        } else if results.len() < 100 {
            2
        } else if results.len() < 1000 {
            3
        } else {
            4
        };
        println!(
            "┌─{}──{}┬───┐",
            "".repeat(digits),
            "".repeat(max_width + 1)
        );
        results.iter().for_each(|res| {
            if !self.compact_output && counter > 1 {
                println!(
                    "├─{}──{}┼───┤",
                    "".repeat(digits),
                    "".repeat(max_width + 1)
                );
            }
            println!(
                "│ {:digits$}. {:max_width$} │ {}",
                counter,
                res.0,
                if res.1 { "Y" } else { "N" }
            );
            counter += 1;
        });
        println!(
            "└─{}──{}┴───┘",
            "".repeat(digits),
            "".repeat(max_width + 1)
        );
    }
}

fn print_help_info(
    long_help: Option<bool>,
    filtered: Option<Vec<String>>,
) -> Vec<CommandLineOption> {
    println!("命令用法: md-fmt [选项] <Markdown 文件名>\n");

    let mut commands = vec![];

    // 标准选项
    commands.push(
        CommandLineOption::new("--help", "输出当前的帮助信息 (--help 更详细)", "")
            .set_condition(builder::CommandLineOptionCondition::Standard)
            .set_short("-h"),
    );

    // 格式化选项
    commands.push(
        CommandLineOption::new(
            "--colon",
            "中文冒号转为英文冒号+空格",
            "比如: “:” => “: ”。如果在行末,则会生成“:”,即删除末尾的空格。",
        )
        .set_condition(builder::CommandLineOptionCondition::Format),
    );
    commands.push(
        CommandLineOption::new(
            "--enclose-table",
            "表格的每一行两端使用 |",
            "比如表格的对齐行: “:-- | :--” => “| :-- | :-- |”。",
        )
        .set_condition(builder::CommandLineOptionCondition::Format),
    );
    commands.push(
        CommandLineOption::new("--extract-links", "从段落中提取超链接", "比如:\n“这句话包含了一个[超链接](https://dongs.xyz/)” => “这句话包含了一个[超链接](https://dongs.xyz/)\\n\\n超链接:\\n<url>https://dongs.xyz/</url>”")
            .set_condition(builder::CommandLineOptionCondition::Format),
    );
    commands.push(
        CommandLineOption::new("--extract-no-anchor", "提取链接时不包括锚点部分", "")
            .set_condition(builder::CommandLineOptionCondition::Format),
    );
    commands.push(
        CommandLineOption::new("--google-list-style", "使用 Google 风格的列表样式", "")
            .set_condition(builder::CommandLineOptionCondition::Format),
    );
    commands.push(
        CommandLineOption::new(
            "--italic-to-bold",
            "斜体字更改为加粗文字",
            "比如: “a*b*c” => “a**b**c”",
        )
        .set_condition(builder::CommandLineOptionCondition::Format),
    );
    commands.push(
        CommandLineOption::new(
            "--parenthesis",
            "中文括号转为英文括号+空格",
            "比如:\n“()” => “ () ”\n最终结果将根据上下文去除多余的空格。",
        )
        .set_condition(builder::CommandLineOptionCondition::Format),
    );
    commands.push(
        CommandLineOption::new("--pretty-table", "以相同列宽展示表格中的每一列", "")
            .set_condition(builder::CommandLineOptionCondition::Format),
    );
    commands.push(
        CommandLineOption::new(
            "--semicolon",
            "中文分号转为英文分号+空格",
            "比如: “;” => “; ”\n最终结果将根据上下文去除多余的空格。",
        )
        .set_condition(builder::CommandLineOptionCondition::Format),
    );
    commands.push(
        CommandLineOption::new(
            "--strip-enclosed-url",
            "去除 <url> 内部的非必要空格",
            "比如: “<url> https://dongs.xyz/ </url>” => “<url>https://dongs.xyz/</url>”",
        )
        .set_condition(builder::CommandLineOptionCondition::Format),
    );
    commands.push(
        CommandLineOption::new(
            "--whitespace-around-bold",
            "加粗文字前后使用空格",
            "比如:\n“a**b**c” => “a **b** c”;\n“a **b**c” => “a **b** c”。\n最终结果将根据上下文去除多余的空格。",
        )
        .set_condition(builder::CommandLineOptionCondition::Format),
    );

    // 附加选项
    commands.push(
        CommandLineOption::new("--print", "在控制台输出当前启用的调整", "")
            .set_condition(builder::CommandLineOptionCondition::Additional),
    );
    commands.push(
        CommandLineOption::new("--print-compact", "窄行距输出当前启用的调整", "")
            .set_condition(builder::CommandLineOptionCondition::Additional),
    );

    // 调试选项
    commands.push(
        CommandLineOption::new(
            "--debug-markdown-tag-pair",
            "执行 Markdown 模块的函数时输出成对的 Tag (仅适用于 `debug` feature)",
            "",
        )
        .set_condition(builder::CommandLineOptionCondition::Debug),
    );

    // 定制风格
    commands.push(
        CommandLineOption::new(
            "--flavor-hugging-face-wechat",
            "使用 Hugging Face 微信公众号风格来调整输入内容",
            "",
        )
        .set_condition(builder::CommandLineOptionCondition::Flavor),
    );

    // use termsize::{get as get_termsize, Size};
    // Switch to termsize-alt because termsize crates on crates.io is out dated.
    use termsize_alt::{get as get_termsize, Size};
    let Size { rows: _, cols } = get_termsize().unwrap_or(Size {
        rows: 40,
        cols: 120,
    });

    let line_width = Some(cols.into());

    match long_help {
        Some(true) => print_doc(commands.clone(), filtered, line_width),
        _ => print_help(commands.clone(), line_width),
    }

    commands
}

#[cfg(test)]
mod test {
    use crate::args::Args;
    #[test]
    fn test_argument_parsing() {
        let mut options: Vec<String> = vec!["--colon", "--parenthesis", "test.md"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        if let Some(args) = Args::parse(options) {
            assert_eq!(args.flag_colon, true);
            assert_eq!(args.flag_parenthesis, true);
        };

        options = vec!["--flavor-hugging-face-wechat", "test.md"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        if let Some(args) = Args::parse(options) {
            assert_eq!(args.flag_colon, true);
            assert_eq!(args.flag_parenthesis, true);
            assert_eq!(args.flag_italic_to_bold_font, true);
            assert_eq!(args.flag_whitespace_around_bold_font, true);
        };
    }

    #[test]
    fn test_malformed_options() {
        let options = vec!["--flavor-hugging-face-wechat"]
            .iter()
            .map(|s| s.to_string())
            .collect();

        Args::parse(options);
    }
}