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
//! LaTeX の文書を PDF にする
//!
//! 使い方:
//! hongo doc.tex
//! hongo doc.tex -o out.pdf
//! hongo --font-japanese font/ipaexm.ttf doc.tex
//!
//! 数式の書体(latinmodern-math.otf)は font/ に置く。和文の書体も font/ に置けば
//! 自動で見つける。役ごとに指定したいときは --font-… で渡す。
use hongo::style::Style;
use std::path::{Path, PathBuf};
/// 役ごとに使うフォントのファイル
#[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 = "使い方: hongo [選び方] 文書.tex
-o, --output <ファイル> 書き出し先。既定は文書と同じ名前の .pdf
--font-math <ファイル> 数式の書体。既定は font/latinmodern-math.otf
--font-roman <ファイル> 地の文の書体
--font-italic <ファイル>
--font-bold <ファイル>
--font-mono <ファイル>
--font-sans <ファイル>
--font-japanese <ファイル> 和文の書体。既定は font/ にある最初のもの
-h, --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);
}
}
/// 引数を読む。案内を出しただけなら None
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!("読む文書が 2 つあります: {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} のあとにファイルを書いてください")),
};
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!("知らない選び方です: {one}\n\n{USAGE}")),
}
at += 2;
}
if setting.input.is_none() {
return Err(format!("読む文書を書いてください。\n\n{USAGE}"));
}
Ok(Some(setting))
}
/// 文書を組んで書き出す
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!("読めません: {}: {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(|| {
"数式の書体が見つかりません。font/latinmodern-math.otf を置くか \
--font-math で指定してください"
.to_string()
})?,
};
let japanese = match &setting.japanese {
Some(path) => Some(path.clone()),
None => any_font(&places, &math),
};
if japanese.is_none() {
eprintln!(
"和文の書体がありません。font/ に明朝体(IPAex明朝、Noto Serif JP など)を\
置くと日本語が出ます"
);
}
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 をそのまま出す
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!("書けません: {}: {reason}", output.display()))?;
if !made.missing.is_empty() {
let shown: String = made.missing.iter().take(30).collect();
eprintln!("どの書体にもない字があります: {shown}");
}
println!(
"{} - {} ページ, {} キロバイト",
output.display(),
made.page,
made.data.len() / 1024
);
Ok(())
}
/// フォントを探す場所
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
}
/// 名前でフォントを探す
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
}
/// 数式の書体ではないフォントを 1 つ探す
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
}