1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! 段落と、その中の文字
//!
//! docx の段落 (`<w:p>`) は、書式の変わり目で切れた「続きの文字」(`<w:r>`) が並んだものである。
//! 「太字のここだけ」を表すために、同じ文が複数の続きに分かれていることも多い。
//! 文字だけが要るときは [`Paragraph::text`] でつないで受け取る。
use crate::error::Error;
use crate::xml::{self, Event, Reader};
/// 行のそろえ方
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Align {
/// 指定なし。書式に従う
#[default]
None,
Left,
Center,
Right,
/// 両端をそろえる
Justify,
}
impl Align {
/// `<w:jc w:val="...">` から読む
pub fn of(value: Option<&str>) -> Align {
match value {
Some("left") | Some("start") => Align::Left,
Some("center") => Align::Center,
Some("right") | Some("end") => Align::Right,
Some("both") | Some("distribute") => Align::Justify,
_ => Align::None,
}
}
/// `<w:jc w:val="...">` に書く形
pub fn name(self) -> Option<&'static str> {
match self {
Align::None => None,
Align::Left => Some("left"),
Align::Center => Some("center"),
Align::Right => Some("right"),
Align::Justify => Some("both"),
}
}
}
/// 書式のそろった、続きの文字
///
/// 改行は `\n`、タブは `\t` として text に入る。書き出すときに `<w:br/>` と `<w:tab/>` に戻る。
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Run {
pub text: String,
pub bold: bool,
pub italic: bool,
pub underline: bool,
/// 取り消し線
pub strike: bool,
/// 大きさ。ポイント。0 なら書式の既定
pub size: f64,
/// 色。RRGGBB の 6 桁。空なら書式の既定
pub color: String,
/// 書体の名前。空なら書式の既定
pub font: String,
}
impl Run {
/// 飾りのない文字
pub fn new(text: &str) -> Run {
Run {text: text.to_string(), ..Run::default()}
}
/// 太字の文字
pub fn bold(text: &str) -> Run {
Run {text: text.to_string(), bold: true, ..Run::default()}
}
}
/// 段落
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Paragraph {
/// 段落の書式の名前 (`<w:pStyle>`)。ないときは空
pub style: String,
/// 行のそろえ方
pub align: Align,
/// 中身
pub run: Vec<Run>,
}
impl Paragraph {
/// 飾りのない 1 行
pub fn new(text: &str) -> Paragraph {
Paragraph {run: vec![Run::new(text)], ..Paragraph::default()}
}
/// 書式の名前を指定した 1 行
pub fn styled(text: &str, style: &str) -> Paragraph {
Paragraph {
style: style.to_string(),
run: vec![Run::new(text)],
..Paragraph::default()
}
}
/// 中の続きをつないだ文字
pub fn text(&self) -> String {
let mut result = String::new();
for one in &self.run {
result.push_str(&one.text);
}
result
}
}
/// `<w:p>` を読んだ直後から `</w:p>` まで読む
pub fn read(source: &mut Reader) -> Result<Paragraph, Error> {
let mut result = Paragraph::default();
let mut inside = false;
let mut decorating = false;
let mut reading = false;
let mut run: Option<Run> = None;
while let Some(event) = source.next()? {
if event == Event::Text {
if reading {
if let Some(one) = run.as_mut() {
one.text.push_str(source.text());
}
}
continue;
}
if event == Event::Close {
match source.name() {
"p" => return Ok(result),
"pPr" => inside = false,
"rPr" => decorating = false,
"t" => reading = false,
"r" => {
if let Some(one) = run.take() {
result.run.push(one);
}
}
_ => {}
}
continue;
}
let empty = event == Event::Empty;
match source.name() {
"pPr" => inside = !empty,
"pStyle" if inside => result.style = source.attribute("val").unwrap_or("").to_string(),
"jc" if inside => result.align = Align::of(source.attribute("val")),
// 段落そのものの飾り (`<w:pPr><w:rPr>`) は、続きの飾りではない
"r" if !inside => run = Some(Run::default()),
"rPr" => decorating = !empty && run.is_some(),
"t" if run.is_some() => reading = !empty,
"br" => {
if let Some(one) = run.as_mut() {
one.text.push('\n');
}
}
"tab" => {
if let Some(one) = run.as_mut() {
one.text.push('\t');
}
}
_ if decorating => {
if let Some(one) = run.as_mut() {
decorate(one, source);
}
}
_ => {}
}
}
Ok(result)
}
/// `<w:rPr>` の中の 1 つを読む
fn decorate(run: &mut Run, source: &Reader) {
match source.name() {
"b" => run.bold = flag(source.attribute("val")),
"i" => run.italic = flag(source.attribute("val")),
"strike" => run.strike = flag(source.attribute("val")),
"u" => run.underline = source.attribute("val") != Some("none"),
"color" => {
let value = source.attribute("val").unwrap_or("");
if value != "auto" {
run.color = value.to_string();
}
}
"sz" => {
// 半ポイントで入っている
let value: f64 = source.attribute("val").unwrap_or("0").parse().unwrap_or(0.0);
run.size = value / 2.0;
}
"rFonts" => {
let value = source.attribute("ascii").or(source.attribute("eastAsia"));
run.font = value.unwrap_or("").to_string();
}
_ => {}
}
}
/// `<w:b/>` のように値のない印は入り、`w:val="0"` なら消す
fn flag(value: Option<&str>) -> bool {
!matches!(value, Some("0") | Some("false") | Some("off"))
}
/// 段落を XML にして足す
pub fn write_into(result: &mut String, one: &Paragraph) {
result.push_str("<w:p>");
let align = one.align.name();
if !one.style.is_empty() || align.is_some() {
result.push_str("<w:pPr>");
if !one.style.is_empty() {
result.push_str("<w:pStyle w:val=\"");
xml::escape_into(&one.style, result);
result.push_str("\"/>");
}
if let Some(name) = align {
result.push_str(&format!("<w:jc w:val=\"{name}\"/>"));
}
result.push_str("</w:pPr>");
}
for run in &one.run {
run_into(result, run);
}
result.push_str("</w:p>");
}
/// 続きの文字を XML にして足す
fn run_into(result: &mut String, run: &Run) {
result.push_str("<w:r>");
let decorated = run.bold || run.italic || run.strike || run.underline
|| run.size > 0.0 || !run.color.is_empty() || !run.font.is_empty();
if decorated {
// docx は rPr の中の順番が決まっている。rFonts、b、i、strike、color、sz、u の順
result.push_str("<w:rPr>");
if !run.font.is_empty() {
result.push_str("<w:rFonts w:ascii=\"");
xml::escape_into(&run.font, result);
result.push_str("\" w:hAnsi=\"");
xml::escape_into(&run.font, result);
result.push_str("\" w:eastAsia=\"");
xml::escape_into(&run.font, result);
result.push_str("\"/>");
}
if run.bold {
result.push_str("<w:b/>");
}
if run.italic {
result.push_str("<w:i/>");
}
if run.strike {
result.push_str("<w:strike/>");
}
if !run.color.is_empty() {
result.push_str("<w:color w:val=\"");
xml::escape_into(&run.color, result);
result.push_str("\"/>");
}
if run.size > 0.0 {
result.push_str(&format!("<w:sz w:val=\"{}\"/>", (run.size * 2.0).round() as i64));
}
if run.underline {
result.push_str("<w:u w:val=\"single\"/>");
}
result.push_str("</w:rPr>");
}
// 改行とタブは、文字ではなく印として置く
let mut piece = String::new();
for value in run.text.chars() {
if value == '\n' || value == '\t' {
text_into(result, &piece);
piece.clear();
result.push_str(if value == '\n' {"<w:br/>"} else {"<w:tab/>"});
continue;
}
piece.push(value);
}
text_into(result, &piece);
result.push_str("</w:r>");
}
/// 文字を `<w:t>` にして足す。空なら置かない
fn text_into(result: &mut String, text: &str) {
if text.is_empty() {
return;
}
result.push_str("<w:t xml:space=\"preserve\">");
xml::escape_into(text, result);
result.push_str("</w:t>");
}