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
//! Footnotes at the bottom of pages.
use std::collections::HashMap;
use f_office_units::Length;
use crate::body::{Block, Columns, Content, NoteId, NoteMark, Notes, Paragraph, Section};
use crate::lines::{Line, NoteNumber, Piece};
use crate::note_setup::{NoteLabel, NoteRestart, NoteSetup};
use crate::text::FontNotes;
use super::output::StoryKey;
use super::pages::StoryInputs;
use super::sections::SectionIndex;
use super::{Layout, Previous};
mod flow;
mod splits;
#[cfg(test)]
mod tests;
pub(super) use splits::{Foot, Part};
/// The footnotes that a layout pass has numbered: part of its output.
#[derive(Clone, Debug, Default)]
pub(super) struct NoteNumbers {
/// The number of each footnote ID, in the order of the first references.
numbers: HashMap<NoteId, NoteNumber>,
/// Each numbered footnote, at the place of its number.
numbered: Vec<NumberedNote>,
/// The place of each footnote among the footnotes whose references stand on its page, as
/// the pages of this pass end.
places: NotePlaces,
/// The height of each footnote without the space after its last paragraph, and that
/// paragraph, by number.
sizes: HashMap<NoteNumber, (Length, Option<Previous>)>,
/// The last height of each separator, with the story inputs of its layout, which a use
/// with equal story inputs takes again.
separators: HashMap<Separator, (StoryInputs, SeparatorHeight)>,
}
impl NoteNumbers {
/// The places of the footnotes on their pages that this pass found.
pub(super) fn take_places(&mut self) -> NotePlaces {
std::mem::take(&mut self.places)
}
}
/// A footnote or an endnote that a layout pass has numbered at its first reference.
#[derive(Clone, Debug)]
pub(super) struct NumberedNote {
/// Its ID.
pub(super) id: NoteId,
/// The section of its first reference.
section: SectionIndex,
/// The index of the page being filled when its first reference was measured.
page: usize,
/// What its reference and its mark show.
pub(super) label: NoteLabel,
/// Its running number: the number that a note after it in a section whose numbers go on
/// counts from. It is its number, except in a section whose numbers start again on each
/// page, where the running numbers go on through the pages.
running: i64,
}
/// The place of each footnote among the footnotes whose references stand on its page, from 0,
/// by footnote ID: what a pass found, which numbers the footnotes of the next pass in a section
/// whose footnotes start their numbers again on each page.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NotePlaces(HashMap<NoteId, usize>);
impl NotePlaces {
/// Whether no footnote of such a section stands on a page.
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
/// A separator of the footnotes of a page.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(super) enum Separator {
/// The separator above the footnotes of a page (`w:separator`).
Normal,
/// The separator above the rest of a footnote that started on the page before
/// (`w:continuationSeparator`).
Continuation,
}
impl Separator {
/// The blocks of this separator in the footnotes `notes`.
pub(super) fn blocks(self, notes: &Notes) -> &[Block] {
match self {
Self::Normal => ¬es.separator,
Self::Continuation => ¬es.continuation,
}
}
}
/// A footnote of the footnotes part that the layout lays out: its ID, which names its story
/// ([`super::StoryKind::key`]), and its blocks.
#[derive(Clone, Copy, Debug)]
pub(super) struct Footnote<'a> {
/// Its ID in the footnotes part.
pub(super) id: NoteId,
/// Its blocks.
pub(super) blocks: &'a [Block],
}
/// The height of a separator laid out from 0, with the warnings and the font notes of its
/// layout, which each use of the height adds to the layout again, as a new layout of the
/// separator would.
#[derive(Clone, Debug)]
struct SeparatorHeight {
height: Length,
warnings: crate::Warnings,
notes: FontNotes,
}
/// The footnotes of the page being filled: part of the page state.
#[derive(Clone, Debug, Default)]
pub(super) struct PageNotes {
/// The numbers of the footnotes on the page being filled.
page: Vec<NoteNumber>,
/// The height that those footnotes and the separator take at the bottom of the page.
height: Length,
/// The first lines of the last footnote of the page, when the footnote goes on to the
/// next page.
part: Option<Part>,
/// The footnote whose rest starts the footnotes of the page, and the first line of the
/// rest.
rest: Option<(NoteNumber, usize)>,
/// The room for the lines that widow control binds to a line of the paragraph being laid
/// out, when the footnote of that line goes on to the next page.
reserve: Option<splits::Reserve>,
}
/// Where the footnotes of a page stand across.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NoteColumns {
/// Within the margins of the section.
Section,
/// At the foot of the text column that holds their reference, as wide as it.
Reference,
/// In the columns of the footnote area, as many as the section's text columns, which have
/// one width: each column filled before the next.
Flow(usize),
}
impl<'a> Layout<'a> {
/// The number of a footnote, numbering it when its first reference comes, as the
/// footnotes of the current section are numbered, with the reference's `mark`.
pub(super) fn note_number(&mut self, id: NoteId, mark: NoteMark) -> NoteNumber {
if let Some(number) = self.output.notes.numbers.get(&id) {
return *number;
}
let setup = self.section_layout(self.section_index).notes.footnotes;
let places = Some(&self.context.earlier.note_places);
let note = self.numbered_note((id, mark), &self.output.notes.numbered, setup, places);
let number = NoteNumber::of_index(self.output.notes.numbered.len());
self.output.notes.numbered.push(note);
self.output.notes.numbers.insert(id, number);
number
}
/// What the reference and the mark of the footnote `number` show.
pub(super) fn note_label(&self, number: NoteNumber) -> NoteLabel {
self.output
.notes
.numbered
.get(number.index())
.map_or(NoteLabel::FIRST, |note| note.label)
}
/// Numbers the note `id`, whose first reference comes now, after the notes `before` of
/// its kind, as `setup` numbers the notes of its kind in the current section (ECMA-376
/// Part 1, 17.11, `w:numRestart` and `w:numStart`): with numbers that go on, the running
/// number of the note before plus 1, or `setup.start` for the first note; with numbers
/// that start again in each section, also `setup.start` for the first note of the
/// section; with numbers that start again on each page, `setup.start` plus the note's
/// place on its page, while its running number goes on from the note before. A note whose
/// reference has a custom mark takes no number: the next note gets the number it would
/// have had.
pub(super) fn numbered_note(
&self,
(id, mark): (NoteId, NoteMark),
before: &[NumberedNote],
setup: NoteSetup,
places: Option<&NotePlaces>,
) -> NumberedNote {
let section = self.section_index;
let page = self.output.pages.len();
let last = before.last();
let next = last.map_or(setup.start, |last| last.running.saturating_add(1));
let (value, running) = match setup.restart {
NoteRestart::EachPage => {
let place = places
.and_then(|places| places.0.get(&id).copied())
.unwrap_or_else(|| place_when_measured(before, (section, page)));
let value = setup
.start
.saturating_add(f_office_units::count_factor(place));
(value, next)
}
NoteRestart::EachSection if last.is_none_or(|last| last.section != section) => {
(setup.start, setup.start)
}
NoteRestart::EachSection | NoteRestart::Continuous => (next, next),
};
let running = match mark {
NoteMark::Number => running,
NoteMark::Custom => running.saturating_sub(1),
};
NumberedNote {
id,
section,
page,
label: NoteLabel {
value,
format: setup.format,
},
running,
}
}
/// The footnotes whose references are on a line and not yet on this page, and the
/// height they add at the bottom of the page, with the separator when they are the first.
pub(super) fn new_notes(&mut self, line: &Line) -> (Vec<NoteNumber>, Length) {
let mut numbers: Vec<NoteNumber> = line
.placed
.iter()
.filter_map(|p| match p.piece {
Piece::Note(number) => Some(number),
_ => None,
})
.filter(|n| !self.page_notes.page.contains(n))
.collect();
numbers.dedup();
if numbers.is_empty() {
return (numbers, Length::ZERO);
}
if let NoteColumns::Flow(columns) = self.note_columns() {
let mut all = self.page_notes.page.clone();
all.extend(&numbers);
let height = self.separator_height(Separator::Normal) + self.note_flow(&all, columns).0;
return (numbers, height - self.page_notes.height);
}
let last = self.page_notes.page.last().copied();
let mut height = self.notes_span(last, &numbers);
if self.page_notes.page.is_empty() {
height += self.separator_height(Separator::Normal);
}
(numbers, height)
}
/// The height of the footnotes already on this page.
pub(super) fn notes_height(&self) -> Length {
self.page_notes.height
}
/// The height of the footnotes that a line of the body has below it on this page: none
/// for a line in a table cell, which the page does not fit by itself.
pub(super) fn body_notes(&self) -> Length {
if self.column.cell.is_some() {
Length::ZERO
} else {
self.fitted_notes(self.notes_height())
}
}
/// The height `notes` of the footnotes of a page as the fit of a line above them counts
/// it: none below the compatibility mode from which the line needs more than the room of
/// its text.
pub(super) fn fitted_notes(&self, notes: Length) -> Length {
if self.settings.mode_rules.notes_need_whole_line_room() {
notes
} else {
Length::ZERO
}
}
/// The section whose margins a footnote and its separator are laid out in: the text
/// column being filled where the footnotes stand at the foot of their reference's column,
/// the first column where they flow in the columns of the footnote area, and else the
/// section.
pub(super) fn note_section(&self) -> Section {
match self.note_columns() {
NoteColumns::Section => self.section,
NoteColumns::Reference => self.column_section(self.column_index),
NoteColumns::Flow(_) => self.column_section(0),
}
}
/// The section as a section of one column: the text column `index`.
fn column_section(&self, index: usize) -> Section {
let mut section = self.section;
if let Some(&(left, width)) = self.columns.get(index) {
section.left = left;
section.right = section.width - left - width;
section.columns = Columns::default();
}
section
}
/// Where the footnotes of the page being filled stand across: in a section of more than
/// one text column, before `NOTE_FLOW_MODE` at the foot of the column that holds their
/// reference, outside a table cell, and from it in the columns of the footnote area when
/// the text columns have one width.
fn note_columns(&self) -> NoteColumns {
let Some(&(_, width)) = self.columns.first().filter(|_| self.columns.len() > 1) else {
return NoteColumns::Section;
};
if self.settings.mode_rules.notes_in_reference_column() {
if self.column.cell.is_none() {
NoteColumns::Reference
} else {
NoteColumns::Section
}
} else if self.columns.iter().all(|column| column.1 == width) {
NoteColumns::Flow(self.columns.len())
} else {
NoteColumns::Section
}
}
/// Lays out the footnotes of the text column that ends now at its foot, when each footnote
/// stands at the foot of the column of its reference, so that the next column of the page
/// starts with none.
pub(super) fn place_column_notes(&mut self) {
if self.note_columns() == NoteColumns::Reference {
self.place_notes();
}
}
/// Records footnotes as placed on this page.
pub(super) fn add_notes(&mut self, numbers: Vec<NoteNumber>, height: Length) {
self.page_notes.page.extend(numbers);
self.page_notes.height += height;
}
/// Lays out the footnotes of the page that ends now, so that they end at the bottom
/// margin, below the separator. A page that starts with the rest of a footnote has the
/// continuation separator, and the rest of a footnote that goes on becomes the first
/// footnote of the next page.
pub(super) fn place_notes(&mut self) {
let numbers = std::mem::take(&mut self.page_notes.page);
let height = std::mem::take(&mut self.page_notes.height);
let part = self.page_notes.part.take();
let rest = self.page_notes.rest.take();
if numbers.is_empty() {
return;
}
self.record_places(&numbers, rest.map(|(number, _)| number));
let mut y = self.page_bottom() - height;
let separator = if rest.is_some() {
Separator::Continuation
} else {
Separator::Normal
};
let (items, end) = self.separator(separator, y);
self.items.extend(items);
y = end;
if let NoteColumns::Flow(columns) = self.note_columns() {
for run in self.note_flow(&numbers, columns).1 {
let section = self.column_section(run.column);
self.place_note(§ion, run.number, y + run.top, run.lines);
}
return;
}
let section = self.note_section();
for (index, number) in numbers.iter().enumerate() {
let from = rest.filter(|r| r.0 == *number).map_or(0, |r| r.1);
let to = part.filter(|p| p.number == *number).map(|p| p.lines);
let cut = self.place_note(§ion, *number, y, (from, to));
let next = numbers.get(index + 1).copied();
let size = self.note_size(*number).0 + self.note_after(*number, next);
y += size - cut;
}
if let Some(part) = part {
self.carry_note_rest(part);
}
}
/// Lays out the lines of the footnote `number` from the line `from` to the line `to`, or
/// to its end, with the margins of `section` and the top of the first of them at `y`.
/// Gives the height of the lines before `from`.
fn place_note(
&mut self,
section: &Section,
number: NoteNumber,
y: Length,
(from, to): (usize, Option<usize>),
) -> Length {
let Some(story) = self.note_story(number) else {
return Length::ZERO;
};
if from == 0 && to.is_none() {
let (items, _, lines) = self.placed_note(section, story, y, number);
self.items.extend(items);
self.output.placed.extend(lines);
return Length::ZERO;
}
let (items, lines, cut) = self.note_lines(section, story, y, number, (from, to));
self.items.extend(items);
self.output.placed.extend(lines);
cut
}
/// Records the place of each footnote `numbers` of the page that ends now among those
/// whose references stand on the page, all but the rest `rest` of a footnote from the page
/// before, for the footnotes of the sections that start their numbers again on each page.
fn record_places(&mut self, numbers: &[NoteNumber], rest: Option<NoteNumber>) {
let referenced = numbers.iter().filter(|number| Some(**number) != rest);
for (place, number) in referenced.enumerate() {
let Some(note) = self.output.notes.numbered.get(number.index()) else {
continue;
};
let setup = self.section_layout(note.section).notes.footnotes;
if setup.restart == NoteRestart::EachPage {
self.output.notes.places.0.insert(note.id, place);
}
}
}
/// The footnote `number` in the footnotes part.
fn note_story(&self, number: NoteNumber) -> Option<Footnote<'a>> {
let note = self.output.notes.numbered.get(number.index())?;
let context = self.context;
let blocks = context.notes.by_id.get(¬e.id)?;
Some(Footnote {
id: note.id,
blocks,
})
}
/// The height of a footnote without the space after its last paragraph, and that
/// paragraph.
fn note_size(&mut self, number: NoteNumber) -> (Length, Option<Previous>) {
if let Some(size) = self.output.notes.sizes.get(&number) {
return size.clone();
}
let size = self
.note_story(number)
.map_or((Length::ZERO, None), |note| self.note_end(note, number));
self.output.notes.sizes.insert(number, size.clone());
size
}
/// The space after the last paragraph of a footnote that stays below it: before the
/// footnote `next` of the page, or at the page's foot. Contextual spacing removes it
/// before a footnote whose first paragraph has the same style.
fn note_after(&mut self, number: NoteNumber, next: Option<NoteNumber>) -> Length {
let Some(last) = self.note_size(number).1.filter(|p| !p.after_auto) else {
return Length::ZERO;
};
let first = next.and_then(|n| self.note_story(n));
let dropped = match first.and_then(|note| note.blocks.first()) {
Some(Block::Paragraph(p)) => {
let props = self
.styles
.paragraph_properties_without_list_level(&p.props, None);
last.drops_after_before(props.style.as_deref())
}
_ => false,
};
if dropped { Length::ZERO } else { last.after }
}
/// The height that the footnotes `numbers` add below the footnote `last` of the page:
/// each with the space after it, and without the space after `last` that the first of
/// them removes.
fn notes_span(&mut self, last: Option<NoteNumber>, numbers: &[NoteNumber]) -> Length {
let mut height = Length::ZERO;
let mut before = last;
for number in numbers {
if let Some(before) = before {
height -= self.note_after(before, None) - self.note_after(before, Some(*number));
}
height += self.note_size(*number).0 + self.note_after(*number, None);
before = Some(*number);
}
height
}
/// The height of a separator: where its layout from 0 ends. A page asks it again for each
/// line that brings its first footnotes or lacks room for them, so the height is kept with
/// the story inputs of its layout, and a use with equal story inputs takes it again in
/// place of a new layout. Each use adds the font notes of the layout, as a new layout would,
/// and its warnings as those of a layout of the separator, which count once
/// ([`super::StoryKind::key`]).
fn separator_height(&mut self, separator: Separator) -> Length {
let section = self.note_section();
let inputs = self.story_inputs(§ion);
if let Some((kept, height)) = self.output.notes.separators.get(&separator)
&& *kept == inputs
{
let height = height.clone();
return self.use_separator(separator, height);
}
let mut layout = self.separator_from(inputs.clone(), separator);
let height = SeparatorHeight {
height: layout.y + layout.separator_after(),
warnings: std::mem::take(&mut layout.output.warnings),
notes: layout.shaper.take_notes(),
};
self.output
.notes
.separators
.insert(separator, (inputs, height.clone()));
self.use_separator(separator, height)
}
/// The space below the last line of a separator, in this separator's layout, that takes
/// room above the footnotes: the space after its last paragraph when the target keeps it
/// ([`super::decisions::kept_separator_space`]) and the separator is the written one that
/// the settings list, and none for the separator that Word draws itself.
pub(super) fn separator_after(&self) -> Length {
let listed =
self.context.settings.footnote_separators == crate::styles::NoteSeparators::Listed;
self.previous
.as_ref()
.filter(|last| listed && !last.after_auto)
.and_then(|last| super::decisions::kept_separator_space(&self.context.quirks, last))
.map_or(Length::ZERO, |last| last.after)
}
/// Adds the warnings and the font notes of a layout of `separator`, and gives its height.
fn use_separator(&mut self, separator: Separator, height: SeparatorHeight) -> Length {
let key = StoryKey::Separator(separator);
self.output.join_story_warnings(key, height.warnings);
self.shaper.add_notes(height.notes);
height.height
}
}
/// The place on its page of a note whose first reference is measured on the page `page` of
/// the section `section`, in a pass that knows no earlier place: the count of the notes
/// `before` that were measured there, which a later pass corrects from the pages.
fn place_when_measured(before: &[NumberedNote], (section, page): (SectionIndex, usize)) -> usize {
before
.iter()
.rev()
.take_while(|note| note.section == section && note.page == page)
.count()
}
impl Layout<'_> {
/// Warns once that the note marks in `paragraphs`, the text of a text box or, when
/// `frame`, of a frame, show 1 where the box stands in its note: a footnote mark in a text
/// box of a footnote and an endnote mark in a text box or a frame of an endnote, whose
/// stories do not take the note's number (**Feature not supported**). The warning names
/// `part`.
pub(super) fn warn_of_box_note_marks<'p>(
&mut self,
paragraphs: impl IntoIterator<Item = &'p Paragraph> + Clone,
frame: bool,
part: &str,
) {
let in_footnote = !frame
&& self
.story
.as_ref()
.is_some_and(|story| matches!(story.kind, super::StoryKind::Footnote { .. }));
let in_endnote = self.endnote.is_some();
let footnote_mark = |content: &Content| matches!(content, Content::FootnoteMark);
let endnote_mark = |content: &Content| matches!(content, Content::EndnoteMark);
let shows_one = (in_footnote && holds(paragraphs.clone(), &footnote_mark))
|| (in_endnote && holds(paragraphs, &endnote_mark));
if shows_one {
self.warn_of_feature(crate::Feature::NoteMarkInBox, part);
}
}
}
/// Whether the runs of `paragraphs` hold a content that `found` finds.
fn holds<'p>(
paragraphs: impl IntoIterator<Item = &'p Paragraph>,
found: &dyn Fn(&Content) -> bool,
) -> bool {
paragraphs
.into_iter()
.flat_map(|paragraph| ¶graph.runs)
.flat_map(|run| &run.content)
.any(found)
}