Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.4.01085.8 KB2026-10-160.3.21087.6 KB2026-10-160.3.11087.5 KB2026-10-160.3.0117.8 KB2026-10-160.2.1106.1 KB2026-10-150.2.0105.5 KB2026-10-15
Version
0.4.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-16
Size
1085.8 KB
Downloads
19
Checksum
df10d3447b809454aba0a9fd252d07428b819520aff22324461ba2dcbf1e43fb
Dependencies
rust/[email protected]
rust/[email protected]

main.rs

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
//! Turns a LaTeX document into a PDF
//!
//! Usage:
//!   hongo doc.tex
//!   hongo doc.tex -o out.pdf
//!   hongo --font-japanese font/ipaexm.ttf doc.tex
//!
//! Put the math typeface (latinmodern-math.otf) in font/. A typeface for Japanese text in font/
//! is also found automatically. To specify a typeface for each role, pass it with --font-….

use hongo::style::Style;
use std::path::{Path, PathBuf};


/// The font file to use for each role
#[derive(Debug, Clone, Default)]
struct Setting {
    input: Option<PathBuf>,
    output: Option<PathBuf>,
    math: Option<PathBuf>,
    roman: Option<PathBuf>,
    italic: Option<PathBuf>,
    bold: Option<PathBuf>,
    mono: Option<PathBuf>,
    sans: Option<PathBuf>,
    japanese: Option<PathBuf>,
}


const USAGE: &str = "usage: hongo [options] document.tex

  -o, --output <file>         where to write the PDF. By default, the document's name with .pdf
      --font-math <file>      the math typeface. By default, font/latinmodern-math.otf
      --font-roman <file>     the typeface for body text
      --font-italic <file>
      --font-bold <file>
      --font-mono <file>
      --font-sans <file>
      --font-japanese <file>  the typeface for Japanese text. By default, the first one in font/
  -h, --help                  show this help";


fn main() {
    let setting = match read_arguments() {
        Ok(Some(setting)) => setting,
        Ok(None) => return,
        Err(reason) => {
            eprintln!("{reason}");
            std::process::exit(1);
        }
    };

    if let Err(reason) = work(&setting) {
        eprintln!("{reason}");
        std::process::exit(1);
    }
}


/// Reads the arguments. None if it only printed the usage
fn read_arguments() -> Result<Option<Setting>, String> {
    let argument: Vec<String> = std::env::args().skip(1).collect();
    let mut setting = Setting::default();
    let mut at = 0;

    while at < argument.len() {
        let one = argument[at].as_str();

        if one == "-h" || one == "--help" {
            println!("{USAGE}");

            return Ok(None);
        }

        if !one.starts_with('-') {
            if setting.input.is_some() {
                return Err(format!("two documents were given: {one}"));
            }

            setting.input = Some(PathBuf::from(one));
            at += 1;

            continue;
        }

        let value = match argument.get(at + 1) {
            Some(value) => PathBuf::from(value),
            None => return Err(format!("{one} must be followed by a file")),
        };

        match one {
            "-o" | "--output" => setting.output = Some(value),
            "--font-math" => setting.math = Some(value),
            "--font-roman" => setting.roman = Some(value),
            "--font-italic" => setting.italic = Some(value),
            "--font-bold" => setting.bold = Some(value),
            "--font-mono" => setting.mono = Some(value),
            "--font-sans" => setting.sans = Some(value),
            "--font-japanese" => setting.japanese = Some(value),
            _ => return Err(format!("unknown option: {one}\n\n{USAGE}")),
        }

        at += 2;
    }

    if setting.input.is_none() {
        return Err(format!("no document was given\n\n{USAGE}"));
    }

    Ok(Some(setting))
}


/// Typesets the document and writes it out
fn work(setting: &Setting) -> Result<(), String> {
    let input = setting.input.clone().unwrap_or_default();
    let source = std::fs::read_to_string(&input)
        .map_err(|reason| format!("cannot read {}: {reason}", input.display()))?;
    let base = input.parent().unwrap_or(Path::new(".")).to_path_buf();
    let places = font_places(&base);
    let math = match &setting.math {
        Some(path) => path.clone(),
        None => find_font("latinmodern-math.otf", &places).ok_or_else(|| {
            "the math typeface was not found. Put font/latinmodern-math.otf in place, or pass one \
with --font-math"
                .to_string()
        })?,
    };
    let japanese = match &setting.japanese {
        Some(path) => Some(path.clone()),
        None => any_font(&places, &math),
    };

    if japanese.is_none() {
        eprintln!(
            "no typeface for Japanese text. Put a Mincho typeface such as IPAex Mincho or Noto \
Serif JP in font/ to set Japanese"
        );
    }

    let library = hongo::font::open(
        &math,
        setting.roman.as_deref(),
        setting.italic.as_deref(),
        setting.bold.as_deref(),
        setting.mono.as_deref(),
        setting.sans.as_deref(),
        japanese.as_deref(),
    )
    .map_err(|reason| reason.to_string())?;
    let style = Style::default();
    let made = hongo::render(&source, &library, &style, &base).map_err(|reason| {
        // message already gives the position as a line and a column, so print it as it is
        format!("{}: {}", input.display(), reason.message)
    })?;
    let output = match &setting.output {
        Some(path) => path.clone(),
        None => input.with_extension("pdf"),
    };
    std::fs::write(&output, &made.data)
        .map_err(|reason| format!("cannot write {}: {reason}", output.display()))?;

    if !made.missing.is_empty() {
        let shown: String = made.missing.iter().take(30).collect();
        eprintln!("characters missing from every typeface: {shown}");
    }

    println!(
        "{} - {} {}, {} KB",
        output.display(),
        made.page,
        if made.page == 1 {"page"} else {"pages"},
        made.data.len() / 1024
    );

    Ok(())
}


/// The places to look for fonts
fn font_places(base: &Path) -> Vec<PathBuf> {
    let mut places = vec![base.join("font"), PathBuf::from("font")];

    if let Ok(exe) = std::env::current_exe() {
        if let Some(directory) = exe.parent() {
            places.push(directory.join("../../font"));
        }
    }

    places
}


/// Looks for a font by name
fn find_font(name: &str, places: &[PathBuf]) -> Option<PathBuf> {
    for one in places {
        let found = one.join(name);

        if found.is_file() {
            return Some(found);
        }
    }

    None
}


/// Looks for one font that is not the math typeface
fn any_font(places: &[PathBuf], except: &Path) -> Option<PathBuf> {
    for one in places {
        let listing = match std::fs::read_dir(one) {
            Ok(listing) => listing,
            Err(_) => continue,
        };
        let mut found: Vec<PathBuf> = listing
            .filter_map(|entry| entry.ok())
            .map(|entry| entry.path())
            .filter(|path| {
                let suffix = path
                    .extension()
                    .and_then(|one| one.to_str())
                    .unwrap_or_default()
                    .to_lowercase();

                matches!(suffix.as_str(), "otf" | "ttf" | "ttc")
                    && path.file_name() != except.file_name()
            })
            .collect();
        found.sort();

        if let Some(first) = found.into_iter().next() {
            return Some(first);
        }
    }

    None
}