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
/// Converts a markdown string to a groff/troff string.
///
/// * `title` is the name of the program. It's typically all-uppercase.
///
/// * `section` is the numeric section of man pages. Usually `1`.
///
/// The conversion is very rough. HTML fragments are merely stripped from tags.
/// GitHub tables extension is not supported.
pub fn convert(markdown_markup: &str, title: &str, section: u8) -> String {
    use pulldown_cmark::{Parser, Options};
    use pulldown_cmark::Event::*;
    use pulldown_cmark::Tag::*;

    let mut options = Options::empty();
    options.insert(Options::ENABLE_STRIKETHROUGH);
    let parser = Parser::new_ext(markdown_markup, options);

    let mut out = Rough { out: String::new(), in_quotes: false };
    out.title(title, section);

    let mut links = Vec::new();
    let mut images = Vec::new();
    let mut min_header_level = 999;
    let mut link_ref_num = 1;
    let mut list_item_num = None;
    let mut in_list = false;
    let mut first_para_in_list = false;

    fn flush_links(out: &mut Rough, links: &mut Vec<(String, String, String)>) {
        if links.is_empty() {
            return;
        }

        out.empty_line();
        for (n, url, title) in links.drain(..) {
            out.text(&format!("{} {} {}", n, url, title));
            out.line_break();
        }
    }

    for event in parser {
        match event {
            Rule => out.centered("----"),
            Html(markup) => {
                out.text(&strip_tags(&markup));
            },
            TaskListMarker(checked) => out.text(if checked {"[x]"} else {"[ ]"}),
            Start(Heading(n, _, _)) => {
                let n = n as u32;
                flush_links(&mut out, &mut links);

                if n < min_header_level {
                    min_header_level = n;
                }
                out.section_start(n + 1 - min_header_level);
            },
            End(Heading(n, _, _)) => out.section_end((n as u32) + 1 - min_header_level),

            Start(Link(..)) | Start(Image(..)) => {},
            End(Link(_, url, title)) => {
                let marker = format!("[{}]", link_ref_num);
                out.text(&marker);
                links.push((marker, url.to_string(), title.to_string()));
                link_ref_num += 1;
            },
            End(Image(_, url, title)) => {
                let marker = format!("[img{}]", link_ref_num);
                out.text(&marker);
                images.push((marker, url.to_string(), title.to_string()));
                link_ref_num += 1;
            },

            Start(CodeBlock(_)) => out.pre_start(),
            End(CodeBlock(_)) => out.pre_end(),

            Start(List(num)) => {
                list_item_num = num;
                out.indent()
            },
            End(List(_)) => out.outdent(),

            Start(Item) => {
                in_list = true;
                first_para_in_list = true;
                out.list_start(list_item_num);
                if let Some(n) = &mut list_item_num {
                    *n += 1;
                }
            },
            End(Item) => {
                in_list = false;
                out.list_end(); flush_links(&mut out, &mut links);
            },

            Start(BlockQuote) => out.blockquote_start(),
            End(BlockQuote) => {
                flush_links(&mut out, &mut links);
                out.blockquote_end()
            },

            Start(Paragraph) => {
                if in_list {
                    if first_para_in_list {
                        first_para_in_list = false;
                    } else {
                        out.empty_line();
                    }
                } else {
                    out.paragraph_start()
                }
            },
            End(Paragraph) => {flush_links(&mut out, &mut links); out.paragraph_end();},

            Start(Emphasis) => out.italic_start(),
            End(Emphasis) => out.italic_end(),

            Start(Strikethrough) => {out.text("~"); out.italic_start();},
            End(Strikethrough) => {out.italic_end(); out.text("~");},

            Start(Strong) => out.bold_start(),
            End(Strong) => out.bold_end(),

            HardBreak => out.line_break(),
            SoftBreak => out.ensure_line_start(),
            Code(text) => out.code(&text),
            Text(text) => out.text(&text),
            FootnoteReference(s) | Start(FootnoteDefinition(s)) => {
                out.text(&format!("[*{}]", s));
            },
            End(FootnoteDefinition(_)) => {},

            // FIXME: total fudge
            Start(Table(_)) => out.paragraph_start(),
            End(Table(_)) => out.paragraph_end(),
            Start(TableHead) => out.paragraph_start(),
            End(TableHead) => out.paragraph_end(),
            Start(TableRow) | End(TableRow) => out.line_break(),
            Start(TableCell) | End(TableCell) => out.text(" | "),
        }
    }

    flush_links(&mut out, &mut links);
    flush_links(&mut out, &mut images);

    out.out
}

struct Rough {
    out: String,
    in_quotes: bool,
}

impl Rough {
    pub fn title(&mut self, title: &str, man_section: u8) {
        self.ensure_line_start();
        self.out.push_str(".TH \"");
        self.in_quotes = true;
        self.text(title);
        self.in_quotes = false;
        self.text(&format!("\" {}", man_section));
        self.out.push_str("\n");
    }

