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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! The text blocks of the body: each paragraph and table, in the order of the document, with its
//! address, its kind with its style and text, and the pages that its lines lie on, for a reader
//! of the document such as `foffice read`.
//!
//! The body's blocks follow its XML one for one: each `w:p` and `w:tbl` among the block-level
//! children, with block-level content controls, custom XML and the shown branch of alternate
//! content in their place (`body::block_children`), gives one block, so an address names the
//! same element in the file.
use std::collections::HashMap;
use std::fmt;
use std::num::NonZeroUsize;
use std::ops::{Range, RangeInclusive};
use std::str::FromStr;
use crate::body::toc::TableOfContents;
use crate::body::{Block, Content, Paragraph, ParagraphId};
use crate::layout::PlacedLine;
use crate::params;
use crate::styles::Styles;
/// The text of a picture in the text of its paragraph.
pub(crate) const PICTURE_MARKER: &str = "{PICTURE}";
/// One step of an address: the story that it starts in, or the place of a block, a row, a cell
/// or a text box among its kind, from 1.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AddressStep {
/// The header part of this number, in the order in which the sections first name the
/// header parts (`h`).
Header(NonZeroUsize),
/// The footer part of this number, in the order in which the sections first name the
/// footer parts (`f`).
Footer(NonZeroUsize),
/// The footnote of this number among the normal footnotes of its part, in the order of the
/// part (`n`).
Footnote(NonZeroUsize),
/// The endnote of this number among the normal endnotes of its part, in the order of the
/// part (`e`).
Endnote(NonZeroUsize),
/// The paragraph of this number among the paragraphs of its story, cell or text box (`p`).
Paragraph(NonZeroUsize),
/// The table of this number among the tables of its story, cell or text box (`t`).
Table(NonZeroUsize),
/// The row of this number of its table (`r`).
Row(NonZeroUsize),
/// The cell of this number of its row (`c`).
Cell(NonZeroUsize),
/// The text box of this number among the text boxes of its paragraph (`b`).
TextBox(NonZeroUsize),
}
impl AddressStep {
/// The letter that names the step's kind.
const fn letter(self) -> char {
match self {
Self::Header(_) => 'h',
Self::Footer(_) => 'f',
Self::Footnote(_) => 'n',
Self::Endnote(_) => 'e',
Self::Paragraph(_) => 'p',
Self::Table(_) => 't',
Self::Row(_) => 'r',
Self::Cell(_) => 'c',
Self::TextBox(_) => 'b',
}
}
/// The step's number, from 1.
const fn number(self) -> NonZeroUsize {
match self {
Self::Header(n)
| Self::Footer(n)
| Self::Footnote(n)
| Self::Endnote(n)
| Self::Paragraph(n)
| Self::Table(n)
| Self::Row(n)
| Self::Cell(n)
| Self::TextBox(n) => n,
}
}
/// Whether the step names a story other than the body.
const fn is_story(self) -> bool {
matches!(
self,
Self::Header(_) | Self::Footer(_) | Self::Footnote(_) | Self::Endnote(_)
)
}
}
/// The path by which a reader names an element of a story (**Address**):
/// `p12` for the twelfth paragraph of the body, `t2/r4/c1/p1` for the first paragraph of the
/// first cell of the fourth row of the second table, `t2/r4` for that row, `p5/b1/p2` for the
/// second paragraph of the first text box of the fifth paragraph, and `h1/p3` for the third
/// paragraph of the first header part. Its grammar is
///
/// ```text
/// address = [ story "/" ] block
/// story = ( "h" | "f" | "n" | "e" ) number
/// block = "p" number [ "/b" number "/" block ]
/// | "t" number [ "/r" number [ "/c" number [ "/" block ] ] ]
/// number = a decimal number from 1, without a sign or leading zeros
/// ```
///
/// so that a value of this type always names a paragraph, a table, a row or a cell.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Address {
steps: Vec<AddressStep>,
}
impl Address {
/// The steps from the body down to the element, never empty.
#[must_use]
pub fn steps(&self) -> &[AddressStep] {
&self.steps
}
/// Whether it names an element of the body outside text boxes.
#[must_use]
pub fn in_body(&self) -> bool {
!self
.steps
.iter()
.any(|step| step.is_story() || matches!(step, AddressStep::TextBox(_)))
}
/// The address of a block of a story or a cell that holds the steps of `self`, the block
/// itself named by `step`.
pub(crate) fn then(&self, step: AddressStep) -> Self {
let mut steps = self.steps.clone();
steps.push(step);
Self { steps }
}
/// The address of the block `step` of the body.
pub(crate) fn top(step: AddressStep) -> Self {
Self { steps: vec![step] }
}
/// The address of the block `step` of the cell `cell`, or of the body when `cell` is none.
pub(crate) fn within(cell: Option<&Self>, step: AddressStep) -> Self {
cell.map_or_else(|| Self::top(step), |cell| cell.then(step))
}
/// The address of the table that holds the row `self`, or none when `self` names no row.
pub(crate) fn table_of_row(&self) -> Option<Self> {
match self.steps.split_last() {
Some((AddressStep::Row(_), table)) if !table.is_empty() => Some(Self {
steps: table.to_vec(),
}),
_ => None,
}
}
/// The address of the row that holds the cell `self`, with the cell's number, or none when
/// `self` names no cell.
pub(crate) fn row_of_cell(&self) -> Option<(Self, NonZeroUsize)> {
match self.steps.split_last() {
Some((AddressStep::Cell(number), row)) => Some((
Self {
steps: row.to_vec(),
},
*number,
)),
_ => None,
}
}
/// The steps of the cell or the body that holds the block, the row or the cell `self`:
/// every step but the last.
pub(crate) fn container(&self) -> &[AddressStep] {
self.steps
.split_last()
.map_or(&[], |(_, container)| container)
}
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (index, step) in self.steps.iter().enumerate() {
if index > 0 {
f.write_str("/")?;
}
write!(f, "{}{}", step.letter(), step.number())?;
}
Ok(())
}
}
/// Why a text does not read as an address. Each error's text names the fix.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AddressError {
/// The text is empty.
Empty,
/// A step is not a letter of a step's kind followed by a number from 1.
Step {
/// The step.
step: String,
},
/// A step stands where the grammar does not allow its kind.
Order {
/// The step.
step: String,
/// What the grammar allows there.
expected: &'static str,
},
/// The text ends where the grammar needs another step.
Unfinished {
/// What the grammar needs there.
expected: &'static str,
},
}
impl fmt::Display for AddressError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => f.write_str(
"the address is empty: name a paragraph or a table, such as p12 or t2/r4/c1/p1",
),
Self::Step { step } => write!(
f,
"`{step}` is not a step of an address: write h, f, n, e, p, t, r, c or b and a \
number from 1, such as p12 or t2/r4/c1/p1"
),
Self::Order { step, expected } => write!(
f,
"`{step}` cannot stand there: the address needs {expected}, as in t2/r4/c1/p1 \
or h1/p3/b1/p1"
),
Self::Unfinished { expected } => write!(
f,
"the address ends too soon: it needs {expected}, as in h1/p3/b1/p1"
),
}
}
}
impl std::error::Error for AddressError {}
/// What the grammar allows as the next step.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Next {
/// A story or a block, at the start.
Start,
/// A paragraph or a table, after a story or a text box, which the address cannot end with.
Block,
/// A row, after a table, or the end.
Row,
/// A cell, after a row, or the end.
Cell,
/// A block, after a cell, or the end.
BlockInCell,
/// A text box, after a paragraph, or the end.
TextBox,
}
impl Next {
/// What an error says that the grammar allows.
const fn expected(self) -> &'static str {
match self {
Self::Start => "a story (h, f, n or e), a paragraph (p) or a table (t)",
Self::Block | Self::BlockInCell => "a paragraph (p) or a table (t)",
Self::Row => "a row (r) after a table",
Self::Cell => "a cell (c) after a row",
Self::TextBox => "a text box (b) or nothing after a paragraph",
}
}
/// What the grammar allows after `step`, or none when it does not allow `step` here.
const fn after(self, step: AddressStep) -> Option<Self> {
Some(match (self, step) {
(Self::Start, step) if step.is_story() => Self::Block,
(Self::Start | Self::Block | Self::BlockInCell, AddressStep::Paragraph(_)) => {
Self::TextBox
}
(Self::Start | Self::Block | Self::BlockInCell, AddressStep::Table(_)) => Self::Row,
(Self::TextBox, AddressStep::TextBox(_)) => Self::Block,
(Self::Row, AddressStep::Row(_)) => Self::Cell,
(Self::Cell, AddressStep::Cell(_)) => Self::BlockInCell,
_ => return None,
})
}
}
impl FromStr for Address {
type Err = AddressError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
if text.is_empty() {
return Err(AddressError::Empty);
}
let mut steps = Vec::new();
let mut next = Next::Start;
for part in text.split('/') {
let step = read_step(part)?;
next = next.after(step).ok_or_else(|| AddressError::Order {
step: part.to_owned(),
expected: next.expected(),
})?;
steps.push(step);
}
if next == Next::Block {
return Err(AddressError::Unfinished {
expected: next.expected(),
});
}
Ok(Self { steps })
}
}
/// Reads one step: its kind's letter and a number from 1 without a sign or leading zeros.
fn read_step(part: &str) -> Result<AddressStep, AddressError> {
let bad = || AddressError::Step {
step: part.to_owned(),
};
let mut chars = part.chars();
let kind = chars.next().ok_or_else(bad)?;
let digits = chars.as_str();
if digits.is_empty() || digits.starts_with('0') || !digits.bytes().all(|b| b.is_ascii_digit()) {
return Err(bad());
}
let number = digits.parse::<NonZeroUsize>().map_err(|_| bad())?;
Ok(match kind {
'h' => AddressStep::Header(number),
'f' => AddressStep::Footer(number),
'n' => AddressStep::Footnote(number),
'e' => AddressStep::Endnote(number),
'b' => AddressStep::TextBox(number),
'p' => AddressStep::Paragraph(number),
't' => AddressStep::Table(number),
'r' => AddressStep::Row(number),
'c' => AddressStep::Cell(number),
_ => return Err(bad()),
})
}
/// What a text block is.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum TextBlockKind {
/// A paragraph, with its style ID and its text.
Paragraph {
/// The ID of its paragraph style, as the file writes it, if it has one.
style: Option<String>,
/// Its text as a reader sees it in the file: the text of its runs, a tab as `\t`, a
/// line, page or column break as `\n`, a check box as ☐ or ☒, the stored result of a
/// field whose value Word may compute again, and a marker in braces for what has no
/// text of its own: `{PAGE}` and `{NUMPAGES}` for the page number and the page count,
/// `{FOOTNOTE}` and `{ENDNOTE}` for a note's reference, `{PICTURE}` and `{OBJECT}` for
/// an inline object, and `{DRAWING}` for a drawing. Field codes, bookmarks, comment
/// anchors and the marks of notes, comments and equations give no text.
text: String,
},
/// A table, with its number of rows. The paragraphs of its cells follow it as text blocks
/// of their own.
Table {
/// The number of rows.
rows: usize,
},
}
/// A paragraph or a table of the body, as a reader of the document lists it (**Text block**).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct TextBlock {
/// Where it is in the body.
pub address: Address,
/// What it is, with its style and text for a paragraph.
pub kind: TextBlockKind,
/// The indices of the pages that its lines lie on, from the first to the last, counted from
/// 0 as `f_office::Document::page` counts them, while its address counts from 1; for a
/// table, those of the lines of its cells. It is none when the layout placed no line of the
/// block: a paragraph whose mark and text are hidden, or a table none of whose cells has a
/// placed line.
pub page_indices: Option<RangeInclusive<usize>>,
/// The span of its element in the bytes of the main document part, where the reader found
/// it (**Source span**), or none for a block that F-Office made itself or
/// a part not in UTF-8. The edits of `foffice` find the element of an address with it.
pub source: Option<Range<usize>>,
/// For a table, the span of each row's element in the same way, in the order of the rows;
/// empty for a paragraph.
pub row_sources: Vec<Option<Range<usize>>>,
/// For a paragraph that is a heading, its outline level from 0 for the top level to 8: the
/// `w:outlineLvl` of its own properties, or else of its style and the styles that it is
/// based on. It is none for body text and for a table.
pub outline_level: Option<u8>,
/// For a paragraph that the body's table of contents lists, the level from 0 that it gives
/// the paragraph. The table of contents is the first `TOC` field of the body that is not a
/// table of figures (no `\c` and no `\a`). Its stored entries give the levels: each entry
/// that links to a bookmark (by a `PAGEREF` or a `HYPERLINK \l` field) lists the
/// paragraph that holds the bookmark's start, at the level of the entry's style (`toc 1`
/// gives 0). When no stored entry links to a paragraph, its switches give them: the
/// paragraphs of the styles of `\t`, those whose outline level lies in the range of `\o`
/// or `\u`, and those of the `TC` fields that `\f` and `\l` list. It is none for a
/// paragraph that the table of contents does not list, for a table, and for every block of a
/// body without one.
pub toc_level: Option<u8>,
}
/// The text blocks of the body's `blocks`, in the order of the document, with the pages of the
/// `lines` that the layout placed, the outline levels that the paragraphs take from their
/// properties and `styles`, and the levels that the body's table of contents `toc` gives them.
#[must_use]
pub(crate) fn text_blocks(
blocks: &[Block],
lines: &[PlacedLine],
(styles, toc): (&Styles, Option<&TableOfContents>),
) -> Vec<TextBlock> {
let mut pages: HashMap<ParagraphId, RangeInclusive<usize>> = HashMap::new();
for line in lines {
let page = line.page..=line.page;
let span = pages.remove(&line.paragraph);
if let Some(span) = widen(span, Some(&page)) {
pages.insert(line.paragraph, span);
}
}
let levels = toc_levels::toc_levels(blocks, styles, toc);
let mut out = Vec::new();
add_blocks(blocks, None, (&pages, styles, &levels), &mut out);
out
}
/// Adds the text blocks of `blocks`, the blocks of the body when `within` is none, or else of
/// the cell at that address, and gives the pages that their lines lie on.
fn add_blocks(
blocks: &[Block],
within: Option<&Address>,
(pages, styles, levels): (
&HashMap<ParagraphId, RangeInclusive<usize>>,
&Styles,
&HashMap<ParagraphId, u8>,
),
out: &mut Vec<TextBlock>,
) -> Option<RangeInclusive<usize>> {
let (mut paragraphs, mut tables) = (0, 0);
let mut all = None;
for block in blocks {
let (block_address, kind, span, source, (outline_level, toc_level)) = match block {
Block::Paragraph(paragraph) => {
paragraphs += 1;
let kind = TextBlockKind::Paragraph {
style: paragraph.props.style.clone(),
text: paragraph_text(paragraph),
};
let step = AddressStep::Paragraph(number(paragraphs));
let source = paragraph.source.range();
let address = Address::within(within, step);
(
address,
kind,
pages.get(¶graph.id).cloned(),
source,
(
outline_level(paragraph, styles),
levels.get(¶graph.id).copied(),
),
)
}
Block::Table(table) => {
tables += 1;
let table_address = Address::within(within, AddressStep::Table(number(tables)));
let at = out.len();
let mut span = None;
for (row_index, row) in table.rows.iter().enumerate() {
let row_address = table_address.then(AddressStep::Row(number(row_index + 1)));
for (cell_index, cell) in row.cells.iter().enumerate() {
let step = AddressStep::Cell(number(cell_index + 1));
let cell_span = add_blocks(
&cell.blocks,
Some(&row_address.then(step)),
(pages, styles, levels),
out,
);
span = widen(span, cell_span.as_ref());
}
}
let kind = TextBlockKind::Table {
rows: table.rows.len(),
};
// The table comes before the blocks of its cells.
out.insert(
at,
TextBlock {
address: table_address,
kind,
page_indices: span.clone(),
source: table.source.range(),
row_sources: table.rows.iter().map(|row| row.source.range()).collect(),
outline_level: None,
toc_level: None,
},
);
all = widen(all, span.as_ref());
continue;
}
};
all = widen(all, span.as_ref());
out.push(TextBlock {
address: block_address,
kind,
page_indices: span,
source,
row_sources: Vec::new(),
outline_level,
toc_level,
});
}
all
}
/// The outline level of `paragraph`, as [`TextBlock::outline_level`] says: none for the level
/// of body text.
pub(super) fn outline_level(paragraph: &Paragraph, styles: &Styles) -> Option<u8> {
let props = styles.paragraph_properties_without_list_level(¶graph.props, None);
props
.outline_level
.filter(|level| *level < params::BODY_TEXT_OUTLINE_LEVEL)
}
/// The pages from the first of `pages` and `more` to the last, or those of the one that is
/// given.
fn widen(
pages: Option<RangeInclusive<usize>>,
more: Option<&RangeInclusive<usize>>,
) -> Option<RangeInclusive<usize>> {
match (pages, more) {
(Some(a), Some(b)) => Some((*a.start()).min(*b.start())..=(*a.end()).max(*b.end())),
(a, b) => a.or_else(|| b.cloned()),
}
}
/// The number, from 1, of the block, row or cell that `count` blocks, rows or cells end, which
/// is never 0.
pub(crate) fn number(count: usize) -> NonZeroUsize {
NonZeroUsize::MIN.saturating_add(count.saturating_sub(1))
}
/// The text of a paragraph, as [`TextBlockKind::Paragraph`] says.
#[must_use]
fn paragraph_text(paragraph: &Paragraph) -> String {
let mut text = String::new();
for content in paragraph.runs.iter().flat_map(|run| &run.content) {
match content {
Content::Text(piece) => text.push_str(piece),
Content::Tab | Content::PositionTab { .. } => text.push('\t'),
Content::LineBreak
| Content::ClearingBreak
| Content::PageBreak
| Content::ColumnBreak => text.push('\n'),
Content::CheckBox(check_box) => {
text.push(if check_box.checked { '☒' } else { '☐' });
}
Content::PageNumber => text.push_str("{PAGE}"),
Content::PageCount => text.push_str("{NUMPAGES}"),
Content::Date(field) => text.push_str(&field.stored),
Content::DocProperty(field) => text.push_str(&field.stored),
Content::StyleRef(field) => text.push_str(&field.stored),
Content::PageRef(field) => text.push_str(&field.stored),
Content::NumberRef(field) => text.push_str(&field.stored),
Content::If(field) => text.push_str(&field.stored),
Content::FootnoteReference(..) => text.push_str("{FOOTNOTE}"),
Content::EndnoteReference(..) => text.push_str("{ENDNOTE}"),
Content::Object { picture, .. } => {
text.push_str(if picture.is_some() {
PICTURE_MARKER
} else {
"{OBJECT}"
});
}
Content::Drawing(_) | Content::Floating(_) => text.push_str("{DRAWING}"),
Content::FieldBegin
| Content::FieldLock
| Content::DropDown(_)
| Content::FieldCode(_)
| Content::FieldSeparate
| Content::FieldEnd
| Content::Bookmark(_)
| Content::FieldMark
| Content::HyperlinkEdge
| Content::ControlEdge
| Content::RemovedEdge
| Content::CommentAnchor(_)
| Content::FootnoteMark
| Content::EndnoteMark
| Content::CommentMark
| Content::Separator
| Content::ContinuationSeparator
| Content::Stack(_)
| Content::Grown(_)
| Content::Radical(_)
| Content::Accent(_)
| Content::Matrix(_)
| Content::MathBar(_)
| Content::MathSlash(_)
| Content::Scripts(_)
| Content::Advance(_) => {}
}
}
text
}
mod toc_levels;
#[cfg(test)]
mod tests;