ctb_formats_troff/
troff.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND Apache-2.0
2// SPDX-License-Identifier for parts derived from mantohtml: Apache-2.0
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// Parts derived from mantohtml:
22// Copyright © 2022-2023 by Michael R Sweet.
23//
24// Licensed under Apache License v2.0.
25// <https://opensource.org/licenses/Apache-2.0>
26
27// See additional licensing details at end of file.
28
29//! Man page to HTML conversion program.
30//! Based on <https://github.com/michaelrsweet/mantohtml>
31//! Not 100% equivalent to the above; there are a couple intentional
32//! differences where there appeared to be bugs (.in 17 gives 17em not 1em, and
33//! doubled `</a>\n</a>` only has one `</a>`); and it uses its own name/version.
34//!
35//! Usage:
36//!
37//!    mantohtml \[OPTIONS\] MAN-FILE \[... MAN-FILE\] >HTML-FILE
38//!
39//! Options:
40//!
41//!    --author 'AUTHOR'        Set author metadata
42//!    --chapter 'CHAPTER'      Set chapter (H1 heading)
43//!    --copyright 'COPYRIGHT'  Set copyright metadata
44//!    --css CSS-FILE-OR-URL    Use named stylesheet
45//!    --help                   Show help
46//!    --subject 'SUBJECT'      Set subject metadata
47//!    --title 'TITLE'          Set output title
48//!    --version                Show version
49//!
50//! Converted to Rust with AI assistance
51//! Limitations: Supports a subset of macros, not all of roff and its packages.
52//!
53//! Other implementations:
54//! <https://github.com/plan9foundation/plan9/blob/main/sys/src/cmd/troff2html/troff2html.c>
55//! <https://github.com/plan9foundation/plan9/tree/main/sys/src/cmd/troff>
56
57#[expect(
58    clippy::wildcard_imports,
59    reason = "Standard workspace crate prelude"
60)]
61pub(crate) use ctb_utilities::*;
62
63use std::env;
64use std::fs;
65use std::io::{self, Write};
66use std::path::Path;
67
68use anyhow::Result;
69use num_enum::IntoPrimitive;
70
71use ctb_formats_utilities::FormatLog;
72
73#[cfg(test)]
74pub(crate) fn get_troff_data(key: &str) -> Option<Vec<u8>> {
75    ctb_utilities::load_manifest_fixture(env!("CARGO_MANIFEST_DIR"), key)
76}
77
78// -----------------------------------------------------------------------------
79// Constants / Types
80// -----------------------------------------------------------------------------
81
82#[derive(Copy, Clone, Debug, PartialEq, Eq)]
83enum Font {
84    Regular,
85    Bold,
86    Italic,
87    Small,
88    SmallBold,
89    Monospace,
90}
91
92#[derive(Copy, Clone, Debug, PartialEq, Eq, IntoPrimitive)]
93#[repr(u8)]
94enum Heading {
95    Topic,
96    Section,
97    Subsection,
98}
99
100struct State {
101    wrote_header: bool,
102    in_block: Option<&'static str>,
103    in_link: bool,
104    indent: usize,
105    author: Option<String>,
106    chapter: Option<String>,
107    copyright: Option<String>,
108    css: Option<String>,
109    subject: Option<String>,
110    title: Option<String>,
111
112    atopic: String,
113    asection: String,
114    font: Font,
115}
116
117impl State {
118    fn new() -> Self {
119        State {
120            wrote_header: false,
121            in_block: None,
122            in_link: false,
123            indent: 0,
124            author: None,
125            chapter: None,
126            copyright: None,
127            css: None,
128            subject: None,
129            title: None,
130            atopic: String::new(),
131            asection: String::new(),
132            font: Font::Regular,
133        }
134    }
135}
136
137// -----------------------------------------------------------------------------
138// Main
139// -----------------------------------------------------------------------------
140
141fn main() {
142    let mut args: Vec<String> = env::args().collect();
143    if args.is_empty() {
144        args.push("mantohtml".into());
145    }
146
147    let mut state = State::new();
148
149    let mut i = 1usize;
150    let mut end_of_options = false;
151
152    if args.len() == 1 {
153        usage(None);
154        std::process::exit(1);
155    }
156
157    while i < args.len() {
158        let Some(arg) = args.get(i) else {
159            break;
160        };
161        if !end_of_options && arg == "--author" {
162            i = i.saturating_add(1);
163            if i >= args.len() {
164                eprintln!("mantohtml: Missing author after --author.");
165                std::process::exit(1);
166            }
167            state.author = args.get(i).cloned();
168        } else if !end_of_options && arg == "--chapter" {
169            i = i.saturating_add(1);
170            if i >= args.len() {
171                eprintln!("mantohtml: Missing chapter after --chapter.");
172                std::process::exit(1);
173            }
174            state.chapter = args.get(i).cloned();
175        } else if !end_of_options && arg == "--copyright" {
176            i = i.saturating_add(1);
177            if i >= args.len() {
178                eprintln!("mantohtml: Missing copyright after --copyright.");
179                std::process::exit(1);
180            }
181            state.copyright = args.get(i).cloned();
182        } else if !end_of_options && arg == "--css" {
183            i = i.saturating_add(1);
184            if i >= args.len() {
185                eprintln!(
186                    "mantohtml: Missing CSS filename or URL after --css."
187                );
188                std::process::exit(1);
189            }
190            state.css = args.get(i).cloned();
191        } else if !end_of_options && arg == "--help" {
192            usage(None);
193            return;
194        } else if !end_of_options && arg == "--subject" {
195            i = i.saturating_add(1);
196            if i >= args.len() {
197                eprintln!("mantohtml: Missing subject after --subject.");
198                std::process::exit(1);
199            }
200            state.subject = args.get(i).cloned();
201        } else if !end_of_options && arg == "--title" {
202            i = i.saturating_add(1);
203            if i >= args.len() {
204                eprintln!("mantohtml: Missing title after --title.");
205                std::process::exit(1);
206            }
207            state.title = args.get(i).cloned();
208        } else if !end_of_options && arg == "--version" {
209            println!("{}", package_version());
210            return;
211        } else if !end_of_options && arg == "--" {
212            end_of_options = true;
213        } else if !end_of_options && arg.starts_with('-') {
214            usage(Some(arg));
215            std::process::exit(1);
216        } else {
217            // Treat as filename
218            if let Err(err) = convert_man_to_stdout(&mut state, arg) {
219                eprintln!("{err}");
220            }
221        }
222        i = i.saturating_add(1);
223    }
224
225    if !state.wrote_header {
226        usage(None);
227        std::process::exit(1);
228    }
229}
230
231// -----------------------------------------------------------------------------
232// Conversion
233// -----------------------------------------------------------------------------
234
235fn convert_man_to_stdout(
236    state: &mut State,
237    filename: &str,
238) -> Result<(), String> {
239    let data = fs::read(filename).map_err(|e| format!("{filename}: {e}"))?;
240
241    let basepath;
242    if let Some(parent) = Path::new(filename).parent() {
243        basepath = parent.to_string_lossy().to_string();
244    } else {
245        basepath = ".".into();
246    }
247
248    convert_man_from_data(
249        state,
250        data,
251        Some(filename),
252        Some(basepath.as_str()),
253        io::stdout(),
254    )
255}
256
257pub fn convert_man_troff_to_html(
258    data: Vec<u8>,
259) -> Result<(Vec<u8>, FormatLog)> {
260    let mut state = State::new();
261    let mut buffer: Vec<u8> = Vec::new();
262    let mut log: FormatLog = FormatLog::default();
263    let result =
264        convert_man_from_data(&mut state, data, None, None, &mut buffer);
265
266    if let Err(err) = result {
267        log.error(&err);
268        return Ok((buffer, log));
269    }
270
271    Ok((buffer, log))
272}
273
274#[expect(
275    clippy::too_many_lines,
276    clippy::arithmetic_side_effects,
277    reason = "Legacy macro conversion dispatcher"
278)]
279fn convert_man_from_data<W: Write>(
280    state: &mut State,
281    data: Vec<u8>,
282    filename: Option<&str>,
283    basepath: Option<&str>,
284    out: W,
285) -> Result<(), String> {
286    let mut reader = ManReader::new(&data);
287
288    let mut th_seen = false;
289    let mut warning = false;
290    let mut break_text = String::new();
291
292    let mut stdout = io::BufWriter::new(out);
293
294    // Reason for fallback: document title defaults to "document" if filename parameter is None.
295    let filename = filename.unwrap_or("document");
296
297    while let Some(line) = reader.man_gets() {
298        // Handle macro lines starting with '.'
299        if line.starts_with('.') {
300            let mut lp: &str = &line;
301            // Reason for fallback: macro_name defaults to empty string if line contains no token.
302            let macro_name = parse_value(&mut lp).unwrap_or_default();
303
304            if macro_name == "." {
305                continue;
306            } else if macro_name == ".TH" {
307                // .TH title section ...
308                // Reason for fallback: title_val defaults to empty string if missing in .TH.
309                let title_val = parse_value(&mut lp).unwrap_or_default();
310                if title_val.is_empty() {
311                    return Err(format!(
312                        "mantohtml: Missing title in '.TH' on line {} of '{}'.",
313                        reader.line_number(),
314                        filename
315                    ));
316                }
317                // Reason for fallback: section defaults to empty string if missing in .TH.
318                let section = parse_value(&mut lp).unwrap_or_default();
319                if section.is_empty()
320                    // Reason for fallback: defaults to space character if section string is empty.
321                    || !section.chars().next().unwrap_or(' ').is_ascii_digit()
322                {
323                    return Err(format!(
324                        "mantohtml: Missing section in '.TH' on line {} of '{}'.",
325                        reader.line_number(),
326                        filename
327                    ));
328                }
329                let topic = format!("{title_val}({section})");
330
331                if state.wrote_header {
332                    if state.in_link {
333                        writeln!(stdout, "</a>").ok();
334                        state.in_link = false;
335                    }
336                    if let Some(block) = state.in_block.take() {
337                        writeln!(stdout, "</{block}>").ok();
338                    }
339                } else {
340                    html_header(state, &topic, &mut stdout);
341                }
342
343                html_heading(state, Heading::Topic, &topic, &mut stdout);
344                th_seen = true;
345            } else if !th_seen {
346                if !warning {
347                    eprintln!(
348                        "mantohtml: Need '.TH' before '{}' macro on line {} of '{}'.",
349                        macro_name,
350                        reader.line_number(),
351                        filename
352                    );
353                    warning = true;
354                }
355                continue;
356            } else if macro_name == ".B" {
357                let mut remainder = lp.to_owned();
358                if remainder.trim().is_empty()
359                    && let Some(next_line) = reader.man_gets()
360                {
361                    remainder = next_line;
362                }
363                push_font(state, Font::Bold, &mut stdout);
364                man_puts(state, &remainder, &mut stdout);
365                pop_font(state, &mut stdout);
366                writeln!(stdout, "{break_text}").ok();
367                break_text.clear();
368            } else if macro_name == ".BI" {
369                handle_xx(
370                    state,
371                    Font::Bold,
372                    Font::Italic,
373                    &mut reader,
374                    lp,
375                    &mut break_text,
376                    &mut stdout,
377                    basepath,
378                );
379            } else if macro_name == ".BR" {
380                handle_xx(
381                    state,
382                    Font::Bold,
383                    Font::Regular,
384                    &mut reader,
385                    lp,
386                    &mut break_text,
387                    &mut stdout,
388                    basepath,
389                );
390            } else if macro_name == ".EE" || macro_name == ".fi" {
391                if state.in_block == Some("pre") {
392                    writeln!(stdout, "</pre>").ok();
393                    state.in_block = None;
394                } else {
395                    eprintln!(
396                        "mantohtml: '{}' with no '.EX' or '.nf' on line {} of '{}'.",
397                        macro_name,
398                        reader.line_number(),
399                        filename
400                    );
401                }
402            } else if macro_name == ".EX" || macro_name == ".nf" {
403                close_link_if(state, &mut stdout);
404                close_block_if(state, &mut stdout);
405                write!(stdout, "    <pre>").ok();
406                state.in_block = Some("pre");
407            } else if macro_name == ".HP" {
408                let mut lp2 = lp;
409                // Reason for fallback: HP macro indent defaults to 2.5em per groff man specification.
410                let indent = parse_measurement(&mut lp2, 'n')
411                    .unwrap_or_else(|| "2.5em".into());
412                close_link_if(state, &mut stdout);
413                close_block_if(state, &mut stdout);
414                write!(
415                    stdout,
416                    "    <p style=\"margin-left: {indent}; text-indent: -{indent};\">"
417                )
418                .ok();
419                state.in_block = Some("p");
420            } else if macro_name == ".I" {
421                let mut remainder = lp.to_owned();
422                if remainder.trim().is_empty()
423                    && let Some(next_line) = reader.man_gets()
424                {
425                    remainder = next_line;
426                }
427                push_font(state, Font::Italic, &mut stdout);
428                man_puts(state, &remainder, &mut stdout);
429                pop_font(state, &mut stdout);
430                writeln!(stdout, "{break_text}").ok();
431                break_text.clear();
432            } else if macro_name == ".IB" {
433                handle_xx(
434                    state,
435                    Font::Italic,
436                    Font::Bold,
437                    &mut reader,
438                    lp,
439                    &mut break_text,
440                    &mut stdout,
441                    basepath,
442                );
443            } else if macro_name == ".IP" {
444                let mut lp2 = lp;
445                // Reason for fallback: IP macro tag defaults to empty string if not supplied.
446                let tag = parse_value(&mut lp2).unwrap_or_default();
447                // Reason for fallback: IP macro indent defaults to 2.5em per groff man specification.
448                let indent = parse_measurement(&mut lp2, 'n')
449                    .unwrap_or_else(|| "2.5em".into());
450                close_link_if(state, &mut stdout);
451                if let Some(block) = state.in_block
452                    && block != "ul"
453                {
454                    writeln!(stdout, "</{block}>").ok();
455                    state.in_block = None;
456                }
457                if state.in_block.is_none() {
458                    writeln!(stdout, "    <ul>").ok();
459                    state.in_block = Some("ul");
460                }
461                let list_style = if tag == "\\(bu" || tag == "-" || tag == "*" {
462                    ""
463                } else {
464                    "list-style-type: none; "
465                };
466                write!(
467                    stdout,
468                    "    <li style=\"{list_style}margin-left: {indent};\">"
469                )
470                .ok();
471            } else if macro_name == ".IR" {
472                handle_xx(
473                    state,
474                    Font::Italic,
475                    Font::Regular,
476                    &mut reader,
477                    lp,
478                    &mut break_text,
479                    &mut stdout,
480                    basepath,
481                );
482            } else if macro_name == ".LP"
483                || macro_name == ".P"
484                || macro_name == ".PP"
485            {
486                close_link_if(state, &mut stdout);
487                close_block_if(state, &mut stdout);
488                write!(stdout, "    <p>").ok();
489                state.in_block = Some("p");
490            } else if macro_name == ".ME" || macro_name == ".UE" {
491                if state.in_link {
492                    writeln!(stdout, "</a>").ok();
493                    state.in_link = false;
494                }
495            } else if macro_name == ".MT" {
496                let mut lp2 = lp;
497                // Reason for fallback: MT macro email defaults to empty string if not supplied.
498                let email = parse_value(&mut lp2).unwrap_or_default();
499                if !email.is_empty() {
500                    write!(
501                        stdout,
502                        "<a href=\"mailto:{}\">",
503                        html_escape(&email)
504                    )
505                    .ok();
506                    state.in_link = true;
507                }
508            } else if macro_name == ".RB" {
509                handle_xx(
510                    state,
511                    Font::Regular,
512                    Font::Bold,
513                    &mut reader,
514                    lp,
515                    &mut break_text,
516                    &mut stdout,
517                    basepath,
518                );
519            } else if macro_name == ".RE" {
520                if state.indent > 0 {
521                    writeln!(stdout, "    </div>").ok();
522                    state.indent -= 1;
523                } else {
524                    eprintln!(
525                        "mantohtml: Unbalanced '.RE' on line {} of '{}'.",
526                        reader.line_number(),
527                        filename
528                    );
529                }
530            } else if macro_name == ".RS" {
531                let mut lp2 = lp;
532                // Reason for fallback: RS macro indent defaults to 0.5in per groff man specification.
533                let indent = parse_measurement(&mut lp2, 'n')
534                    .unwrap_or_else(|| "0.5in".into());
535                writeln!(stdout, "    <div style=\"margin-left: {indent};\">")
536                    .ok();
537                state.indent += 1;
538            } else if macro_name == ".SB" {
539                let mut remainder = lp.to_owned();
540                if remainder.trim().is_empty()
541                    && let Some(next_line) = reader.man_gets()
542                {
543                    remainder = next_line;
544                }
545                push_font(state, Font::SmallBold, &mut stdout);
546                man_puts(state, &remainder, &mut stdout);
547                pop_font(state, &mut stdout);
548                writeln!(stdout, "{break_text}").ok();
549                break_text.clear();
550            } else if macro_name == ".SH" {
551                close_link_if(state, &mut stdout);
552                close_block_if(state, &mut stdout);
553                html_heading(state, Heading::Section, lp, &mut stdout);
554            } else if macro_name == ".SM" {
555                let mut remainder = lp.to_owned();
556                if remainder.trim().is_empty()
557                    && let Some(next_line) = reader.man_gets()
558                {
559                    remainder = next_line;
560                }
561                push_font(state, Font::Small, &mut stdout);
562                man_puts(state, &remainder, &mut stdout);
563                pop_font(state, &mut stdout);
564                writeln!(stdout, "{break_text}").ok();
565                break_text.clear();
566            } else if macro_name == ".SS" {
567                close_link_if(state, &mut stdout);
568                close_block_if(state, &mut stdout);
569                html_heading(state, Heading::Subsection, lp, &mut stdout);
570            } else if macro_name == ".SY" {
571                if let Some(block) = state.in_block.take() {
572                    writeln!(stdout, "</{block}>").ok();
573                }
574                write!(stdout, "    <p style=\"font-family: monospace;\">")
575                    .ok();
576                state.in_block = Some("p");
577            } else if macro_name == ".TP" {
578                let mut lp2 = lp;
579                // Reason for fallback: TP macro indent defaults to 2.5em per groff man specification.
580                let indent = parse_measurement(&mut lp2, 'n')
581                    .unwrap_or_else(|| "2.5em".into());
582                close_link_if(state, &mut stdout);
583                close_block_if(state, &mut stdout);
584                write!(
585                    stdout,
586                    "    <p style=\"margin-left: {indent}; text-indent: -{indent};\">"
587                )
588                .ok();
589                state.in_block = Some("p");
590                break_text = "<br>".into();
591            } else if macro_name == ".UR" {
592                let mut lp2 = lp;
593                // Reason for fallback: UR macro url defaults to empty string if not supplied.
594                let url = parse_value(&mut lp2).unwrap_or_default();
595                if !url.is_empty() {
596                    write!(stdout, "<a href=\"{}\">", html_escape(&url)).ok();
597                    state.in_link = true;
598                }
599            } else if macro_name == ".YS" {
600                if state.in_block == Some("p") {
601                    writeln!(stdout, "</p>").ok();
602                    state.in_block = None;
603                } else {
604                    eprintln!(
605                        "mantohtml: '.YS' seen without prior '.SY' on line {} of '{}'.",
606                        reader.line_number(),
607                        filename
608                    );
609                }
610            } else if macro_name == ".br" {
611                writeln!(stdout, "<br>").ok();
612            } else if macro_name == ".in" {
613                let mut lp2 = lp;
614                if let Some(indent) = parse_measurement(&mut lp2, 'm') {
615                    writeln!(
616                        stdout,
617                        "    <div style=\"margin-left: {};\">",
618                        html_escape(&indent)
619                    )
620                    .ok();
621                    state.indent += 1;
622                } else if state.indent > 0 {
623                    writeln!(stdout, "    </div>").ok();
624                    state.indent -= 1;
625                } else {
626                    eprintln!(
627                        "mantohtml: '.in' seen without prior '.in INDENT' on line {} of '{}'.",
628                        reader.line_number(),
629                        filename
630                    );
631                }
632            } else if macro_name == ".sp" {
633                writeln!(stdout, "<br>&nbsp;<br>").ok();
634            } else {
635                eprintln!(
636                    "mantohtml: Unsupported command/macro '{}' on line {} of '{}'.",
637                    macro_name,
638                    reader.line_number(),
639                    filename
640                );
641            }
642        } else if th_seen {
643            // Text
644            if state.in_block.is_none() {
645                write!(stdout, "<p>").ok();
646                state.in_block = Some("p");
647            }
648            man_puts(state, &line, &mut stdout);
649            writeln!(stdout, "{break_text}").ok();
650            break_text.clear();
651        } else if !line.is_empty() && !warning {
652            eprintln!(
653                "mantohtml: Ignoring text before '.TH' on line {} of '{}'.",
654                reader.line_number(),
655                filename
656            );
657            warning = true;
658        }
659    }
660
661    if state.wrote_header {
662        html_footer(state, &mut stdout);
663    }
664
665    stdout.flush().ok();
666    Ok(())
667}
668
669// -----------------------------------------------------------------------------
670// ManReader replicating C man_gets
671// -----------------------------------------------------------------------------
672
673struct ManReader<'a> {
674    data: &'a [u8],
675    pos: usize,
676    line: usize,
677}
678
679impl<'a> ManReader<'a> {
680    fn new(data: &'a [u8]) -> Self {
681        Self {
682            data,
683            pos: 0,
684            line: 0,
685        }
686    }
687
688    fn line_number(&self) -> usize {
689        self.line
690    }
691
692    fn getc(&mut self) -> Option<u8> {
693        let c = self.data.get(self.pos).copied()?;
694        self.pos = self.pos.saturating_add(1);
695        Some(c)
696    }
697
698    fn ungetc(&mut self) {
699        if self.pos > 0 {
700            self.pos = self.pos.saturating_sub(1);
701        }
702    }
703
704    fn man_gets(&mut self) -> Option<String> {
705        let mut out = Vec::new();
706        while let Some(c) = self.getc() {
707            if c == b'\n' {
708                self.line = self.line.saturating_add(1);
709                break;
710            } else if c == b'\\' {
711                if let Some(nc) = self.getc() {
712                    if nc == b'\n' {
713                        // Continuation
714                        self.line = self.line.saturating_add(1);
715                        continue;
716                    } else if nc == b'"' {
717                        // Comment until end of line
718                        while let Some(cc) = self.getc() {
719                            if cc == b'\n' {
720                                self.line = self.line.saturating_add(1);
721                                break;
722                            }
723                        }
724                        break;
725                    }
726                    out.push(b'\\');
727                    out.push(nc);
728                } else {
729                    break;
730                }
731            } else {
732                out.push(c);
733            }
734        }
735
736        if out.is_empty() && self.pos >= self.data.len() {
737            None
738        } else {
739            Some(String::from_utf8_lossy(&out).to_string())
740        }
741    }
742}
743
744// -----------------------------------------------------------------------------
745// Helpers: HTML output
746// -----------------------------------------------------------------------------
747
748fn html_escape(s: &str) -> String {
749    let mut out = String::with_capacity(s.len());
750    for ch in s.chars() {
751        match ch {
752            '&' => out.push_str("&amp;"),
753            '<' => out.push_str("&lt;"),
754            // The original doesn't escape a couple things that I usually would
755            // '>' => out.push_str("&gt;"),
756            '"' => out.push_str("&quot;"),
757            // '\'' => out.push_str("&apos;"),
758            _ => out.push(ch),
759        }
760    }
761    out
762}
763
764fn html_anchor(s: &str) -> String {
765    let mut out = String::new();
766    let bytes = s.as_bytes();
767    let mut i = 0usize;
768    while let Some(&b) = bytes.get(i) {
769        let c = char::from(b);
770        if c.is_ascii_alphanumeric() || c == '.' || c == '-' {
771            out.push(c.to_ascii_lowercase());
772        } else if (c == '(' || c == ' ' || c == '\t')
773            && i.saturating_add(1) < bytes.len()
774            && !out.ends_with('-')
775        {
776            out.push('-');
777        }
778        i = i.saturating_add(1);
779        if out.len() >= 255 {
780            break;
781        }
782    }
783    out
784}
785
786fn html_header(state: &mut State, topic: &str, w: &mut impl Write) {
787    if state.wrote_header {
788        return;
789    }
790    state.wrote_header = true;
791    let _ = writeln!(w, "<!DOCTYPE html>");
792    let _ = writeln!(w, "<html>");
793    let _ = writeln!(w, "  <head>");
794
795    if let Some(css) = &state.css {
796        if css.starts_with("http://") || css.starts_with("https://") {
797            let _ = writeln!(
798                w,
799                "    <link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">",
800                html_escape(css)
801            );
802        } else {
803            let _ = writeln!(w, "    <style><!--");
804            if let Ok(text) = fs::read_to_string(css) {
805                let _ = write!(w, "{text}");
806            }
807            let _ = writeln!(w, "--></style>");
808        }
809    }
810    if let Some(author) = &state.author {
811        let _ = writeln!(
812            w,
813            "    <meta name=\"author\" content=\"{}\">",
814            html_escape(author)
815        );
816    }
817    if let Some(c) = &state.copyright {
818        let _ = writeln!(
819            w,
820            "    <meta name=\"copyright\" content=\"{}\">",
821            html_escape(c)
822        );
823    }
824    let _ = writeln!(
825        w,
826        "    <meta name=\"creator\" content=\"{} v{} convert_man_troff_to_html\">",
827        package_short_name(),
828        package_version()
829    );
830    if let Some(subject) = &state.subject {
831        let _ = writeln!(
832            w,
833            "    <meta name=\"subject\" content=\"{}\">",
834            html_escape(subject)
835        );
836    }
837    // Reason for fallback: header title defaults to topic parameter or generic "Documentation" if title is unassigned.
838    let title = state.title.as_deref().unwrap_or({
839        if topic.is_empty() {
840            "Documentation"
841        } else {
842            topic
843        }
844    });
845    let _ = writeln!(w, "    <title>{}</title>", html_escape(title));
846    let _ = writeln!(w, "  </head>");
847    let _ = writeln!(w, "  <body>");
848
849    if let Some(chapter) = &state.chapter {
850        let anchor = html_anchor(chapter);
851        let _ = writeln!(
852            w,
853            "    <h1 id=\"{}\">{}</h1>",
854            anchor,
855            html_escape(chapter)
856        );
857    }
858}
859
860fn html_footer(state: &mut State, w: &mut impl Write) {
861    if state.wrote_header {
862        let _ = writeln!(w, "  </body>");
863        let _ = writeln!(w, "</html>");
864        state.wrote_header = false;
865    }
866}
867
868fn push_font(state: &mut State, font: Font, w: &mut impl Write) {
869    if state.font == font && state.in_block.is_some() {
870        return;
871    }
872    // Close previous
873    if state.font != Font::Regular {
874        match state.font {
875            Font::Bold => {
876                let _ = write!(w, "</strong>");
877            }
878            Font::Italic => {
879                let _ = write!(w, "</em>");
880            }
881            Font::Small => {
882                let _ = write!(w, "</small>");
883            }
884            Font::SmallBold => {
885                let _ = write!(w, "</small>");
886            }
887            Font::Monospace => {
888                let _ = write!(w, "</pre>");
889            }
890            Font::Regular => (),
891        }
892    }
893    if state.in_block.is_none() {
894        let _ = write!(w, "<p>");
895        state.in_block = Some("p");
896    }
897    match font {
898        Font::Regular => (),
899        Font::Bold => {
900            let _ = write!(w, "<strong>");
901        }
902        Font::Italic => {
903            let _ = write!(w, "<em>");
904        }
905        Font::Small => {
906            let _ = write!(w, "<small>");
907        }
908        Font::SmallBold => {
909            let _ = write!(w, "<small style=\"font-weight: bold;\">");
910        }
911        Font::Monospace => {
912            let _ = write!(w, "<pre>");
913        }
914    }
915    state.font = font;
916}
917
918fn pop_font(state: &mut State, w: &mut impl Write) {
919    push_font(state, Font::Regular, w);
920}
921
922fn html_heading(
923    state: &mut State,
924    heading: Heading,
925    raw: &str,
926    w: &mut impl Write,
927) {
928    // Regenerate capitalized heading for section/subsection
929    let mut title = raw.trim().to_string();
930    if heading != Heading::Topic {
931        title = capitalize_heading_words(&title);
932    }
933
934    if state.in_link {
935        let _ = writeln!(w, "</a>");
936        state.in_link = false;
937    }
938    if let Some(block) = state.in_block.take() {
939        let _ = writeln!(w, "</{block}>");
940    }
941
942    let heading_u8: u8 = heading.into();
943    let hlevel = if state.chapter.is_some() {
944        heading_u8.saturating_add(2)
945    } else {
946        heading_u8.saturating_add(1)
947    };
948
949    match heading {
950        Heading::Topic => {
951            state.atopic = html_anchor(raw);
952            let _ = write!(
953                w,
954                "    <h{} id=\"{}\">",
955                hlevel,
956                html_escape(&state.atopic)
957            );
958        }
959        Heading::Section => {
960            state.asection = html_anchor(raw);
961            let _ = write!(
962                w,
963                "    <h{} id=\"{}.{}\">",
964                hlevel,
965                html_escape(&state.atopic),
966                html_escape(&state.asection)
967            );
968        }
969        Heading::Subsection => {
970            let subsection = html_anchor(raw);
971            let _ = write!(
972                w,
973                "    <h{} id=\"{}.{}.{}\">",
974                hlevel,
975                html_escape(&state.atopic),
976                html_escape(&state.asection),
977                html_escape(&subsection)
978            );
979        }
980    }
981
982    man_puts(state, &title, w);
983    let _ = writeln!(w, "</h{hlevel}>");
984}
985
986fn capitalize_heading_words(s: &str) -> String {
987    let mut title = s.as_bytes().to_vec();
988    // Capitalize first letter of each word except "a", "and", "or", "the"
989    let mut i = 0usize;
990    while i < title.len() {
991        let Some(&ch) = title.get(i) else {
992            break;
993        };
994        if (char::from(ch)).is_ascii_alphabetic() {
995            // Check if this is the start of a word (first letter or preceded by non-alpha)
996            let is_start = i == 0;
997            // Check for exception words: "a ", "and ", "or ", "the "
998            let is_exception =
999                title.get(i..i.saturating_add(2)) == Some(b"a ".as_slice())
1000                    || title.get(i..i.saturating_add(4))
1001                        == Some(b"and ".as_slice())
1002                    || title.get(i..i.saturating_add(3))
1003                        == Some(b"or ".as_slice())
1004                    || title.get(i..i.saturating_add(4))
1005                        == Some(b"the ".as_slice());
1006
1007            if is_start || !is_exception {
1008                // Capitalize first letter
1009                if let Some(elem) = title.get_mut(i) {
1010                    *elem = ch.to_ascii_uppercase();
1011                }
1012            }
1013
1014            // Lowercase the rest of the word
1015            let mut j = i.saturating_add(1);
1016            while j < title.len()
1017                && title
1018                    .get(j)
1019                    .copied()
1020                    .map(char::from)
1021                    .is_some_and(|c| c.is_ascii_alphabetic())
1022            {
1023                if let Some(elem) = title.get_mut(j) {
1024                    *elem = elem.to_ascii_lowercase();
1025                }
1026                j = j.saturating_add(1);
1027            }
1028            i = j;
1029        } else {
1030            i = i.saturating_add(1);
1031        }
1032    }
1033    // Reason for fallback: invalid UTF-8 title bytes default to empty string.
1034    String::from_utf8(title).unwrap_or_default()
1035}
1036
1037// -----------------------------------------------------------------------------
1038// Macro handling similar to man_xx
1039// -----------------------------------------------------------------------------
1040
1041#[expect(clippy::too_many_arguments, reason = "Legacy macro conversion helper")]
1042fn handle_xx(
1043    state: &mut State,
1044    a: Font,
1045    b: Font,
1046    reader: &mut ManReader,
1047    lp: &str,
1048    break_text: &mut String,
1049    w: &mut impl Write,
1050    basepath: Option<&str>,
1051) {
1052    let mut line_rest = lp.to_owned();
1053    if line_rest.trim().is_empty()
1054        && let Some(next_line_r) = reader.man_gets()
1055    {
1056        line_rest = next_line_r; // move the owned String
1057    }
1058    let mut line_rest = line_rest.as_str();
1059    let mut words = Vec::new();
1060    {
1061        while let Some(val) = parse_value(&mut line_rest) {
1062            words.push(val);
1063        }
1064    }
1065
1066    let have_basepath = basepath.is_some();
1067    let basepath = basepath.unwrap_or("");
1068    let original_font = state.font;
1069    let mut use_a = true;
1070    let mut idx = 0usize;
1071    while idx < words.len() {
1072        let Some(word) = words.get(idx) else {
1073            break;
1074        };
1075        // Attempt link detection for ".BR name (section)"
1076        let mut have_link = false;
1077        if a == Font::Bold
1078            && b == Font::Regular
1079            && use_a
1080            && idx.saturating_add(1) < words.len()
1081            && words
1082                .get(idx.saturating_add(1))
1083                .is_some_and(|w| w.starts_with('(') && w.contains(')'))
1084        {
1085            if let Some(sec) = words.get(idx.saturating_add(1)) {
1086                if let Some(endp) = sec.find(')') {
1087                    let section = sec.get(1..endp).unwrap_or("");
1088                    if section
1089                        .chars()
1090                        .next()
1091                        .is_some_and(|c| c.is_ascii_digit())
1092                        && have_basepath
1093                    {
1094                        let manfile = format!("{basepath}/{word}.{section}");
1095                        if Path::new(&manfile).exists() {
1096                            let _ = write!(
1097                                w,
1098                                "<a href=\"{}.html\">",
1099                                html_escape(word)
1100                            );
1101                            have_link = true;
1102                        }
1103                    }
1104                }
1105            }
1106        }
1107
1108        push_font(state, if use_a { a } else { b }, w);
1109        man_puts(state, word, w);
1110
1111        if have_link {
1112            if idx.saturating_add(1) < words.len() {
1113                idx = idx.saturating_add(1);
1114                push_font(state, b, w);
1115                if let Some(w_next) = words.get(idx) {
1116                    man_puts(state, w_next, w);
1117                }
1118            }
1119            let _ = write!(w, "</a>");
1120        } else {
1121            use_a = !use_a;
1122        }
1123        idx = idx.saturating_add(1);
1124    }
1125
1126    push_font(state, original_font, w);
1127    let _ = writeln!(w);
1128    if !break_text.is_empty() {
1129        let _ = writeln!(w, "{break_text}");
1130        break_text.clear();
1131    }
1132    let _ = writeln!(w);
1133}
1134
1135// -----------------------------------------------------------------------------
1136// man_puts + escape/sequence handling (subset of original logic)
1137// -----------------------------------------------------------------------------
1138
1139fn flush_fragment(start: usize, end: usize, w: &mut impl Write, bytes: &[u8]) {
1140    if end > start {
1141        if let Some(slice) = bytes.get(start..end) {
1142            let text = String::from_utf8_lossy(slice);
1143            let _ = write!(w, "{}", html_escape(&text));
1144        }
1145    }
1146}
1147
1148fn man_puts(state: &mut State, s: &str, w: &mut impl Write) {
1149    let mut i = 0usize;
1150    let bytes = s.as_bytes();
1151    let mut fragment_start = 0usize;
1152
1153    while let Some(&b) = bytes.get(i) {
1154        if b == b'\\' {
1155            if bytes.get(i.saturating_add(1)).is_some() {
1156                flush_fragment(fragment_start, i, w, bytes);
1157                i = i.saturating_add(1);
1158
1159                #[allow(
1160                    clippy::expect_used,
1161                    reason = "i < bytes.len() guaranteed by preceding is_some check"
1162                )]
1163                let c = char::from(
1164                    *bytes
1165                        .get(i)
1166                        .expect("i < bytes.len() guaranteed by is_some check"),
1167                );
1168                match c {
1169                    'f' => {
1170                        if let Some(&b2) = bytes.get(i.saturating_add(1)) {
1171                            i = i.saturating_add(1);
1172                            let fch = char::from(b2);
1173                            match fch {
1174                                'R' | 'P' => push_font(state, Font::Regular, w),
1175                                'b' | 'B' => push_font(state, Font::Bold, w),
1176                                'i' | 'I' => push_font(state, Font::Italic, w),
1177                                _ => {
1178                                    eprintln!(
1179                                        "mantohtml: Unknown font '\\f{fch}' ignored."
1180                                    );
1181                                }
1182                            }
1183                            i = i.saturating_add(1);
1184                        } else {
1185                            i = i.saturating_add(1);
1186                        }
1187                    }
1188                    '*' => {
1189                        i = i.saturating_add(1);
1190                        if let Some(&bch) = bytes.get(i) {
1191                            let ch = char::from(bch);
1192                            if ch == '(' {
1193                                i = i.saturating_add(1);
1194                                if let (Some(&bm1), Some(&bm2)) = (
1195                                    bytes.get(i),
1196                                    bytes.get(i.saturating_add(1)),
1197                                ) {
1198                                    let m1 = char::from(bm1);
1199                                    let m2 = char::from(bm2);
1200                                    let macro_id = format!("{m1}{m2}");
1201                                    match macro_id.as_str() {
1202                                        "aq" => {
1203                                            let _ = write!(w, "'");
1204                                        }
1205                                        "dq" => {
1206                                            let _ = write!(w, "&quot;");
1207                                        }
1208                                        "lq" => {
1209                                            let _ = write!(w, "&ldquo;");
1210                                        }
1211                                        "rq" => {
1212                                            let _ = write!(w, "&rdquo;");
1213                                        }
1214                                        "Tm" => {
1215                                            let _ = write!(w, "<sup>TM</sup>");
1216                                        }
1217                                        _ => {
1218                                            eprintln!(
1219                                                "mantohtml: Unknown macro '\\*({m1}{m2})' ignored."
1220                                            );
1221                                        }
1222                                    }
1223                                    i = i.saturating_add(2);
1224                                }
1225                            } else {
1226                                match ch {
1227                                    'R' => {
1228                                        let _ = write!(w, "&reg;");
1229                                    }
1230                                    _ => {
1231                                        eprintln!(
1232                                            "mantohtml: Unknown macro '\\*{ch}' ignored."
1233                                        );
1234                                    }
1235                                }
1236                                i = i.saturating_add(1);
1237                            }
1238                        }
1239                    }
1240                    '(' => {
1241                        // \(... style
1242                        if let Some(seq) = bytes.get(i..i.saturating_add(3)) {
1243                            let token = String::from_utf8_lossy(seq);
1244                            match token.as_ref() {
1245                                "(bu" => {
1246                                    let _ = write!(w, "&middot;");
1247                                }
1248                                "(em" => {
1249                                    let _ = write!(w, "&mdash;");
1250                                }
1251                                "(en" => {
1252                                    let _ = write!(w, "&ndash;");
1253                                }
1254                                "(ga" => {
1255                                    let _ = write!(w, "`");
1256                                }
1257                                "(ha" => {
1258                                    let _ = write!(w, "^");
1259                                }
1260                                "(ti" => {
1261                                    let _ = write!(w, "~");
1262                                }
1263                                _ => {
1264                                    let _ =
1265                                        write!(w, "{}", html_escape(&token));
1266                                }
1267                            }
1268                            i = i.saturating_add(3);
1269                        } else {
1270                            // Just treat literally
1271                            let _ = write!(w, "(");
1272                            i = i.saturating_add(1);
1273                        }
1274                    }
1275                    '[' => {
1276                        // \[xx] style
1277                        let mut j = i;
1278                        while let Some(&bj) = bytes.get(j) {
1279                            if bj == b']' {
1280                                break;
1281                            }
1282                            j = j.saturating_add(1);
1283                        }
1284
1285                        if matches!(bytes.get(j), Some(b']')) {
1286                            #[allow(
1287                                clippy::expect_used,
1288                                reason = "i + 1 <= j < bytes.len() established by bracket scan"
1289                            )]
1290                            let token_bytes =
1291                                bytes.get(i.saturating_add(1)..j).expect(
1292                                    "i + 1 <= j < bytes.len() in bracket scan",
1293                                );
1294                            match token_bytes {
1295                                b"aq" => {
1296                                    let _ = write!(w, "'");
1297                                }
1298                                b"co" => {
1299                                    let _ = write!(w, "&copy;");
1300                                }
1301                                b"cq" => {
1302                                    let _ = write!(w, "&rsquo;");
1303                                }
1304                                b"de" => {
1305                                    let _ = write!(w, "&deg;");
1306                                }
1307                                b"dq" => {
1308                                    let _ = write!(w, "&quot;");
1309                                }
1310                                b"lq" => {
1311                                    let _ = write!(w, "&ldquo;");
1312                                }
1313                                b"mc" => {
1314                                    let _ = write!(w, "&mu;");
1315                                }
1316                                b"oq" => {
1317                                    let _ = write!(w, "&lsquo;");
1318                                }
1319                                b"rg" => {
1320                                    let _ = write!(w, "&reg;");
1321                                }
1322                                b"rq" => {
1323                                    let _ = write!(w, "&rdquo;");
1324                                }
1325                                b"tm" => {
1326                                    let _ = write!(w, "<sup>TM</sup>");
1327                                }
1328                                // Unknown, output literally
1329                                _ => {
1330                                    let token =
1331                                        String::from_utf8_lossy(token_bytes);
1332                                    let _ = write!(
1333                                        w,
1334                                        "\\[{}]",
1335                                        html_escape(&token)
1336                                    );
1337                                }
1338                            }
1339                            i = j.saturating_add(1);
1340                        } else {
1341                            // Unterminated, output literally
1342                            let _ = write!(w, "\\[");
1343                            i = i.saturating_add(1);
1344                        }
1345                    }
1346                    'e' => {
1347                        // Escaped backslash
1348                        let _ = write!(w, "\\");
1349                        i = i.saturating_add(1);
1350                    }
1351                    // Numeric escape like \123 (octal-ish in original)
1352                    d if d.is_ascii_digit() => {
1353                        let mut num = String::new();
1354                        num.push(d);
1355                        i = i.saturating_add(1);
1356
1357                        if let Some(&b2) = bytes.get(i) {
1358                            let c2 = char::from(b2);
1359                            if c2.is_ascii_digit() {
1360                                num.push(c2);
1361                                i = i.saturating_add(1);
1362                            }
1363                        }
1364                        if let Some(&b3) = bytes.get(i) {
1365                            let c3 = char::from(b3);
1366                            if c3.is_ascii_digit() {
1367                                num.push(c3);
1368                                i = i.saturating_add(1);
1369                            }
1370                        }
1371
1372                        if let Ok(v) = i32::from_str_radix(&num, 8) {
1373                            let _ = write!(w, "&#{v};");
1374                        }
1375                    }
1376                    other => {
1377                        // Pass through certain escapes; warn on unknown
1378                        match other {
1379                            '\\' | '"' | '\'' | '-' | ' ' => {
1380                                let _ = write!(w, "{other}");
1381                            }
1382                            _ => {
1383                                eprintln!(
1384                                    "mantohtml: Unrecognized escape '\\{other}' ignored."
1385                                );
1386                                let _ = write!(w, "\\{other}");
1387                            }
1388                        }
1389                        i = i.saturating_add(1);
1390                    }
1391                }
1392
1393                fragment_start = i;
1394            } else {
1395                i = i.saturating_add(1);
1396            }
1397        } else if {
1398            #[allow(
1399                clippy::expect_used,
1400                reason = "i < bytes.len() guaranteed by loop condition"
1401            )]
1402            let rem = bytes.get(i..).expect("i < bytes.len() in loop");
1403            starts_with_url(rem)
1404        } {
1405            flush_fragment(fragment_start, i, w, bytes);
1406            #[allow(
1407                clippy::expect_used,
1408                reason = "i < bytes.len() guaranteed by loop condition"
1409            )]
1410            let rem = bytes.get(i..).expect("i < bytes.len() in loop");
1411            let (url, consumed) = extract_url(rem);
1412            let _ = write!(
1413                w,
1414                "<a href=\"{}\">{}</a>",
1415                html_escape(&url),
1416                html_escape(&url)
1417            );
1418            i = i.saturating_add(consumed);
1419            fragment_start = i;
1420        } else if matches!(b, b'<' | b'&' | b'"') {
1421            flush_fragment(fragment_start, i, w, bytes);
1422            let ch = char::from(b);
1423            let _ = write!(w, "{}", html_escape(&ch.to_string()));
1424            i = i.saturating_add(1);
1425            fragment_start = i;
1426        } else {
1427            i = i.saturating_add(1);
1428        }
1429    }
1430
1431    flush_fragment(fragment_start, i, w, bytes);
1432}
1433
1434fn starts_with_url(slice: &[u8]) -> bool {
1435    // Reason for fallback: invalid UTF-8 slice defaults to empty string for URL detection.
1436    let s = std::str::from_utf8(slice).unwrap_or("");
1437    s.starts_with("http://") || s.starts_with("https://")
1438}
1439
1440/// Get URL from a chunk of bytes. If it is not valid UTF-8, returns empty string.
1441fn extract_url(slice: &[u8]) -> (String, usize) {
1442    // Reason for fallback: invalid UTF-8 slice defaults to empty string for URL extraction.
1443    let s = std::str::from_utf8(slice).unwrap_or("");
1444    let mut end = 0usize;
1445    let chars: Vec<char> = s.chars().collect();
1446    while end < chars.len() {
1447        let Some(&c) = chars.get(end) else {
1448            break;
1449        };
1450        if c.is_whitespace() {
1451            break;
1452        }
1453        if ",.)".contains(c)
1454            && (end.saturating_add(1) == chars.len()
1455                || chars
1456                    .get(end.saturating_add(1))
1457                    .copied()
1458                    .is_none_or(|c| c.is_whitespace() || c == '\0'))
1459        {
1460            break;
1461        }
1462        end = end.saturating_add(1);
1463    }
1464    #[allow(
1465        clippy::expect_used,
1466        reason = "end <= chars.len() guaranteed by while end < chars.len() loop"
1467    )]
1468    let url: String = chars
1469        .get(..end)
1470        .expect("end <= chars.len() in extract_url")
1471        .iter()
1472        .collect();
1473    let len = url.len();
1474    (url, len)
1475}
1476
1477// -----------------------------------------------------------------------------
1478// Parsing helpers (parse_value / parse_measurement)
1479// -----------------------------------------------------------------------------
1480
1481#[expect(
1482    clippy::expect_used,
1483    clippy::unwrap_in_result,
1484    reason = "String slices are guaranteed to be valid char boundaries by preceding starts_with or chars().next() checks"
1485)]
1486fn parse_value(line: &mut &str) -> Option<String> {
1487    let mut l = line.trim_start();
1488    if l.is_empty() {
1489        return None;
1490    }
1491    let mut out = String::new();
1492    if l.starts_with('"') {
1493        l = l.get(1..).expect("starts with quote");
1494        while !l.is_empty() {
1495            let c = l.chars().next()?;
1496            if c == '"' {
1497                l = l.get(1..).expect("c == quote");
1498                break;
1499            } else if c == '\\' {
1500                l = l.get(1..).expect("c == backslash");
1501                if let Some(nextc) = l.chars().next() {
1502                    out.push(nextc);
1503                    l = l.get(nextc.len_utf8()..).expect("valid char boundary");
1504                }
1505            } else {
1506                out.push(c);
1507                l = l.get(c.len_utf8()..).expect("valid char boundary");
1508            }
1509        }
1510    } else {
1511        while !l.is_empty() {
1512            let c = l.chars().next()?;
1513            if c.is_whitespace() {
1514                break;
1515            }
1516            out.push(c);
1517            l = l.get(c.len_utf8()..).expect("valid char boundary");
1518            if c == '\\' && !l.is_empty() {
1519                // Keep escaped char
1520                let c2 = l.chars().next()?;
1521                out.push(c2);
1522                l = l.get(c2.len_utf8()..).expect("valid char boundary");
1523            }
1524        }
1525    }
1526    *line = l.trim_start();
1527    Some(out)
1528}
1529
1530fn parse_measurement(line: &mut &str, defunit: char) -> Option<String> {
1531    let val = parse_value(line)?;
1532    if val.is_empty() {
1533        return None;
1534    }
1535    let s = val.clone();
1536    let unit = s
1537        .chars()
1538        .next_back()
1539        .filter(char::is_ascii_alphabetic)
1540        // Reason for fallback: unit char defaults to specified defunit (e.g. 'n') if last char is not alphabetic.
1541        .unwrap_or(defunit);
1542
1543    let number_part =
1544        if s.chars().last().is_some_and(|c| c.is_ascii_alphabetic()) {
1545            let mut chars = s.chars();
1546            chars.next_back();
1547            chars.as_str().to_string()
1548        } else {
1549            s.clone()
1550        };
1551
1552    // Reason for fallback: number parsing defaults to 0.0 if number_part is non-numeric.
1553    let parsed = number_part.parse::<f64>().unwrap_or(0.0);
1554
1555    let converted = match unit {
1556        'c' => format!("{number_part}cm"),
1557        'f' => format!("{:.1}%", 100.0 * parsed / 65536.0),
1558        'i' => format!("{number_part}in"),
1559        'm' => format!("{number_part}em"),
1560        'M' => format!("{:.2}em", parsed * 0.01),
1561        'n' => format!("{}em", parsed * 0.5),
1562        'P' => format!("{number_part}pc"),
1563        'p' => format!("{number_part}pt"),
1564        's' => format!("{:.1}%", 100.0 * parsed),
1565        'u' => format!("{number_part}px"),
1566        'v' => number_part,
1567        _ => return None,
1568    };
1569
1570    Some(converted)
1571}
1572
1573// -----------------------------------------------------------------------------
1574// Utility
1575// -----------------------------------------------------------------------------
1576
1577fn close_block_if(state: &mut State, w: &mut impl Write) {
1578    if let Some(block) = state.in_block.take() {
1579        let _ = writeln!(w, "</{block}>");
1580    }
1581}
1582
1583fn close_link_if(state: &mut State, w: &mut impl Write) {
1584    if state.in_link {
1585        let _ = writeln!(w, "</a>");
1586        state.in_link = false;
1587    }
1588}
1589
1590fn usage(bad: Option<&str>) {
1591    if let Some(opt) = bad {
1592        eprintln!("Unknown option: {opt}");
1593    }
1594    println!("Usage: mantohtml [OPTIONS] MAN-FILE [... MAN-FILE] >HTML-FILE");
1595    println!("Options:");
1596    println!("   --author 'AUTHOR'        Set author metadata");
1597    println!("   --chapter 'CHAPTER'      Set chapter (H1 heading)");
1598    println!("   --copyright 'COPYRIGHT'  Set copyright metadata");
1599    println!("   --css CSS-FILE-OR-URL    Use named stylesheet");
1600    println!("   --help                   Show help");
1601    println!("   --subject 'SUBJECT'      Set subject metadata");
1602    println!("   --title 'TITLE'          Set output title");
1603    println!("   --version                Show version");
1604}
1605
1606#[cfg(test)]
1607#[allow(
1608    clippy::panic,
1609    clippy::expect_used,
1610    clippy::unwrap_used,
1611    clippy::unwrap_in_result,
1612    clippy::panic_in_result_fn,
1613    clippy::indexing_slicing,
1614    clippy::arithmetic_side_effects,
1615    reason = "Standard repository test boilerplate"
1616)]
1617mod tests {
1618    use ctb_formats_utilities::assert_vec_u8_ok_eq_no_warnings;
1619
1620    use super::*;
1621
1622    #[crate::ctb_test]
1623    fn test_html_escape() {
1624        assert_eq!(html_escape("Hello & World"), "Hello &amp; World");
1625        // > is not escaped by this function
1626        assert_eq!(html_escape("<tag>"), "&lt;tag>");
1627        assert_eq!(html_escape("\"quote\""), "&quot;quote&quot;");
1628        assert_eq!(html_escape("No special chars"), "No special chars");
1629    }
1630
1631    #[crate::ctb_test]
1632    fn test_html_anchor() {
1633        assert_eq!(html_anchor("Section 1.2"), "section-1.2");
1634        assert_eq!(html_anchor("My-Function()"), "my-function-");
1635        assert_eq!(html_anchor("A B C"), "a-b-c");
1636        assert_eq!(html_anchor("!@#$%^&*()"), "-");
1637    }
1638
1639    #[crate::ctb_test]
1640    fn test_capitalize_heading_words() {
1641        assert_eq!(
1642            capitalize_heading_words("the quick brown fox"),
1643            "The Quick Brown Fox"
1644        );
1645        assert_eq!(
1646            capitalize_heading_words("a tale of two cities"),
1647            "A Tale Of Two Cities"
1648        );
1649        assert_eq!(
1650            capitalize_heading_words("a tale or two cities"),
1651            "A Tale or Two Cities"
1652        );
1653        assert_eq!(
1654            capitalize_heading_words("and then there were none"),
1655            "And Then There Were None"
1656        );
1657    }
1658
1659    #[crate::ctb_test]
1660    fn test_starts_with_url() {
1661        assert!(starts_with_url(b"http://example.com"));
1662        assert!(starts_with_url(b"https://example.com"));
1663        assert!(!starts_with_url(b"ftp://example.com"));
1664        assert!(!starts_with_url(b"Just some text"));
1665    }
1666
1667    #[crate::ctb_test]
1668    fn test_extract_url() {
1669        let (url, len) =
1670            extract_url(b"http://example.com/path?query=1 more text");
1671        assert_eq!(url, "http://example.com/path?query=1");
1672        assert_eq!(len, url.len());
1673
1674        let (url2, len2) = extract_url(b"https://example.com.");
1675        assert_eq!(url2, "https://example.com");
1676        assert_eq!(len2, url2.len());
1677
1678        let (url3, len3) = extract_url(b"https://example.com)");
1679        assert_eq!(url3, "https://example.com");
1680        assert_eq!(len3, url3.len());
1681    }
1682
1683    #[crate::ctb_test]
1684    fn test_convert_from_fixture() {
1685        let fixture_expected =
1686            get_troff_data("fixtures/out.html").expect("Could not get fixture");
1687        // replace bytes `ctoolbox v0.1.0 convert_man_troff_to_html` with the actual version
1688        let fixture_expected = string::bytes_str_replace(
1689            &fixture_expected,
1690            b"ctoolbox v0.1.0 convert_man_troff_to_html",
1691            format!(
1692                "ctoolbox v{} convert_man_troff_to_html",
1693                package_version()
1694            )
1695            .as_bytes(),
1696        );
1697        assert_vec_u8_ok_eq_no_warnings(
1698            &fixture_expected,
1699            convert_man_troff_to_html(
1700                get_troff_data("fixtures/in.1").expect("Could not get fixture"),
1701            ),
1702        );
1703    }
1704}
1705
1706/*
1707
1708
1709                                Apache License
1710                          Version 2.0, January 2004
1711                       http://www.apache.org/licenses/
1712
1713  TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1714
1715  1. Definitions.
1716
1717     "License" shall mean the terms and conditions for use, reproduction,
1718     and distribution as defined by Sections 1 through 9 of this document.
1719
1720     "Licensor" shall mean the copyright owner or entity authorized by
1721     the copyright owner that is granting the License.
1722
1723     "Legal Entity" shall mean the union of the acting entity and all
1724     other entities that control, are controlled by, or are under common
1725     control with that entity. For the purposes of this definition,
1726     "control" means (i) the power, direct or indirect, to cause the
1727     direction or management of such entity, whether by contract or
1728     otherwise, or (ii) ownership of fifty percent (50%) or more of the
1729     outstanding shares, or (iii) beneficial ownership of such entity.
1730
1731     "You" (or "Your") shall mean an individual or Legal Entity
1732     exercising permissions granted by this License.
1733
1734     "Source" form shall mean the preferred form for making modifications,
1735     including but not limited to software source code, documentation
1736     source, and configuration files.
1737
1738     "Object" form shall mean any form resulting from mechanical
1739     transformation or translation of a Source form, including but
1740     not limited to compiled object code, generated documentation,
1741     and conversions to other media types.
1742
1743     "Work" shall mean the work of authorship, whether in Source or
1744     Object form, made available under the License, as indicated by a
1745     copyright notice that is included in or attached to the work
1746     (an example is provided in the Appendix below).
1747
1748     "Derivative Works" shall mean any work, whether in Source or Object
1749     form, that is based on (or derived from) the Work and for which the
1750     editorial revisions, annotations, elaborations, or other modifications
1751     represent, as a whole, an original work of authorship. For the purposes
1752     of this License, Derivative Works shall not include works that remain
1753     separable from, or merely link (or bind by name) to the interfaces of,
1754     the Work and Derivative Works thereof.
1755
1756     "Contribution" shall mean any work of authorship, including
1757     the original version of the Work and any modifications or additions
1758     to that Work or Derivative Works thereof, that is intentionally
1759     submitted to Licensor for inclusion in the Work by the copyright owner
1760     or by an individual or Legal Entity authorized to submit on behalf of
1761     the copyright owner. For the purposes of this definition, "submitted"
1762     means any form of electronic, verbal, or written communication sent
1763     to the Licensor or its representatives, including but not limited to
1764     communication on electronic mailing lists, source code control systems,
1765     and issue tracking systems that are managed by, or on behalf of, the
1766     Licensor for the purpose of discussing and improving the Work, but
1767     excluding communication that is conspicuously marked or otherwise
1768     designated in writing by the copyright owner as "Not a Contribution."
1769
1770     "Contributor" shall mean Licensor and any individual or Legal Entity
1771     on behalf of whom a Contribution has been received by Licensor and
1772     subsequently incorporated within the Work.
1773
1774  2. Grant of Copyright License. Subject to the terms and conditions of
1775     this License, each Contributor hereby grants to You a perpetual,
1776     worldwide, non-exclusive, no-charge, royalty-free, irrevocable
1777     copyright license to reproduce, prepare Derivative Works of,
1778     publicly display, publicly perform, sublicense, and distribute the
1779     Work and such Derivative Works in Source or Object form.
1780
1781  3. Grant of Patent License. Subject to the terms and conditions of
1782     this License, each Contributor hereby grants to You a perpetual,
1783     worldwide, non-exclusive, no-charge, royalty-free, irrevocable
1784     (except as stated in this section) patent license to make, have made,
1785     use, offer to sell, sell, import, and otherwise transfer the Work,
1786     where such license applies only to those patent claims licensable
1787     by such Contributor that are necessarily infringed by their
1788     Contribution(s) alone or by combination of their Contribution(s)
1789     with the Work to which such Contribution(s) was submitted. If You
1790     institute patent litigation against any entity (including a
1791     cross-claim or counterclaim in a lawsuit) alleging that the Work
1792     or a Contribution incorporated within the Work constitutes direct
1793     or contributory patent infringement, then any patent licenses
1794     granted to You under this License for that Work shall terminate
1795     as of the date such litigation is filed.
1796
1797  4. Redistribution. You may reproduce and distribute copies of the
1798     Work or Derivative Works thereof in any medium, with or without
1799     modifications, and in Source or Object form, provided that You
1800     meet the following conditions:
1801
1802     (a) You must give any other recipients of the Work or
1803         Derivative Works a copy of this License; and
1804
1805     (b) You must cause any modified files to carry prominent notices
1806         stating that You changed the files; and
1807
1808     (c) You must retain, in the Source form of any Derivative Works
1809         that You distribute, all copyright, patent, trademark, and
1810         attribution notices from the Source form of the Work,
1811         excluding those notices that do not pertain to any part of
1812         the Derivative Works; and
1813
1814     (d) If the Work includes a "NOTICE" text file as part of its
1815         distribution, then any Derivative Works that You distribute must
1816         include a readable copy of the attribution notices contained
1817         within such NOTICE file, excluding those notices that do not
1818         pertain to any part of the Derivative Works, in at least one
1819         of the following places: within a NOTICE text file distributed
1820         as part of the Derivative Works; within the Source form or
1821         documentation, if provided along with the Derivative Works; or,
1822         within a display generated by the Derivative Works, if and
1823         wherever such third-party notices normally appear. The contents
1824         of the NOTICE file are for informational purposes only and
1825         do not modify the License. You may add Your own attribution
1826         notices within Derivative Works that You distribute, alongside
1827         or as an addendum to the NOTICE text from the Work, provided
1828         that such additional attribution notices cannot be construed
1829         as modifying the License.
1830
1831     You may add Your own copyright statement to Your modifications and
1832     may provide additional or different license terms and conditions
1833     for use, reproduction, or distribution of Your modifications, or
1834     for any such Derivative Works as a whole, provided Your use,
1835     reproduction, and distribution of the Work otherwise complies with
1836     the conditions stated in this License.
1837
1838  5. Submission of Contributions. Unless You explicitly state otherwise,
1839     any Contribution intentionally submitted for inclusion in the Work
1840     by You to the Licensor shall be under the terms and conditions of
1841     this License, without any additional terms or conditions.
1842     Notwithstanding the above, nothing herein shall supersede or modify
1843     the terms of any separate license agreement you may have executed
1844     with Licensor regarding such Contributions.
1845
1846  6. Trademarks. This License does not grant permission to use the trade
1847     names, trademarks, service marks, or product names of the Licensor,
1848     except as required for reasonable and customary use in describing the
1849     origin of the Work and reproducing the content of the NOTICE file.
1850
1851  7. Disclaimer of Warranty. Unless required by applicable law or
1852     agreed to in writing, Licensor provides the Work (and each
1853     Contributor provides its Contributions) on an "AS IS" BASIS,
1854     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
1855     implied, including, without limitation, any warranties or conditions
1856     of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
1857     PARTICULAR PURPOSE. You are solely responsible for determining the
1858     appropriateness of using or redistributing the Work and assume any
1859     risks associated with Your exercise of permissions under this License.
1860
1861  8. Limitation of Liability. In no event and under no legal theory,
1862     whether in tort (including negligence), contract, or otherwise,
1863     unless required by applicable law (such as deliberate and grossly
1864     negligent acts) or agreed to in writing, shall any Contributor be
1865     liable to You for damages, including any direct, indirect, special,
1866     incidental, or consequential damages of any character arising as a
1867     result of this License or out of the use or inability to use the
1868     Work (including but not limited to damages for loss of goodwill,
1869     work stoppage, computer failure or malfunction, or any and all
1870     other commercial damages or losses), even if such Contributor
1871     has been advised of the possibility of such damages.
1872
1873  9. Accepting Warranty or Additional Liability. While redistributing
1874     the Work or Derivative Works thereof, You may choose to offer,
1875     and charge a fee for, acceptance of support, warranty, indemnity,
1876     or other liability obligations and/or rights consistent with this
1877     License. However, in accepting such obligations, You may act only
1878     on Your own behalf and on Your sole responsibility, not on behalf
1879     of any other Contributor, and only if You agree to indemnify,
1880     defend, and hold each Contributor harmless for any liability
1881     incurred by, or claims asserted against, such Contributor by reason
1882     of your accepting any such warranty or additional liability.
1883
1884  END OF TERMS AND CONDITIONS
1885
1886  APPENDIX: How to apply the Apache License to your work.
1887
1888     To apply the Apache License to your work, attach the following
1889     boilerplate notice, with the fields enclosed by brackets "[]"
1890     replaced with your own identifying information. (Don't include
1891     the brackets!)  The text should be enclosed in the appropriate
1892     comment syntax for the file format. We also recommend that a
1893     file or class name and description of purpose be included on the
1894     same "printed page" as the copyright notice for easier
1895     identification within third-party archives.
1896
1897  Copyright [yyyy] [name of copyright owner]
1898
1899  Licensed under the Apache License, Version 2.0 (the "License");
1900  you may not use this file except in compliance with the License.
1901  You may obtain a copy of the License at
1902
1903      http://www.apache.org/licenses/LICENSE-2.0
1904
1905  Unless required by applicable law or agreed to in writing, software
1906  distributed under the License is distributed on an "AS IS" BASIS,
1907  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1908  See the License for the specific language governing permissions and
1909  limitations under the License.
1910
1911*/