    pub fn section_start(&mut self, level: u32) {
        self.ensure_line_start();
        self.in_quotes = true;
        // extra line needed too, otherwise headers get wrapped into prev paragraph?
        self.out.push('\n');
        match level {
            1 => self.out.push_str(".SH \""),
            2 => self.out.push_str(".SS \""),
            _ => self.out.push_str(".SB \""),
        }
    }

    pub fn section_end(&mut self, _level: u32) {
        self.in_quotes = false;
        self.out.push_str("\"\n");
    }

    // pub fn table_start(&mut self) {
    //     self.ensure_line_start();
    //     self.out.push_str(".TS\n");
    // }
    // pub fn table_end(&mut self) {
    //     self.ensure_line_start();
    //     self.out.push_str(".TE\n");
    // }

    pub fn paragraph_start(&mut self) {
        self.ensure_line_start();
        self.out.push_str(".PP\n");
    }

    pub fn paragraph_end(&mut self) {
        self.out.push_str("\n");
    }

    pub fn blockquote_start(&mut self) {
        self.indent();
        // self.ensure_line_start();
        // self.out.push_str(".QS\n");
    }

    pub fn blockquote_end(&mut self) {
        self.outdent();
        // self.ensure_line_start();
        // self.out.push_str(".QE\n");
    }

    pub fn list_start(&mut self, n: Option<u64>) {
        self.ensure_line_start();
        self.out.push_str(".Bl\n");
        if let Some(n) = n {
            self.out.push_str(&format!(".IP {}. 4\n", n));
        } else {
            self.out.push_str(".IP \\(bu 4\n");
        }
    }

    pub fn list_end(&mut self) {
        self.ensure_line_start();
        self.out.push_str(".El\n");
    }

    pub fn ensure_line_start(&mut self) {
        if self.out.is_empty() || self.out.chars().rev().next() == Some('\n') {
            return;
        }
        self.out.push('\n');
    }

    pub fn text(&mut self, text: &str) {
        let text = deunicode::deunicode(&text);
        let text = if self.in_quotes {
            text.replace('"', "\"\"")
        } else {
            text.replace('-', "\\-").replace('.', "\\.")
        };
        self.out.push_str(&text);
    }

    pub fn code(&mut self, text: &str) {
        self.out.push_str("`\\f[CR]");
        self.text(text);
        self.out.push_str("\\fP`");
    }

    pub fn pre_start(&mut self) {
        self.indent();
        self.ensure_line_start();
        self.out.push_str(".PP\n");
        self.out.push_str(".nf\n");
    }
    pub fn pre_end(&mut self) {
        self.ensure_line_start();
        self.out.push_str(".fi\n");
        self.outdent();
    }

    pub fn line_break(&mut self) {
        self.ensure_line_start();
        self.out.push_str(".nf\n.fi\n");
    }

    pub fn empty_line(&mut self) {
        self.ensure_line_start();
        self.out.push_str(".sp\n");
    }

    pub fn italic_start(&mut self) {
        self.out.push_str("\\fI");
    }
    pub fn italic_end(&mut self) {
        self.out.push_str("\\fP");
    }

    pub fn bold_start(&mut self) {
        self.out.push_str("\\fB");
    }
    pub fn bold_end(&mut self) {
        self.out.push_str("\\fP");
    }

    pub fn indent(&mut self) {
        self.ensure_line_start();
        self.out.push_str(".RS\n");
    }
    pub fn outdent(&mut self) {
        self.ensure_line_start();
        self.out.push_str(".RE\n");
    }
    pub fn centered(&mut self, text: &str) {
        self.ensure_line_start();
        self.out.push_str(".ce 1000\n");
        self.text(text);
        self.ensure_line_start();
        self.out.push_str(".ce 0\n");
    }
}

fn strip_tags(txt: &str) -> String {
    let mut out = String::with_capacity(txt.len()/2);
    let mut in_tag = false;
    let mut maybe_in_tag = false;
    let mut in_arg = None;
    for ch in txt.chars() {
        match ch {
            '>' if in_tag && in_arg.is_none() => {
                in_tag = false;
            },
            '<' if !in_tag && !maybe_in_tag => {
                maybe_in_tag = true;
            },
            'a'..='z' | 'A'..='Z' | '/' | '!' if maybe_in_tag => {
                maybe_in_tag = false;
                in_tag = true;
            },
            '"' | '\'' if in_tag && in_arg.is_none() => {
                in_arg = Some(ch);
            },
            '"' | '\'' if in_arg == Some(ch) => {
                in_arg = None;
            },
            _ if in_tag => {}
            ch => {
                out.push(ch);
            }
        }
    }
    out
}