1use f_office_units::scale::THOUSANDTHS;
4use f_office_units::{Length, count_factor};
5
6use crate::character_class::CharacterClass;
7use crate::kinsoku::{Kinsoku, breaks_between};
8use crate::props::EastAsianLanguage;
9
10use crate::props::{TabKind, TabStop};
11use crate::tabs::Tabs;
12use crate::text::{AUTOMATIC_HYPHEN, FaceIndex, Glyph, LINE_END_HYPHEN, SOFT_HYPHEN, SpaceKind};
13
14pub(crate) mod joints;
15
16use joints::JointCounts;
17
18const NO_BREAK_SPACE: char = '\u{a0}';
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum Piece {
24 Glyph(Glyph),
26 Tab(Option<FaceIndex>),
28 PositionTab(Option<FaceIndex>, TabStop),
30 LineBreak(Option<FaceIndex>),
32 PageBreak,
34 ColumnBreak,
36 Note(NoteNumber),
38 Endnote(u16),
41 NoteMarkEnd,
44 EndnoteMarkEnd(u16),
47 Comment(CommentIndex),
50 Anchor(usize),
55 Strut(FaceIndex),
58 Clear,
61 Rule {
64 face: FaceIndex,
66 width: Length,
68 },
69 CheckBox {
71 face: FaceIndex,
73 width: Length,
75 },
76 Shift(Length),
79 Advance(Length),
83 Bar {
86 face: FaceIndex,
88 width: Length,
90 },
91 Vinculum {
96 face: FaceIndex,
98 width: Length,
100 top: Length,
102 thickness: Length,
104 beyond: (Length, Length),
106 clear: Length,
109 },
110 Diagonal {
113 face: FaceIndex,
115 width: Length,
117 bottom: Length,
119 top: Length,
121 thickness: Length,
123 rising: bool,
126 },
127 Object {
129 width: Length,
131 height: Length,
133 raised: Length,
136 picture: Option<usize>,
138 drawing: Option<DrawingIndex>,
140 underlined: bool,
144 run_face: Option<FaceIndex>,
151 joins_before: bool,
157 },
158}
159
160#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163pub struct DrawingIndex(usize);
164
165impl DrawingIndex {
166 pub(crate) const fn new(index: usize) -> Self {
168 Self(index)
169 }
170
171 pub(crate) const fn get(self) -> usize {
173 self.0
174 }
175}
176
177#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
180pub struct CommentIndex(usize);
181
182impl CommentIndex {
183 pub(crate) const fn new(index: usize) -> Self {
185 Self(index)
186 }
187
188 pub(crate) const fn get(self) -> usize {
190 self.0
191 }
192}
193
194#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
198pub struct NoteNumber(usize);
199
200impl NoteNumber {
201 pub(crate) const fn of_index(index: usize) -> Self {
204 Self(index)
205 }
206
207 pub(crate) const fn index(self) -> usize {
209 self.0
210 }
211}
212
213#[derive(Clone, Copy, Debug, PartialEq, Eq)]
215pub struct Placed {
216 pub piece: Piece,
218 pub x: Length,
220 pub advance: Length,
222 pub leader: Option<char>,
224 pub tab: Option<TabKind>,
226}
227
228#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
230pub enum LineEnd {
231 #[default]
233 Wrap,
234 Split,
236 Break(Option<FaceIndex>),
238 PageBreak,
240 ColumnBreak,
242}
243
244#[derive(Clone, Debug, Default, PartialEq, Eq)]
246pub struct Line {
247 pub placed: Vec<Placed>,
249 pub end: LineEnd,
251 pub kept: Option<Fit>,
253 pub wrapped: Option<Fit>,
256 pub would_hang: bool,
260 pub hung: bool,
264 pub anchors: Vec<LineAnchor>,
267 pub hyphen: Option<EndHyphen>,
270 pub written_end_spaces: usize,
274}
275
276#[derive(Clone, Copy, Debug, PartialEq, Eq)]
278pub enum EndHyphen {
279 Automatic,
281 Soft,
283}
284
285#[derive(Clone, Copy, Debug, PartialEq, Eq)]
287pub struct LineAnchor {
288 pub at: usize,
290 pub drawing: usize,
292}
293
294#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
296pub enum Step {
297 Start,
299 Label,
301 AfterLabel,
303 Tab,
306 AlignedTab,
309 Stretched,
311 Space,
313 Object,
315 Leader,
317 Glyph,
319}
320
321#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
324pub struct Fit {
325 pub width: Length,
327 pub end: Length,
329 pub word: Length,
331 pub spaces: Length,
333 pub space: Length,
335 pub space_count: usize,
337 pub last_space_count: usize,
339 pub room: Length,
341 pub over: Length,
344 pub shrinks: bool,
346}
347
348impl Line {
349 #[must_use]
352 pub fn pieces(lines: &[Self]) -> Vec<Piece> {
353 let mut pieces = Vec::new();
354 for line in lines {
355 let mut marks = line.anchors.iter().peekable();
356 for (index, placed) in line.placed.iter().enumerate() {
357 while let Some(mark) = marks.next_if(|mark| mark.at <= index) {
358 pieces.push(Piece::Anchor(mark.drawing));
359 }
360 pieces.push(placed.piece);
361 }
362 pieces.extend(marks.map(|mark| Piece::Anchor(mark.drawing)));
363 match line.end {
364 LineEnd::PageBreak => pieces.push(Piece::PageBreak),
365 LineEnd::ColumnBreak => pieces.push(Piece::ColumnBreak),
366 LineEnd::Break(face) => pieces.push(Piece::LineBreak(face)),
367 LineEnd::Wrap | LineEnd::Split => {}
368 }
369 }
370 pieces
371 }
372
373 #[must_use]
376 pub fn starts_with_page_break(&self, index: usize, last: bool) -> bool {
377 index == 0 && !last && self.holds_only_page_break()
378 }
379
380 #[must_use]
382 pub fn holds_only_page_break(&self) -> bool {
383 self.placed.is_empty() && self.end == LineEnd::PageBreak
384 }
385
386 #[must_use]
390 pub fn first_index(lines: &[Self], breaks: LeadingBreaks) -> usize {
391 let leading = lines
392 .iter()
393 .take_while(|line| line.holds_only_page_break())
394 .count();
395 if leading == lines.len() {
396 return 0;
397 }
398 breaks.before_first_line(leading)
399 }
400
401 #[must_use]
403 pub const fn breaks_page_or_column(&self) -> bool {
404 matches!(self.end, LineEnd::PageBreak | LineEnd::ColumnBreak)
405 }
406}
407
408impl Line {
409 #[must_use]
411 pub fn width(&self) -> Length {
412 self.end_of(self.written())
413 }
414
415 #[must_use]
418 pub fn fit_width(&self) -> Length {
419 let written = self.placed.get(..self.written()).unwrap_or_default();
420 self.width() + written.iter().map(|p| counted(&p.piece)).sum()
421 }
422
423 #[must_use]
426 pub fn written(&self) -> usize {
427 self.last_visible().map_or(0, |last| last + 1)
428 }
429
430 #[must_use]
432 pub fn end_of(&self, pieces: usize) -> Length {
433 pieces
434 .checked_sub(1)
435 .and_then(|last| self.placed.get(last))
436 .map_or(Length::ZERO, |p| p.x + p.advance)
437 }
438
439 #[must_use]
442 pub fn holds_left_to_right_text(&self) -> bool {
443 self.placed
444 .iter()
445 .any(|p| !is_space(&p.piece) && run_rtl(&p.piece) == Some(false))
446 }
447
448 #[must_use]
451 pub(crate) fn holds_right_to_left_text(&self) -> bool {
452 self.placed
453 .iter()
454 .any(|p| !is_space(&p.piece) && run_rtl(&p.piece) == Some(true))
455 }
456
457 #[must_use]
461 pub fn last_visible(&self) -> Option<usize> {
462 let last = self
463 .placed
464 .iter()
465 .rposition(|p| !is_space(&p.piece) && !is_operator_space(&p.piece))?;
466 let spaces = self.placed.len() - 1 - last;
467 Some(last + self.written_end_spaces.min(spaces))
468 }
469
470 #[must_use]
473 pub fn first_stretched(&self) -> usize {
474 let after_tab = self
475 .placed
476 .iter()
477 .rposition(|p| matches!(p.piece, Piece::Tab(_) | Piece::PositionTab(..)))
478 .map_or(0, |i| i + 1);
479 let rest = self.placed.get(after_tab..).unwrap_or(&[]);
480 after_tab
481 + rest
482 .iter()
483 .position(|p| !is_space(&p.piece))
484 .unwrap_or(rest.len())
485 }
486}
487
488#[derive(Clone, Copy, Debug, PartialEq, Eq)]
490enum ThaiText {
491 None,
493 InWord,
495 OnLine,
497}
498
499fn is_thai(piece: &Piece) -> bool {
501 matches!(piece, Piece::Glyph(glyph) if CharacterClass::Thai.contains(glyph.ch))
502}
503
504#[derive(Clone, Debug, PartialEq, Eq)]
506pub struct Frame {
507 pub first_width: Length,
509 pub width: Length,
511 pub area_width: Length,
514 pub first_start: Length,
516 pub start: Length,
518 pub tabs: Tabs,
520 pub shrink: Shrink,
522 pub thai_keeps_spaces: bool,
525 pub end_space_fit: EndSpaceFit,
527 pub kinsoku: Option<Kinsoku>,
530 pub joined_spaces: bool,
534 pub breaking: LineBreaking,
536 pub limits_past_end: bool,
540 pub punctuation: Option<Compression>,
543 pub hyphenation: Option<Hyphenation>,
546 pub overflow_punct: OverflowPunct,
549}
550
551#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
554pub enum OverflowPunct {
555 Off,
557 #[default]
559 Warn,
560 Hang,
563}
564
565#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
567pub enum EndSpaceFit {
568 #[default]
570 WithoutSpaces,
571 WithRightToLeftSpaces,
579}
580
581impl EndSpaceFit {
582 fn between_letters(self, line: &Line) -> bool {
585 self == Self::WithRightToLeftSpaces
586 && line
587 .placed
588 .iter()
589 .filter_map(|p| run_glyph(&p.piece))
590 .any(|glyph| left_to_right(glyph.ch))
591 }
592}
593
594#[derive(Clone, Copy, Debug, Default)]
597struct EndSpaces {
598 width: Length,
599 count: usize,
600 shrink: Length,
601 starts_right_to_left: bool,
603}
604
605#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
608pub struct Hyphenation {
609 pub zone: Option<Length>,
612 pub limit: Option<std::num::NonZeroUsize>,
614}
615
616#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
619pub struct LineBreaking {
620 pub ends_aligned_text: bool,
623 pub note_reference_in_word: bool,
626 pub left_stops_to_line_end: bool,
629 pub leading_breaks: LeadingBreaks,
632}
633
634#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
636pub enum LeadingBreaks {
637 #[default]
639 None,
640 First,
642 All,
644}
645
646impl LeadingBreaks {
647 #[must_use]
649 pub fn before_first_line(self, leading: usize) -> usize {
650 match self {
651 Self::None => 0,
652 Self::First => leading.min(1),
653 Self::All => leading,
654 }
655 }
656}
657
658impl Frame {
659 #[must_use]
664 pub fn on_page(&self, first: bool, column: Length, right_to_left: bool) -> (Length, Length) {
665 let (start, width) = if first {
666 (self.first_start, self.first_width)
667 } else {
668 (self.start, self.width)
669 };
670 if right_to_left {
671 (column - start - width, width)
672 } else {
673 (start, width)
674 }
675 }
676}
677
678#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
682pub enum TrailingTrim {
683 #[default]
685 None,
686 Closing,
688 NonJapaneseCentered,
690 NonTraditionalCentered,
692}
693
694impl TrailingTrim {
695 #[must_use]
697 pub fn trims(self, ch: char) -> bool {
698 match self {
699 Self::None => false,
700 Self::Closing => closing_mark(ch),
701 Self::NonJapaneseCentered => closing_mark(ch) && !japanese_centered_mark(ch),
702 Self::NonTraditionalCentered => closing_mark(ch) && !centered_mark(ch),
703 }
704 }
705}
706
707#[derive(Clone, Copy, Debug, PartialEq, Eq)]
714pub struct Compression {
715 pub ratio: i64,
718 pub middle_dot: bool,
720 pub trailing_trim: TrailingTrim,
722}
723
724#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
728pub struct Halves {
729 pub count: usize,
731 pub em: Length,
733}
734
735impl Halves {
736 fn of(pieces: &[Piece], include_middle_dot: bool) -> Self {
738 pieces
739 .iter()
740 .fold(Self::default(), |halves, piece| match piece {
741 Piece::Glyph(g)
742 if !g.label
743 && g.punctuation_half.is_open()
744 && (closing_mark(g.ch)
745 || opening_mark(g.ch)
746 || (include_middle_dot && middle_dot(g.ch))) =>
747 {
748 Self {
749 count: halves.count + 1,
750 em: halves.em.max(g.punctuation_half.full_em(g.advance)),
751 }
752 }
753 _ => halves,
754 })
755 }
756
757 fn and(self, other: Self) -> Self {
759 Self {
760 count: self.count + other.count,
761 em: self.em.max(other.em),
762 }
763 }
764}
765
766impl Compression {
767 #[must_use]
771 pub fn over(self, halves: Halves, (room, gaps): (Length, i64)) -> Length {
772 if halves.count == 0 || gaps <= 0 || room <= Length::ZERO {
773 return Length::ZERO;
774 }
775 let count = count_factor(halves.count);
776 (room * (self.ratio * count))
777 .div_toward_zero(gaps)
778 .min((halves.em * count).div_toward_zero(2))
779 }
780}
781
782#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
786pub struct JointGaps {
787 pub seen: i64,
789 pub other: i64,
791}
792
793impl JointGaps {
794 #[must_use]
796 pub fn of(self, joints: JointCounts) -> i64 {
797 self.seen * count_factor(joints.seen) + self.other * count_factor(joints.other)
798 }
799}
800
801#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
805pub struct Shrink {
806 pub permille: i64,
808 pub stretch_permille: i64,
812 pub natural: (i64, i64),
815 pub joints: JointGaps,
818}
819
820impl Shrink {
821 #[must_use]
826 pub fn of_natural(self, end: Length) -> Option<Length> {
827 let (part, whole) = self.natural;
828 (whole > 0).then(|| {
829 end - (end * (whole - part))
830 .div_round(whole)
831 .nearest_whole(Length::UNITS_PER_TWIP)
832 })
833 }
834
835 #[must_use]
837 pub fn of(self, advance: Length) -> Length {
838 (advance * self.permille).div_toward_zero(THOUSANDTHS)
839 }
840
841 #[must_use]
851 pub fn over(
852 self,
853 spaces: Length,
854 (space, word): (Length, Length),
855 (count, last): (usize, usize),
856 joints: JointCounts,
857 ) -> Length {
858 if self.stretch_permille == 0 || count == 0 {
859 return spaces;
860 }
861 let (count, last) = (count_factor(count), count_factor(last));
862 let gaps = count - last + self.joints.of(joints);
863 let share = self.stretch_permille * count;
864 spaces.min(((space + word) * share).div_toward_zero(THOUSANDTHS * gaps + share))
865 }
866}
867
868#[must_use]
872pub fn break_lines(pieces: &[Piece], frame: &Frame) -> Vec<Line> {
873 if !pieces.iter().any(|piece| matches!(piece, Piece::Anchor(_))) {
874 return break_pieces(pieces, frame);
875 }
876 let mut marks = Vec::new();
877 let mut rest = Vec::with_capacity(pieces.len());
878 for piece in pieces {
879 match piece {
880 Piece::Anchor(drawing) => marks.push((rest.len(), *drawing)),
881 other => rest.push(*other),
882 }
883 }
884 let mut lines = break_pieces(&rest, frame);
885 give_marks(&mut lines, &rest, &marks);
886 lines
887}
888
889fn give_marks(lines: &mut [Line], pieces: &[Piece], marks: &[(usize, usize)]) {
894 let mut next = 0;
895 let mut spans: Vec<(Vec<usize>, usize)> = Vec::with_capacity(lines.len());
897 for line in lines.iter() {
898 let mut find = |found: &dyn Fn(&Piece) -> bool| {
899 while pieces.get(next).is_some_and(|piece| !found(piece)) {
900 next += 1;
901 }
902 next += 1;
903 next - 1
904 };
905 let placed = line
906 .placed
907 .iter()
908 .map(|placed| find(&|piece| same_piece(piece, &placed.piece)))
909 .collect();
910 if line.end != LineEnd::Wrap && line.end != LineEnd::Split {
911 find(&|piece| {
912 matches!(
913 piece,
914 Piece::LineBreak(_) | Piece::PageBreak | Piece::ColumnBreak
915 )
916 });
917 }
918 spans.push((placed, next));
919 }
920 for &(before, drawing) in marks {
921 let index = spans
922 .iter()
923 .position(|(_, end)| *end > before)
924 .unwrap_or(spans.len().saturating_sub(1));
925 let at = spans.get(index).map_or(0, |(placed, _)| {
926 placed.iter().filter(|&&at| at < before).count()
927 });
928 if let Some(line) = lines.get_mut(index) {
929 line.anchors.push(LineAnchor { at, drawing });
930 }
931 }
932}
933
934fn same_piece(piece: &Piece, placed: &Piece) -> bool {
937 match (piece, placed) {
938 (Piece::Glyph(glyph), Piece::Glyph(shown)) if is_hyphen_point(glyph.ch) => {
939 Glyph {
940 ch: shown.ch,
941 ..*glyph
942 } == *shown
943 }
944 _ => piece == placed,
945 }
946}
947
948fn break_pieces(pieces: &[Piece], frame: &Frame) -> Vec<Line> {
950 let mut breaker = Breaker {
951 frame,
952 thai: ThaiText::None,
953 lines: Vec::new(),
954 line: Line::default(),
955 x: Length::ZERO,
956 shrink: Length::ZERO,
957 spaces: Length::ZERO,
958 space_count: 0,
959 stretching: false,
960 counted: Length::ZERO,
961 room: Length::ZERO,
962 blank: Halves::default(),
963 hyphen_lines: 0,
964 ends_at_point: false,
965 };
966 let mut i = 0;
967 while i < pieces.len() {
968 i = breaker.step(pieces, i);
969 }
970 let after_page_break = breaker
973 .lines
974 .last()
975 .is_some_and(|line| line.end == LineEnd::PageBreak);
976 if !(after_page_break && breaker.line.placed.is_empty()) {
977 settle_soft_hyphens(&mut breaker.line, false);
978 strip_trailing_auto_space(&mut breaker.line);
979 breaker.lines.push(breaker.line);
980 }
981 breaker.lines
982}
983
984struct Breaker<'a> {
985 frame: &'a Frame,
986 thai: ThaiText,
988 lines: Vec<Line>,
989 line: Line,
990 x: Length,
991 shrink: Length,
993 spaces: Length,
996 space_count: usize,
998 stretching: bool,
1001 counted: Length,
1004 room: Length,
1006 blank: Halves,
1008 hyphen_lines: usize,
1010 ends_at_point: bool,
1012}
1013
1014impl Breaker<'_> {
1015 fn step(&mut self, pieces: &[Piece], i: usize) -> usize {
1016 match pieces.get(i) {
1017 Some(Piece::LineBreak(face)) => {
1018 self.finish(LineEnd::Break(*face));
1019 i + 1
1020 }
1021 Some(Piece::PageBreak) => {
1022 self.finish(LineEnd::PageBreak);
1023 i + 1
1024 }
1025 Some(Piece::ColumnBreak) => {
1026 self.finish(LineEnd::ColumnBreak);
1027 i + 1
1028 }
1029 Some(piece @ (Piece::Tab(_) | Piece::PositionTab(..))) => {
1030 if matches!(piece, Piece::Tab(_)) && self.stop_past_end() {
1031 self.finish(LineEnd::Wrap);
1032 }
1033 self.place_tab(*piece, pieces.get(i + 1..).unwrap_or(&[]));
1034 i + 1
1035 }
1036 Some(
1037 piece @ (Piece::Note(_)
1038 | Piece::Endnote(_)
1039 | Piece::NoteMarkEnd
1040 | Piece::EndnoteMarkEnd(_)
1041 | Piece::Comment(_)
1042 | Piece::Strut(_)
1043 | Piece::Clear),
1044 ) => {
1045 self.push(*piece, Length::ZERO);
1046 i + 1
1047 }
1048 Some(
1049 Piece::Glyph(_)
1050 | Piece::Shift(_)
1051 | Piece::Advance(_)
1052 | Piece::Bar { .. }
1053 | Piece::Vinculum { .. }
1054 | Piece::Diagonal { .. }
1055 | Piece::Object { .. }
1056 | Piece::Rule { .. }
1057 | Piece::CheckBox { .. },
1058 ) => self.place_word(pieces, i),
1059 Some(Piece::Anchor(_)) | None => i + 1,
1061 }
1062 }
1063
1064 fn finish(&mut self, end: LineEnd) {
1065 let mut line = std::mem::take(&mut self.line);
1066 settle_soft_hyphens(&mut line, false);
1067 strip_trailing_auto_space(&mut line);
1068 line.end = end;
1069 self.lines.push(line);
1070 self.x = Length::ZERO;
1071 self.thai = ThaiText::None;
1072 self.shrink = Length::ZERO;
1073 self.spaces = Length::ZERO;
1074 self.space_count = 0;
1075 self.stretching = false;
1076 self.counted = Length::ZERO;
1077 self.room = Length::ZERO;
1078 self.blank = Halves::default();
1079 self.hyphen_lines = if std::mem::take(&mut self.ends_at_point) {
1080 self.hyphen_lines + 1
1081 } else {
1082 0
1083 };
1084 }
1085
1086 fn width(&self) -> Length {
1087 if self.on_first_line() {
1088 self.frame.first_width
1089 } else {
1090 self.frame.width
1091 }
1092 }
1093
1094 fn start(&self) -> Length {
1095 if self.on_first_line() {
1096 self.frame.first_start
1097 } else {
1098 self.frame.start
1099 }
1100 }
1101
1102 fn on_first_line(&self) -> bool {
1107 let before = self
1108 .frame
1109 .breaking
1110 .leading_breaks
1111 .before_first_line(self.lines.len());
1112 self.lines.len() == before && self.lines.iter().all(Line::holds_only_page_break)
1113 }
1114
1115 fn stop_past_end(&self) -> bool {
1121 let absolute = self.start() + self.x;
1122 let end = self.start() + self.width();
1123 let (stop, default) = self.frame.tabs.next_stop(absolute);
1124 let past = if absolute <= end {
1125 stop.position > end
1126 } else {
1127 self.room == Length::ZERO
1128 };
1129 let moves = default || self.left_stop_to_line_end(stop);
1130 moves && !self.line.placed.is_empty() && past
1131 }
1132
1133 fn stop_or_line_end(&self, piece: &Piece, stop: TabStop, end: Length) -> TabStop {
1137 if matches!(piece, Piece::Tab(_)) && stop.position > end && self.left_stop_to_line_end(stop)
1138 {
1139 TabStop {
1140 position: end,
1141 ..stop
1142 }
1143 } else {
1144 stop
1145 }
1146 }
1147
1148 fn left_stop_to_line_end(&self, stop: TabStop) -> bool {
1151 stop.kind == TabKind::Left
1153 && self.frame.tabs.is_custom(stop)
1154 && self.frame.breaking.left_stops_to_line_end
1155 }
1156
1157 fn place_tab(&mut self, piece: Piece, after: &[Piece]) {
1158 let absolute = self.start() + self.x;
1159 let stop = match piece {
1161 Piece::PositionTab(_, stop) => stop,
1162 _ => self.frame.tabs.next(absolute),
1163 };
1164 let end = self.start() + self.width();
1165 let stop = self.stop_or_line_end(&piece, stop, end);
1166 let gap = stop.position - absolute;
1167 self.room = self.room.max(stop.position - end);
1170 let at_stop = match stop.kind {
1171 TabKind::Right => gap - following_width(after, None),
1172 TabKind::Center => gap - following_width(after, None).div_toward_zero(2),
1173 TabKind::Decimal => gap - following_width(after, Some('.')),
1174 TabKind::Left => gap,
1175 };
1176 let advance = match stop.kind {
1178 TabKind::Right | TabKind::Center | TabKind::Decimal
1179 if self.frame.breaking.ends_aligned_text =>
1180 {
1181 let width = following_width(after, None);
1187 if stop.position >= end && !self.frame.limits_past_end {
1188 let advance = at_stop.max(Length::ZERO);
1189 self.room = self.room.max(absolute + advance + width - end);
1190 advance
1191 } else {
1192 let limit = if stop.position > end && stop.position <= self.frame.area_width {
1193 self.frame.area_width
1194 } else {
1195 end
1196 };
1197 let advance = at_stop.min(limit - absolute - width).max(Length::ZERO);
1198 self.room = self.room.max((absolute + advance + width).min(limit) - end);
1199 advance
1200 }
1201 }
1202 _ => at_stop,
1203 };
1204 self.push(piece, advance.max(Length::ZERO));
1205 if let Some(placed) = self.line.placed.last_mut() {
1206 placed.leader = stop.leader;
1207 placed.tab = Some(stop.kind);
1208 }
1209 }
1210
1211 fn place_word(&mut self, pieces: &[Piece], i: usize) -> usize {
1212 let end = word_end(pieces, i, self.frame);
1213 let word = pieces.get(i..end).unwrap_or(&[]);
1214 let (_, visible) = widths(word);
1215 let ends = self.fitted_end_spaces(word, pieces.get(end));
1216 let visible = visible + ends.width;
1217 if self.thai != ThaiText::OnLine {
1218 self.thai = if word.iter().any(is_thai) {
1219 ThaiText::InWord
1220 } else {
1221 ThaiText::None
1222 };
1223 }
1224 let fit = self.fit_ending(visible, self.punctuation_over(word), ends);
1225 let room = self
1228 .shrink
1229 .max(self.frame.shrink.of_natural(self.x).unwrap_or(Length::ZERO));
1230 let spaces = !self.line.hung && word.iter().all(is_space) && self.x <= self.width() + room;
1231 let overflows = self.line.hung || fit.end > fit.width + fit.over;
1232 if overflows && !spaces && self.place_hanging_word(word, visible) {
1233 return end;
1234 }
1235 if overflows
1236 && !spaces
1237 && !self.line.hung
1238 && let Some(point) = self.hyphen_point(word)
1239 {
1240 return i + self.place_to_point(word, point, fit);
1241 }
1242 if overflows && !self.line.placed.is_empty() && !spaces {
1243 let tab = self.take_trailing_tab();
1246 settle_soft_hyphens(&mut self.line, tab.is_none());
1247 self.line.wrapped = Some(fit);
1248 self.line.would_hang = !self.line.hung && tab.is_none() && self.fits_before_hang(word);
1251 self.finish(LineEnd::Wrap);
1252 if let Some(tab) = tab {
1253 self.place_tab(tab, pieces.get(i..).unwrap_or(&[]));
1254 }
1255 }
1256 if self.x + visible > self.width() + self.trailing_trim_over(word)
1257 && self.line.placed.is_empty()
1258 {
1259 return i + self.place_split(word);
1260 }
1261 self.line.kept = Some(self.fit(visible));
1262 for piece in word {
1263 self.push(*piece, advance(piece));
1264 }
1265 end
1266 }
1267
1268 fn fitted_end_spaces(&self, word: &[Piece], next: Option<&Piece>) -> EndSpaces {
1270 if self.frame.end_space_fit == EndSpaceFit::WithoutSpaces
1271 || !self.line.holds_left_to_right_text()
1272 {
1273 return EndSpaces::default();
1274 }
1275 let Some(last) = word.iter().rposition(|piece| !is_space(piece)) else {
1276 return EndSpaces::default();
1277 };
1278 let letter = |piece: Option<&Piece>| {
1279 piece
1280 .and_then(run_glyph)
1281 .is_some_and(|glyph| right_to_left(glyph.ch))
1282 };
1283 let between = self.frame.end_space_fit.between_letters(&self.line)
1284 && letter(word.get(last))
1285 && letter(next);
1286 let start = EndSpaces {
1287 starts_right_to_left: letter(word.first()),
1288 ..EndSpaces::default()
1289 };
1290 word.iter()
1291 .skip(last + 1)
1292 .take_while(|piece| is_space(piece) && (between || run_rtl(piece) == Some(true)))
1293 .fold(start, |ends, piece| EndSpaces {
1294 width: ends.width + advance(piece) + counted(piece),
1295 count: ends.count + 1,
1296 shrink: ends.shrink + self.frame.shrink.of(advance(piece)),
1297 ..ends
1298 })
1299 }
1300
1301 fn hyphen_point(&self, word: &[Piece]) -> Option<usize> {
1306 let rules = self.frame.hyphenation?;
1307 if rules
1308 .limit
1309 .is_some_and(|limit| self.hyphen_lines >= limit.get())
1310 {
1311 return None;
1312 }
1313 if rules.zone.is_some_and(|zone| self.width() - self.x <= zone) {
1314 return None;
1315 }
1316 (0..word.len()).rev().find(|&k| {
1317 let Some(part) = word.get(..=k).filter(
1318 |part| matches!(part.last(), Some(Piece::Glyph(g)) if g.ch == AUTOMATIC_HYPHEN),
1319 ) else {
1320 return false;
1321 };
1322 let (_, visible) = widths(part);
1323 let fit = self.fit_with(visible, self.punctuation_over(part));
1324 fit.end <= fit.width + fit.over
1325 })
1326 }
1327
1328 fn place_to_point(&mut self, word: &[Piece], point: usize, wrapped: Fit) -> usize {
1332 let part = word.get(..=point).unwrap_or(&[]);
1333 let (_, visible) = widths(part);
1334 self.line.kept = Some(self.fit_with(visible, self.punctuation_over(part)));
1335 for piece in part {
1336 self.push(*piece, advance(piece));
1337 }
1338 settle_soft_hyphens(&mut self.line, true);
1339 self.line.wrapped = Some(wrapped);
1340 self.ends_at_point = true;
1341 self.finish(LineEnd::Wrap);
1342 part.len()
1343 }
1344
1345 fn place_hanging_word(&mut self, word: &[Piece], visible: Length) -> bool {
1350 if self.frame.overflow_punct != OverflowPunct::Hang
1351 || self.line.hung
1352 || self.has_trailing_tab()
1353 || !self.fits_before_hang(word)
1354 {
1355 return false;
1356 }
1357 self.line.kept = Some(self.fit(visible));
1358 for piece in word {
1359 self.push(*piece, advance(piece));
1360 }
1361 self.line.hung = true;
1362 true
1363 }
1364
1365 fn hanging_prefix<'w>(&self, word: &'w [Piece]) -> Option<&'w [Piece]> {
1370 if self.frame.overflow_punct == OverflowPunct::Off {
1371 return None;
1372 }
1373 let last = word.iter().rposition(|piece| !is_space(piece))?;
1374 let (Some(Piece::Glyph(mark)), Some(rest)) = (word.get(last), word.get(..last)) else {
1375 return None;
1376 };
1377 let hangs = match (self.frame.overflow_punct, mark.east_asian_language) {
1378 (_, Some(EastAsianLanguage::NonEastAsian)) => false,
1379 (OverflowPunct::Hang, Some(EastAsianLanguage::Script(script))) => {
1380 Kinsoku::of(script).hangs(mark.ch)
1381 }
1382 _ => self.frame.kinsoku.is_some_and(|k| k.hangs(mark.ch)),
1383 };
1384 hangs.then_some(rest)
1385 }
1386
1387 fn fits_before_hang(&self, word: &[Piece]) -> bool {
1390 let Some(rest) = self.hanging_prefix(word) else {
1391 return false;
1392 };
1393 let (_, visible) = widths(rest);
1394 let fit = self.fit_with(visible, self.punctuation_over(rest));
1395 fit.end <= fit.width + fit.over
1396 }
1397
1398 fn has_trailing_tab(&self) -> bool {
1400 self.line.placed.len() >= 2
1401 && matches!(
1402 self.line.placed.last().map(|p| &p.piece),
1403 Some(Piece::Tab(_) | Piece::PositionTab(..))
1404 )
1405 }
1406
1407 fn fit(&self, word: Length) -> Fit {
1410 self.fit_with(word, Length::ZERO)
1411 }
1412
1413 fn trailing_trim_over(&self, word: &[Piece]) -> Length {
1416 self.frame
1417 .punctuation
1418 .and_then(|c| trailing_closing_half(word, c.trailing_trim))
1419 .map_or(Length::ZERO, |(_, half)| half)
1420 }
1421
1422 fn punctuation_over(&self, word: &[Piece]) -> Length {
1425 let Some(compression) = self.frame.punctuation else {
1426 return Length::ZERO;
1427 };
1428 let (rest, trimmed) = match trailing_closing_half(word, compression.trailing_trim) {
1429 Some((last, half)) => (word.get(..last).unwrap_or(&[]), half),
1430 None => (word, Length::ZERO),
1431 };
1432 let inner = compression.over(
1433 self.blank.and(Halves::of(rest, compression.middle_dot)),
1434 self.stretch(),
1435 );
1436 trimmed + inner
1437 }
1438
1439 fn stretch(&self) -> (Length, i64) {
1443 let first = self.line.first_stretched();
1444 let placed = self.line.placed.get(first..).unwrap_or(&[]);
1445 let spaces =
1446 i64::try_from(placed.iter().filter(|p| is_space(&p.piece)).count()).unwrap_or(0);
1447 let gaps = if spaces > 0 {
1448 spaces
1449 } else {
1450 let full_width = |p: &Placed| matches!(p.piece, Piece::Glyph(g) if CharacterClass::FullWidthCell.contains(g.ch));
1451 let labeled = |p: &Placed| matches!(p.piece, Piece::Glyph(g) if g.label);
1452 i64::try_from(
1453 placed
1454 .windows(2)
1455 .filter(|pair| {
1456 let (Some(a), Some(b)) = (pair.first(), pair.get(1)) else {
1457 return false;
1458 };
1459 !labeled(a) && !labeled(b) && (full_width(a) || full_width(b))
1460 })
1461 .count(),
1462 )
1463 .unwrap_or(0)
1464 };
1465 let end_gap = match self.line.placed.last().map(|p| &p.piece) {
1466 Some(Piece::Glyph(g)) => g.trailing_auto_space,
1467 _ => Length::ZERO,
1468 };
1469 (self.width() - (self.x - end_gap), gaps)
1470 }
1471
1472 fn fit_with(&self, word: Length, punctuation: Length) -> Fit {
1475 self.fit_ending(word, punctuation, EndSpaces::default())
1476 }
1477
1478 fn fit_ending(&self, word: Length, punctuation: Length, ends: EndSpaces) -> Fit {
1480 let last: Vec<&Placed> = self
1485 .line
1486 .placed
1487 .iter()
1488 .rev()
1489 .take_while(|p| self.stretching && (is_space(&p.piece) || is_operator_space(&p.piece)))
1490 .collect();
1491 let space: Length = last.iter().map(|p| p.advance).sum();
1492 let last_space_count = last.iter().filter(|p| is_space(&p.piece)).count();
1493 let end = self.x + self.counted + word;
1494 let kept = self.frame.thai_keeps_spaces && self.thai != ThaiText::None;
1495 let over = if kept {
1496 Length::ZERO
1497 } else {
1498 self.frame
1499 .shrink
1500 .of_natural(end)
1501 .unwrap_or_else(|| self.shrink_over(&last, (space, word), last_space_count, ends))
1502 };
1503 Fit {
1504 width: self.width(),
1505 end,
1506 word,
1507 spaces: self.spaces,
1508 space,
1509 space_count: self.space_count,
1510 last_space_count,
1511 room: self.room,
1512 over: over + self.room + punctuation,
1513 shrinks: !kept && (self.frame.shrink.permille > 0 || self.frame.shrink.natural.1 > 0),
1514 }
1515 }
1516
1517 fn shrink_over(
1526 &self,
1527 last: &[&Placed],
1528 (space, word): (Length, Length),
1529 last_count: usize,
1530 ends: EndSpaces,
1531 ) -> Length {
1532 let rtl_before = last.iter().all(|p| run_rtl(&p.piece) == Some(true));
1533 let letters_before = self.frame.end_space_fit.between_letters(&self.line)
1534 && ends.starts_right_to_left
1535 && self
1536 .line
1537 .placed
1538 .iter()
1539 .rev()
1540 .find(|p| !is_space(&p.piece))
1541 .and_then(|p| run_glyph(&p.piece))
1542 .is_some_and(|glyph| right_to_left(glyph.ch));
1543 let kept_before = self.frame.end_space_fit != EndSpaceFit::WithoutSpaces
1544 && (rtl_before || letters_before)
1545 && !last.is_empty()
1546 && self.line.holds_left_to_right_text();
1547 let (space, hanging) = if kept_before {
1548 (Length::ZERO, 0)
1549 } else {
1550 (space, last_count)
1551 };
1552 let joints = if self.frame.shrink.joints == JointGaps::default() {
1553 JointCounts::default()
1554 } else {
1555 joints::joint_counts(&self.line.placed)
1556 };
1557 self.frame.shrink.over(
1558 self.shrink + ends.shrink,
1559 (space, word),
1560 (self.space_count + ends.count, hanging + ends.count),
1561 joints,
1562 )
1563 }
1564
1565 fn take_trailing_tab(&mut self) -> Option<Piece> {
1567 if self.line.placed.len() >= 2
1568 && matches!(
1569 self.line.placed.last().map(|p| &p.piece),
1570 Some(Piece::Tab(_) | Piece::PositionTab(..))
1571 )
1572 {
1573 let tab = self.line.placed.pop()?;
1574 self.x = tab.x;
1575 Some(tab.piece)
1576 } else {
1577 None
1578 }
1579 }
1580
1581 fn place_split(&mut self, word: &[Piece]) -> usize {
1586 let mut placed = 0;
1587 for piece in word {
1588 let a = advance(piece);
1589 let end_gap = match piece {
1590 Piece::Glyph(g) => g.trailing_auto_space,
1591 _ => Length::ZERO,
1592 };
1593 if placed > 0 && self.x + self.counted + a - end_gap + counted(piece) > self.width() {
1594 break;
1595 }
1596 self.push(*piece, a);
1597 placed += 1;
1598 }
1599 if placed < word.len() {
1600 self.finish(LineEnd::Split);
1601 }
1602 placed
1603 }
1604
1605 fn push(&mut self, piece: Piece, advance: Length) {
1606 self.line.placed.push(Placed {
1607 piece,
1608 x: self.x,
1609 advance,
1610 leader: None,
1611 tab: None,
1612 });
1613 self.x += advance;
1614 if is_thai(&piece) {
1615 self.thai = ThaiText::OnLine;
1616 }
1617 if matches!(piece, Piece::Tab(_) | Piece::PositionTab(..)) {
1620 self.shrink = Length::ZERO;
1621 self.spaces = Length::ZERO;
1622 self.space_count = 0;
1623 self.stretching = false;
1624 self.counted = Length::ZERO;
1625 self.blank = Halves::default();
1626 } else if !is_space(&piece) {
1627 self.stretching = true;
1628 } else if self.stretching {
1629 self.shrink += self.frame.shrink.of(advance);
1630 self.spaces += advance;
1631 self.space_count += 1;
1632 }
1633 self.counted += counted(&piece);
1634 let include_middle_dot = self.frame.punctuation.is_some_and(|c| c.middle_dot);
1635 self.blank = self.blank.and(Halves::of(&[piece], include_middle_dot));
1636 }
1637}
1638
1639fn word_end(pieces: &[Piece], i: usize, frame: &Frame) -> usize {
1644 let mut j = i;
1645 loop {
1646 match pieces.get(j) {
1647 Some(Piece::Glyph(g))
1648 if g.ch != ' ' || matches!(g.space, SpaceKind::Equation | SpaceKind::Assembly) =>
1649 {
1650 j += 1;
1651 if (g.space == SpaceKind::Operator && !pieces.get(j).is_some_and(is_operator_space))
1652 || ends_word_after(g, pieces.get(j), frame.kinsoku)
1653 {
1654 return j;
1655 }
1656 }
1657 Some(
1660 Piece::Shift(_)
1661 | Piece::Bar { .. }
1662 | Piece::Vinculum { .. }
1663 | Piece::Diagonal { .. }
1664 | Piece::Endnote(_)
1665 | Piece::NoteMarkEnd
1666 | Piece::EndnoteMarkEnd(_),
1667 ) => j += 1,
1668 Some(
1671 Piece::Object {
1672 joins_before: true, ..
1673 }
1674 | Piece::Advance(_),
1675 ) => return j + 1,
1676 Some(Piece::Note(_)) if frame.breaking.note_reference_in_word => {
1680 j += 1;
1681 let before = j.checked_sub(2).and_then(|k| pieces.get(k));
1682 if let Some(Piece::Glyph(g)) = before
1683 && ends_word_after(g, pieces.get(j), frame.kinsoku)
1684 {
1685 return j;
1686 }
1687 }
1688 Some(_) if frame.joined_spaces && joins(pieces, (i, j)) => j = spaces_end(pieces, j),
1690 _ => break,
1691 }
1692 }
1693 spaces_end(pieces, j).max(i + 1)
1694}
1695
1696#[must_use]
1699pub(crate) fn widest_word(pieces: &[Piece], frame: &Frame) -> Length {
1700 let mut widest = Length::ZERO;
1701 let mut start = 0;
1702 while start < pieces.len() {
1703 let end = word_end(pieces, start, frame);
1704 widest = widest.max(widths(pieces.get(start..end).unwrap_or_default()).1);
1705 start = end;
1706 }
1707 widest
1708}
1709
1710fn spaces_end(pieces: &[Piece], mut j: usize) -> usize {
1712 while matches!(pieces.get(j), Some(p) if is_space(p)) {
1713 j += 1;
1714 }
1715 j
1716}
1717
1718fn joins(pieces: &[Piece], (i, j): (usize, usize)) -> bool {
1721 let no_break =
1722 |piece: Option<&Piece>| matches!(piece, Some(Piece::Glyph(g)) if g.ch == NO_BREAK_SPACE);
1723 let before = j > i && no_break(j.checked_sub(1).and_then(|k| pieces.get(k)));
1724 pieces.get(j).is_some_and(is_space) && (before || no_break(pieces.get(spaces_end(pieces, j))))
1725}
1726
1727fn ends_word_after(before: &Glyph, next: Option<&Piece>, kinsoku: Option<Kinsoku>) -> bool {
1730 if matches!(
1731 before.ch,
1732 '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | SOFT_HYPHEN
1733 ) {
1734 return true;
1735 }
1736 let Some(Piece::Glyph(next)) = next else {
1737 return false;
1738 };
1739 if next.ch == ' ' {
1740 return false;
1741 }
1742 let kinsoku = kinsoku.map(|k| k.for_pair(before.east_asian_language, next.east_asian_language));
1743 breaks_between(before.ch, next.ch, kinsoku)
1744}
1745
1746const fn is_hyphen_point(ch: char) -> bool {
1749 matches!(ch, SOFT_HYPHEN | AUTOMATIC_HYPHEN)
1750}
1751
1752fn widths(word: &[Piece]) -> (Length, Length) {
1757 let total: Length = word.iter().map(|p| advance(p) + counted(p)).sum();
1758 let trailing: Length = word
1759 .iter()
1760 .rev()
1761 .take_while(|p| is_space(p) || is_operator_space(p))
1762 .map(|p| advance(p) + counted(p))
1763 .sum();
1764 let last_auto_space = match word.last() {
1765 Some(Piece::Glyph(g)) => g.trailing_auto_space,
1766 _ => Length::ZERO,
1767 };
1768 let hyphen = match word.last() {
1769 Some(Piece::Glyph(g)) if is_hyphen_point(g.ch) => g.advance,
1770 _ => Length::ZERO,
1771 };
1772 (total, total - trailing - last_auto_space + hyphen)
1773}
1774
1775fn strip_trailing_auto_space(line: &mut Line) {
1778 if let Some(last) = line.placed.last_mut()
1779 && let Piece::Glyph(g) = &mut last.piece
1780 && g.trailing_auto_space > Length::ZERO
1781 {
1782 let gap = g.trailing_auto_space;
1783 g.advance -= gap;
1784 last.advance -= gap;
1785 if g.auto_space > Length::ZERO {
1786 g.auto_space = (g.auto_space - gap).max(Length::ZERO);
1787 }
1788 g.trailing_auto_space = Length::ZERO;
1789 }
1790}
1791
1792fn settle_soft_hyphens(line: &mut Line, wrapped: bool) {
1796 if wrapped
1797 && let Some(last) = line.placed.last_mut()
1798 && let Piece::Glyph(g) = &mut last.piece
1799 && is_hyphen_point(g.ch)
1800 {
1801 let hyphen = if g.ch == AUTOMATIC_HYPHEN {
1802 g.ch = LINE_END_HYPHEN;
1803 EndHyphen::Automatic
1804 } else {
1805 g.ch = '-';
1806 EndHyphen::Soft
1807 };
1808 last.advance = g.advance;
1809 line.hyphen = Some(hyphen);
1810 }
1811 line.placed
1812 .retain(|p| !matches!(p.piece, Piece::Glyph(g) if is_hyphen_point(g.ch)));
1813}
1814
1815pub(crate) fn following_width(after: &[Piece], decimal: Option<char>) -> Length {
1819 let mut total = Length::ZERO;
1820 let mut visible = Length::ZERO;
1821 for piece in after {
1822 match piece {
1823 Piece::Glyph(glyph) => {
1824 if Some(glyph.ch) == decimal {
1825 return total;
1826 }
1827 total += glyph.advance + glyph.counted;
1828 if glyph.ch != ' ' {
1829 visible = total;
1830 }
1831 }
1832 Piece::Object { width, .. } => {
1833 total += *width;
1834 visible = total;
1835 }
1836 _ => break,
1837 }
1838 }
1839 if decimal.is_some() { total } else { visible }
1840}
1841
1842const fn counted(piece: &Piece) -> Length {
1845 match piece {
1846 Piece::Glyph(g) if !is_hyphen_point(g.ch) => g.counted,
1847 _ => Length::ZERO,
1848 }
1849}
1850
1851pub(crate) const fn advance(piece: &Piece) -> Length {
1852 match piece {
1853 Piece::Glyph(g) if is_hyphen_point(g.ch) => Length::ZERO,
1854 Piece::Glyph(g) => g.advance,
1855 Piece::Shift(length) | Piece::Advance(length) => *length,
1856 Piece::Object { width, .. } | Piece::Rule { width, .. } | Piece::CheckBox { width, .. } => {
1857 *width
1858 }
1859 Piece::Bar { .. }
1860 | Piece::Vinculum { .. }
1861 | Piece::Diagonal { .. }
1862 | Piece::Tab(_)
1863 | Piece::PositionTab(..)
1864 | Piece::LineBreak(_)
1865 | Piece::PageBreak
1866 | Piece::ColumnBreak
1867 | Piece::Note(_)
1868 | Piece::Endnote(_)
1869 | Piece::NoteMarkEnd
1870 | Piece::EndnoteMarkEnd(_)
1871 | Piece::Comment(_)
1872 | Piece::Anchor(_)
1873 | Piece::Strut(_)
1874 | Piece::Clear => Length::ZERO,
1875 }
1876}
1877
1878fn trailing_closing_half(word: &[Piece], trim: TrailingTrim) -> Option<(usize, Length)> {
1881 if trim == TrailingTrim::None {
1882 return None;
1883 }
1884 let last = word.iter().rposition(|piece| !is_space(piece))?;
1885 match word.get(last) {
1886 Some(Piece::Glyph(mark)) if mark.punctuation_half.is_open() && trim.trims(mark.ch) => {
1887 Some((
1888 last,
1889 mark.punctuation_half
1890 .full_em(mark.advance)
1891 .div_toward_zero(2),
1892 ))
1893 }
1894 _ => None,
1895 }
1896}
1897
1898#[must_use]
1901pub fn closing_mark(ch: char) -> bool {
1902 matches!(
1903 ch,
1904 '\u{3001}'
1905 | '\u{3002}'
1906 | '\u{FF0C}'
1907 | '\u{FF0E}'
1908 | '\u{FF1A}'
1909 | '\u{FF1B}'
1910 | '\u{FF01}'
1911 | '\u{300D}'
1912 | '\u{300F}'
1913 | '\u{FF09}'
1914 | '\u{3011}'
1915 | '\u{3015}'
1916 | '\u{3009}'
1917 | '\u{300B}'
1918 | '\u{FF5D}'
1919 | '\u{FF3D}'
1920 )
1921}
1922
1923#[must_use]
1927pub const fn centered_mark(ch: char) -> bool {
1928 matches!(
1929 ch,
1930 '\u{FF0C}' | '\u{3001}' | '\u{3002}' | '\u{FF1B}' | '\u{FF1A}'
1931 )
1932}
1933
1934#[must_use]
1937pub const fn japanese_centered_mark(ch: char) -> bool {
1938 matches!(ch, '\u{FF1A}' | '\u{FF1B}' | '\u{30FB}')
1939}
1940
1941#[must_use]
1944pub const fn middle_dot(ch: char) -> bool {
1945 ch == '\u{30FB}'
1946}
1947
1948#[must_use]
1951pub fn opening_mark(ch: char) -> bool {
1952 matches!(
1953 ch,
1954 '\u{300C}'
1955 | '\u{300E}'
1956 | '\u{FF08}'
1957 | '\u{3010}'
1958 | '\u{3014}'
1959 | '\u{3008}'
1960 | '\u{300A}'
1961 | '\u{FF5B}'
1962 | '\u{FF3B}'
1963 )
1964}
1965
1966#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1968pub(crate) enum KernedMark {
1969 Left,
1971 Right,
1974}
1975
1976#[must_use]
1991pub(crate) fn kerned_pair(
1992 left: char,
1993 right: char,
1994 script: Option<crate::props::EastAsianScript>,
1995) -> Option<KernedMark> {
1996 #[derive(Clone, Copy, PartialEq, Eq)]
1997 enum Kind {
1998 Opening,
1999 Closing,
2000 Middle,
2001 }
2002 let kind = |ch: char| -> Option<Kind> {
2003 use crate::props::EastAsianScript::{Japanese, Simplified, Traditional};
2004 if opening_mark(ch) {
2005 return Some(Kind::Opening);
2006 }
2007 if matches!(
2008 ch,
2009 '\u{300D}'
2010 | '\u{300F}'
2011 | '\u{FF09}'
2012 | '\u{3011}'
2013 | '\u{3015}'
2014 | '\u{3009}'
2015 | '\u{300B}'
2016 | '\u{FF5D}'
2017 | '\u{FF3D}'
2018 ) {
2019 return Some(Kind::Closing);
2020 }
2021 match (ch, script) {
2022 ('\u{3001}' | '\u{3002}' | '\u{FF0C}' | '\u{FF0E}', Some(Simplified | Japanese))
2023 | ('\u{FF01}' | '\u{FF1A}' | '\u{FF1B}', Some(Simplified)) => Some(Kind::Closing),
2024 ('\u{3001}' | '\u{3002}' | '\u{FF0C}' | '\u{FF0E}', Some(Traditional))
2025 | ('\u{FF1A}' | '\u{FF1B}', Some(Japanese | Traditional))
2026 | ('\u{30FB}', Some(Japanese)) => Some(Kind::Middle),
2027 _ => None,
2028 }
2029 };
2030 match (kind(left), kind(right)) {
2031 (Some(Kind::Closing), Some(_)) => Some(KernedMark::Left),
2032 (Some(_), Some(Kind::Opening)) => Some(KernedMark::Right),
2033 _ => None,
2034 }
2035}
2036
2037#[must_use]
2040pub fn is_space(piece: &Piece) -> bool {
2041 matches!(piece, Piece::Glyph(g) if g.ch == ' ' && g.space == SpaceKind::Free)
2042}
2043
2044#[must_use]
2047pub fn stretches(piece: &Piece) -> bool {
2048 is_space(piece) || matches!(piece, Piece::Glyph(g) if g.space == SpaceKind::NoBreak)
2049}
2050
2051fn is_operator_space(piece: &Piece) -> bool {
2054 matches!(piece, Piece::Glyph(g) if g.space == SpaceKind::Operator)
2055}
2056
2057pub(crate) const fn run_glyph(piece: &Piece) -> Option<&Glyph> {
2060 match piece {
2061 Piece::Glyph(glyph) if !glyph.label => Some(glyph),
2062 _ => None,
2063 }
2064}
2065
2066pub(crate) fn run_rtl(piece: &Piece) -> Option<bool> {
2068 run_glyph(piece).map(|glyph| glyph.direction.class().is_some())
2069}
2070
2071pub(crate) fn right_to_left(ch: char) -> bool {
2073 matches!(
2074 unicode_bidi::bidi_class(ch),
2075 unicode_bidi::BidiClass::R | unicode_bidi::BidiClass::AL
2076 )
2077}
2078
2079fn left_to_right(ch: char) -> bool {
2081 unicode_bidi::bidi_class(ch) == unicode_bidi::BidiClass::L
2082}
2083
2084#[cfg(test)]
2085mod tests {
2086 use super::{
2087 EndHyphen, EndSpaceFit, Frame, Hyphenation, JointCounts, JointGaps, LeadingBreaks, Line,
2088 LineBreaking, LineEnd, NoteNumber, Piece, Shrink, break_lines, following_width, is_space,
2089 };
2090 use crate::props::{TabKind, TabStop};
2091 use crate::quirks::{AlignedTabOverrun, LeftStopPastEnd, NoteReferenceBreak};
2092 use crate::tabs::Tabs;
2093 use crate::text::AUTOMATIC_HYPHEN;
2094 use crate::text::{FaceIndex, Glyph, SpaceKind};
2095 use f_office_units::Length;
2096
2097 #[test]
2098 fn keeps_a_footnote_s_place_from_zero() {
2099 assert_eq!(NoteNumber::of_index(4).index(), 4);
2100 }
2101
2102 fn glyphs(text: &str) -> Vec<Piece> {
2103 text.chars()
2104 .map(|ch| Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch)))
2105 .collect()
2106 }
2107
2108 fn marked_from(text: &str, first: usize) -> Vec<Piece> {
2111 let mut pieces = glyphs(text);
2112 for piece in pieces.iter_mut().skip(first) {
2113 if let Piece::Glyph(glyph) = piece {
2114 glyph.direction = crate::text::RunDirection::of(true, None);
2115 }
2116 }
2117 pieces
2118 }
2119
2120 #[test]
2121 fn fits_a_word_with_its_rtl_end_spaces_beside_left_to_right_text() {
2122 let mixed = marked_from("ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}", 3);
2125 let fitted = |width| Frame {
2126 end_space_fit: EndSpaceFit::WithRightToLeftSpaces,
2127 ..frame(width)
2128 };
2129 assert_eq!(
2130 texts(&break_lines(&mixed, &frame(85))),
2131 ["ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} ", "\u{5d4}\u{5d5}"]
2132 );
2133 assert_eq!(
2134 texts(&break_lines(&mixed, &fitted(85))),
2135 ["ab \u{5d0}\u{5d1} ", "\u{5d2}\u{5d3} \u{5d4}\u{5d5}"]
2136 );
2137 let plain = glyphs("ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}");
2140 assert_eq!(
2141 texts(&break_lines(&plain, &fitted(85))),
2142 ["ab \u{5d0}\u{5d1} ", "\u{5d2}\u{5d3} \u{5d4}\u{5d5}"]
2143 );
2144 let latin_after = glyphs("ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} cd");
2145 assert_eq!(
2146 texts(&break_lines(&latin_after, &fitted(85))),
2147 ["ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} ", "cd"]
2148 );
2149 let pure = marked_from("\u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}", 0);
2151 assert_eq!(
2152 texts(&break_lines(&pure, &fitted(55))),
2153 texts(&break_lines(&pure, &frame(55)))
2154 );
2155 let plain_only = glyphs("\u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}");
2158 assert_eq!(
2159 texts(&break_lines(&plain_only, &fitted(55))),
2160 ["\u{5d0}\u{5d1} \u{5d2}\u{5d3} ", "\u{5d4}\u{5d5}"]
2161 );
2162 }
2163
2164 #[test]
2165 fn counts_kept_rtl_spaces_as_spaces_of_a_justified_line() {
2166 let mixed = marked_from(
2169 "ab cd ef gh \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}",
2170 12,
2171 );
2172 let justified = |width| Frame {
2173 shrink: Shrink {
2174 permille: 250,
2175 stretch_permille: 500,
2176 natural: (0, 0),
2177 joints: JointGaps::default(),
2178 },
2179 end_space_fit: EndSpaceFit::WithRightToLeftSpaces,
2180 ..frame(width)
2181 };
2182 let fitted = [
2183 "ab cd ef gh \u{5d0}\u{5d1} \u{5d2}\u{5d3} ",
2184 "\u{5d4}\u{5d5}",
2185 ];
2186 let wrapped = [
2187 "ab cd ef gh \u{5d0}\u{5d1} ",
2188 "\u{5d2}\u{5d3} \u{5d4}\u{5d5}",
2189 ];
2190 assert_eq!(texts(&break_lines(&mixed, &justified(169))), fitted);
2193 assert_eq!(texts(&break_lines(&mixed, &justified(168))), wrapped);
2196 let plain = glyphs("ab cd ef gh \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}");
2198 assert_eq!(texts(&break_lines(&plain, &justified(169))), fitted);
2199 assert_eq!(texts(&break_lines(&plain, &justified(168))), wrapped);
2200 let only = glyphs(
2203 "\u{5e9}\u{5ea} \u{5e7}\u{5e8} \u{5e6}\u{5e4} \u{5e2}\u{5e1} \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}",
2204 );
2205 for width in 160..180 {
2206 let hanging = Frame {
2207 end_space_fit: EndSpaceFit::WithoutSpaces,
2208 ..justified(width)
2209 };
2210 assert_eq!(
2211 texts(&break_lines(&only, &justified(width))),
2212 texts(&break_lines(&only, &hanging)),
2213 "{width}"
2214 );
2215 }
2216 }
2217
2218 fn frame(width: i64) -> Frame {
2219 Frame {
2220 first_width: Length::from_units(width),
2221 width: Length::from_units(width),
2222 area_width: Length::from_units(width),
2223 first_start: Length::ZERO,
2224 start: Length::ZERO,
2225 tabs: Tabs::new([], Length::from_units(25), None),
2226 shrink: Shrink::default(),
2227 thai_keeps_spaces: false,
2228 end_space_fit: EndSpaceFit::WithoutSpaces,
2229 kinsoku: None,
2230 joined_spaces: false,
2231 breaking: LineBreaking::default(),
2232 limits_past_end: true,
2233 punctuation: None,
2234 hyphenation: None,
2235 overflow_punct: super::OverflowPunct::Warn,
2236 }
2237 }
2238
2239 fn texts(lines: &[Line]) -> Vec<String> {
2240 lines
2241 .iter()
2242 .map(|line| {
2243 line.placed
2244 .iter()
2245 .map(|p| match p.piece {
2246 Piece::Glyph(g) => g.ch,
2247 _ => '|',
2248 })
2249 .collect()
2250 })
2251 .collect()
2252 }
2253
2254 #[test]
2255 fn anchor_marks_change_no_line_and_go_to_the_line_of_the_piece_after_them() {
2256 let text = glyphs("ab cd ef");
2257 let mut marked = text.clone();
2259 for (at, drawing) in [(8, 3), (6, 2), (4, 1), (0, 0)] {
2260 marked.insert(at, Piece::Anchor(drawing));
2261 }
2262 for width in [25, 45, 55, 100] {
2263 assert_eq!(
2264 texts(&break_lines(&marked, &frame(width))),
2265 texts(&break_lines(&text, &frame(width))),
2266 "{width}"
2267 );
2268 }
2269 let anchors = |lines: &[Line]| -> Vec<Vec<(usize, usize)>> {
2270 lines
2271 .iter()
2272 .map(|line| line.anchors.iter().map(|a| (a.at, a.drawing)).collect())
2273 .collect()
2274 };
2275 let lines = break_lines(&marked, &frame(55));
2276 assert_eq!(texts(&lines), ["ab cd ", "ef"]);
2277 assert_eq!(
2278 anchors(&lines),
2279 [vec![(0, 0), (4, 1)], vec![(0, 2), (2, 3)]]
2280 );
2281 let again = break_lines(&Line::pieces(&lines), &frame(100));
2283 assert_eq!(anchors(&again), [vec![(0, 0), (4, 1), (6, 2), (8, 3)]]);
2284 }
2285
2286 #[test]
2287 fn a_footnote_reference_as_text_keeps_the_closing_parenthesis_after_it_on_its_line() {
2288 let with = |note_reference_break| Frame {
2289 breaking: LineBreaking {
2290 note_reference_in_word: note_reference_break == NoteReferenceBreak::AsText,
2291 ..LineBreaking::default()
2292 },
2293 ..frame(65)
2294 };
2295 let mut pieces = glyphs("ab (c1");
2296 pieces.push(Piece::Note(NoteNumber::of_index(0)));
2297 pieces.extend(glyphs(") d"));
2298 assert_eq!(
2299 texts(&break_lines(&pieces, &with(NoteReferenceBreak::After))),
2300 ["ab (c1|", ") d"]
2301 );
2302 assert_eq!(
2303 texts(&break_lines(&pieces, &with(NoteReferenceBreak::AsText))),
2304 ["ab ", "(c1|) d"]
2305 );
2306 let mut spaced = glyphs("ab c1");
2308 spaced.push(Piece::Note(NoteNumber::of_index(0)));
2309 spaced.extend(glyphs(" de"));
2310 assert_eq!(
2311 texts(&break_lines(&spaced, &with(NoteReferenceBreak::AsText))),
2312 ["ab c1| ", "de"]
2313 );
2314 }
2315
2316 #[test]
2317 fn a_joined_space_run_keeps_the_words_on_both_of_its_sides_on_one_line() {
2318 let with = |joined_spaces| Frame {
2319 joined_spaces,
2320 ..frame(70)
2321 };
2322 for (text, apart, together) in [
2325 (
2326 "aa bb\u{a0} cc",
2327 ["aa bb\u{a0} ", "cc"],
2328 ["aa ", "bb\u{a0} cc"],
2329 ),
2330 (
2331 "aa bb \u{a0}cc",
2332 ["aa bb ", "\u{a0}cc"],
2333 ["aa ", "bb \u{a0}cc"],
2334 ),
2335 (
2336 "aa b \u{a0} cc",
2337 ["aa b \u{a0} ", "cc"],
2338 ["aa ", "b \u{a0} cc"],
2339 ),
2340 ("aa bb cc", ["aa bb ", "cc"], ["aa bb ", "cc"]),
2341 (
2342 "aa bb\u{a0}cc",
2343 ["aa ", "bb\u{a0}cc"],
2344 ["aa ", "bb\u{a0}cc"],
2345 ),
2346 ] {
2347 assert_eq!(texts(&break_lines(&glyphs(text), &with(false))), apart);
2348 assert_eq!(texts(&break_lines(&glyphs(text), &with(true))), together);
2349 }
2350 }
2351
2352 #[test]
2353 fn breaks_east_asian_text_between_characters_with_kinsoku() {
2354 use crate::kinsoku::Kinsoku;
2355 use crate::props::EastAsianScript;
2356 let with = |kinsoku: Option<Kinsoku>| Frame {
2357 kinsoku,
2358 ..frame(40)
2359 };
2360 let text = glyphs("ab 日本語、文字");
2361 let latin = break_lines(&text, &with(None));
2364 assert_eq!(texts(&latin), vec!["ab ", "日本語、", "文字"]);
2365 let japanese = Some(Kinsoku::of(EastAsianScript::Japanese));
2367 let lines = break_lines(&text, &with(japanese));
2368 assert_eq!(texts(&lines), vec!["ab 日", "本語、文", "字"]);
2369 let mark = glyphs("日本語文、字");
2372 let kept = break_lines(&mark, &with(japanese));
2373 assert_eq!(texts(&kept), vec!["日本語", "文、字"]);
2374 let free = break_lines(&mark, &with(Some(Kinsoku::FREE)));
2375 assert_eq!(texts(&free), vec!["日本語文", "、字"]);
2376 }
2377
2378 #[test]
2379 fn marks_a_line_before_a_word_that_fits_without_its_hanging_mark() {
2380 use crate::kinsoku::Kinsoku;
2381 use crate::props::EastAsianScript;
2382 let simplified = Kinsoku::of(EastAsianScript::Simplified);
2383 let with = |kinsoku: Kinsoku| Frame {
2384 kinsoku: Some(kinsoku),
2385 ..frame(40)
2386 };
2387 let hangs = |text: &str, kinsoku: Kinsoku| {
2388 let lines = break_lines(&glyphs(text), &with(kinsoku));
2389 (
2390 texts(&lines),
2391 lines.iter().map(|l| l.would_hang).collect::<Vec<_>>(),
2392 )
2393 };
2394 let lines = |a: &[&str]| a.iter().map(|t| (*t).to_owned()).collect::<Vec<_>>();
2398 assert_eq!(
2399 hangs("一二三四,五", simplified),
2400 (lines(&["一二三", "四,五"]), vec![true, false])
2401 );
2402 assert_eq!(
2403 hangs("一(ab)", simplified),
2404 (lines(&["一", "(ab)"]), vec![true, false])
2405 );
2406 let no = |text: &str, kinsoku: Kinsoku| {
2410 let (_, hung) = hangs(text, kinsoku);
2411 assert!(hung.iter().all(|hang| !hang), "{text}");
2412 };
2413 no("一二三四,五", simplified.without_hanging());
2414 no("一二三四…五", simplified);
2415 no("一二三四五,", simplified);
2416 no("一二三四,五", Kinsoku::FREE);
2417 }
2418
2419 #[test]
2420 fn breaks_after_spaces_and_hyphens() {
2421 let lines = break_lines(&glyphs("aa bb-cc dd"), &frame(60));
2422 assert_eq!(texts(&lines), vec!["aa bb-", "cc dd"]);
2423 let narrow = break_lines(&glyphs("aa bb-cc dd"), &frame(50));
2424 assert_eq!(texts(&narrow), vec!["aa ", "bb-cc ", "dd"]);
2425 assert_eq!(lines[0].width(), Length::from_units(60));
2426 assert_eq!(lines[1].last_visible(), Some(4));
2427 }
2428
2429 #[test]
2430 fn breaks_an_equation_after_the_space_of_an_operator_which_hangs() {
2431 let pieces: Vec<Piece> = glyphs("a+\u{a0}b+\u{a0}cd")
2432 .into_iter()
2433 .map(|piece| match piece {
2434 Piece::Glyph(mut g) if g.ch == '\u{a0}' => {
2435 g.space = SpaceKind::Operator;
2436 Piece::Glyph(g)
2437 }
2438 other => other,
2439 })
2440 .collect();
2441 let lines = break_lines(&pieces, &frame(50));
2442 assert_eq!(texts(&lines), vec!["a+\u{a0}b+\u{a0}", "cd"]);
2443 assert_eq!(lines[0].last_visible(), Some(4));
2444 assert!(!is_space(&pieces[2]));
2445 }
2446
2447 #[test]
2448 fn a_justified_line_counts_the_operator_space_before_a_term_in_its_room() {
2449 let pieces: Vec<Piece> = glyphs("a b c d+\u{a0}e+\u{a0}f")
2450 .into_iter()
2451 .map(|piece| match piece {
2452 Piece::Glyph(mut g) if g.ch == '\u{a0}' => {
2453 g.space = SpaceKind::Operator;
2454 Piece::Glyph(g)
2455 }
2456 other => other,
2457 })
2458 .collect();
2459 let mut f = frame(101);
2460 f.shrink = Shrink {
2461 permille: 500,
2462 stretch_permille: 500,
2463 natural: (0, 0),
2464 joints: JointGaps::default(),
2465 };
2466 assert_eq!(
2470 texts(&break_lines(&pieces, &f)),
2471 vec!["a b c d+\u{a0}e+\u{a0}", "f"]
2472 );
2473 f.width = Length::from_units(99);
2474 f.first_width = f.width;
2475 assert_eq!(
2476 texts(&break_lines(&pieces, &f)),
2477 vec!["a b c d+\u{a0}", "e+\u{a0}f"]
2478 );
2479 }
2480
2481 #[test]
2482 fn hangs_the_whole_space_after_a_relation() {
2483 let pieces: Vec<Piece> = glyphs("a=\u{200a}\u{a0}b=\u{200a}\u{a0}cd")
2484 .into_iter()
2485 .map(|piece| match piece {
2486 Piece::Glyph(mut g) if matches!(g.ch, '\u{200a}' | '\u{a0}') => {
2487 g.space = SpaceKind::Operator;
2488 Piece::Glyph(g)
2489 }
2490 other => other,
2491 })
2492 .collect();
2493 let lines = break_lines(&pieces, &frame(60));
2494 assert_eq!(
2495 texts(&lines),
2496 vec!["a=\u{200a}\u{a0}b=\u{200a}\u{a0}", "cd"]
2497 );
2498 assert_eq!(lines[0].last_visible(), Some(5));
2499 }
2500
2501 #[test]
2502 fn keeps_the_numbers_of_its_decisions() {
2503 let lines = break_lines(&glyphs("aa bb cc"), &frame(50));
2504 assert_eq!(texts(&lines), vec!["aa bb ", "cc"]);
2505 let u = Length::from_units;
2507 let kept = lines[0].kept.unwrap();
2508 assert_eq!(
2509 (kept.end, kept.word, kept.spaces, kept.space),
2510 (u(50), u(20), u(10), u(10))
2511 );
2512 let wrapped = lines[0].wrapped.unwrap();
2513 assert_eq!(
2514 (wrapped.width, wrapped.end, wrapped.spaces),
2515 (u(50), u(80), u(20))
2516 );
2517 assert_eq!((wrapped.over, wrapped.shrinks), (Length::ZERO, false));
2518 assert_eq!(lines[1].kept.unwrap().end, u(20));
2520 assert_eq!(lines[1].wrapped, None);
2521 }
2522
2523 #[test]
2524 fn shows_a_soft_hyphen_only_where_a_line_ends() {
2525 let text = "aa bb\u{E0AD}cc dd";
2528 let wide = break_lines(&glyphs(text), &frame(70));
2529 assert_eq!(texts(&wide), vec!["aa bbcc ", "dd"]);
2530 assert_eq!(wide[0].placed[5].x, Length::from_units(50));
2531 let narrow = break_lines(&glyphs(text), &frame(60));
2533 assert_eq!(texts(&narrow), vec!["aa bb-", "cc dd"]);
2534 assert_eq!(narrow[0].width(), Length::from_units(60));
2535 let tight = break_lines(&glyphs(text), &frame(50));
2538 assert_eq!(texts(&tight), vec!["aa ", "bbcc ", "dd"]);
2539 let end = break_lines(&glyphs("aa\u{E0AD}"), &frame(60));
2541 assert_eq!(texts(&end), vec!["aa"]);
2542 let literal = break_lines(&glyphs("aa bb\u{AD}cc dd"), &frame(70));
2544 assert_eq!(texts(&literal), vec!["aa ", "bb\u{AD}cc ", "dd"]);
2545 }
2546
2547 #[test]
2548 fn marks_the_line_that_ends_at_a_soft_hyphen() {
2549 let hyphens = |text: &str, width| {
2551 let lines = break_lines(&glyphs(text), &frame(width));
2552 lines.iter().map(|line| line.hyphen).collect::<Vec<_>>()
2553 };
2554 assert_eq!(hyphens("aa bb\u{E0AD}cc dd", 70), [None, None]);
2555 assert_eq!(
2556 hyphens("aa bb\u{E0AD}cc dd", 60),
2557 [Some(EndHyphen::Soft), None]
2558 );
2559 assert_eq!(hyphens("aa\u{E0AD}", 60), [None]);
2560 }
2561
2562 #[test]
2563 fn breaks_after_the_move_of_an_advance_field_but_not_before_it() {
2564 let moved = |before: &str, after: &str| {
2567 let mut pieces = glyphs(before);
2568 pieces.push(Piece::Advance(Length::from_units(30)));
2569 pieces.extend(glyphs(after));
2570 pieces
2571 };
2572 let lines = break_lines(&moved("aa", "bb cc"), &frame(60));
2573 assert_eq!(texts(&lines), vec!["aa|", "bb cc"]);
2574 let lines = break_lines(&moved("a aa", "bb"), &frame(50));
2576 assert_eq!(texts(&lines), vec!["a ", "aa|", "bb"]);
2577 }
2578
2579 fn with_points(text: &str) -> Vec<Piece> {
2581 glyphs(&text.replace('=', &AUTOMATIC_HYPHEN.to_string()))
2582 }
2583
2584 fn hyphenated_texts(lines: &[Line]) -> Vec<String> {
2586 texts(lines)
2587 .into_iter()
2588 .map(|text| text.replace(super::LINE_END_HYPHEN, "-"))
2589 .collect()
2590 }
2591
2592 #[test]
2593 fn ends_a_line_at_the_last_automatic_point_that_fits() {
2594 let hyphenated = |rules| Frame {
2597 hyphenation: Some(rules),
2598 ..frame(120)
2599 };
2600 let pieces = with_points("aaaa hy=phen=ation");
2601 let lines = break_lines(&pieces, &hyphenated(Hyphenation::default()));
2602 assert_eq!(hyphenated_texts(&lines), ["aaaa hyphen-", "ation"]);
2603 assert_eq!(lines[0].hyphen, Some(EndHyphen::Automatic));
2604 assert_eq!(
2606 hyphenated_texts(&break_lines(&pieces, &frame(120))),
2607 ["aaaa ", "hyphenation"]
2608 );
2609 let zone = |units| Hyphenation {
2611 zone: Some(Length::from_units(units)),
2612 limit: None,
2613 };
2614 assert_eq!(
2615 hyphenated_texts(&break_lines(&pieces, &hyphenated(zone(70)))),
2616 ["aaaa ", "hyphenation"]
2617 );
2618 assert_eq!(
2619 hyphenated_texts(&break_lines(&pieces, &hyphenated(zone(69)))),
2620 ["aaaa hyphen-", "ation"]
2621 );
2622 }
2623
2624 #[test]
2625 fn ends_no_more_lines_in_a_row_at_a_point_than_the_limit() {
2626 let pieces = with_points("aaaa=aaaa=aaaa=aaaa=aaaa=aaaa");
2627 let limited = |limit| Frame {
2628 hyphenation: Some(Hyphenation {
2629 zone: None,
2630 limit: std::num::NonZeroUsize::new(limit),
2631 }),
2632 ..frame(60)
2633 };
2634 assert_eq!(
2635 hyphenated_texts(&break_lines(&pieces, &limited(0))),
2636 ["aaaa-", "aaaa-", "aaaa-", "aaaa-", "aaaa-", "aaaa"]
2637 );
2638 assert_eq!(
2641 hyphenated_texts(&break_lines(&pieces, &limited(2))),
2642 ["aaaa-", "aaaa-", "aaaaaa", "aa-", "aaaa-", "aaaa"]
2643 );
2644 }
2645
2646 #[test]
2647 fn breaks_after_en_and_em_dashes() {
2648 let en = break_lines(&glyphs("aa bb\u{2013}cc dd"), &frame(60));
2649 assert_eq!(texts(&en), vec!["aa bb\u{2013}", "cc dd"]);
2650 let em = break_lines(&glyphs("aa bb\u{2014}cc dd"), &frame(60));
2651 assert_eq!(texts(&em), vec!["aa bb\u{2014}", "cc dd"]);
2652 }
2653
2654 #[test]
2655 fn breaks_after_a_unicode_hyphen() {
2656 let lines = break_lines(&glyphs("aa bb\u{2010}cc dd"), &frame(60));
2657 assert_eq!(texts(&lines), vec!["aa bb\u{2010}", "cc dd"]);
2658 }
2659
2660 #[test]
2661 fn thai_text_keeps_the_spaces_of_its_line() {
2662 let mut f = frame(72);
2663 f.shrink = Shrink {
2664 permille: 400,
2665 stretch_permille: 0,
2666 natural: (0, 0),
2667 joints: JointGaps::default(),
2668 };
2669 f.thai_keeps_spaces = true;
2670 assert_eq!(
2673 texts(&break_lines(&glyphs("aa bb cc"), &f)),
2674 vec!["aa bb cc"]
2675 );
2676 assert_eq!(
2677 texts(&break_lines(&glyphs("aa bb กข"), &f)),
2678 vec!["aa bb ", "กข"]
2679 );
2680 assert_eq!(
2681 texts(&break_lines(&glyphs("กข bb cc"), &f)),
2682 vec!["กข bb ", "cc"]
2683 );
2684 f.thai_keeps_spaces = false;
2685 assert_eq!(
2686 texts(&break_lines(&glyphs("กข bb cc"), &f)),
2687 vec!["กข bb cc"]
2688 );
2689 }
2690
2691 #[test]
2692 fn justified_lines_may_shrink_their_spaces() {
2693 let mut f = frame(50);
2694 f.shrink = Shrink {
2695 permille: 400,
2696 stretch_permille: 0,
2697 natural: (0, 0),
2698 joints: JointGaps::default(),
2699 };
2700 assert_eq!(
2703 texts(&break_lines(&glyphs("aa bb c"), &f)),
2704 vec!["aa bb ", "c"]
2705 );
2706 f.width = Length::from_units(72);
2707 f.first_width = f.width;
2708 assert_eq!(
2709 texts(&break_lines(&glyphs("aa bb cc"), &f)),
2710 vec!["aa bb cc"]
2711 );
2712 let u = Length::from_units;
2713 assert_eq!(f.shrink.of(u(10)), u(4));
2714 assert_eq!(
2715 Shrink {
2716 permille: 100,
2717 stretch_permille: 0,
2718 natural: (0, 0),
2719 joints: JointGaps::default(),
2720 }
2721 .of(u(10)),
2722 u(1)
2723 );
2724 }
2725
2726 #[test]
2727 fn a_share_of_the_natural_width_limits_the_overrun_to_the_nearest_twip() {
2728 let twips = |t| Length::from_twips(t).unwrap();
2729 let shrink = Shrink {
2730 natural: (3, 80),
2731 ..Shrink::default()
2732 };
2733 assert_eq!(shrink.of_natural(twips(8_000)), Some(twips(300)));
2736 assert_eq!(shrink.of_natural(twips(8_001)), Some(twips(300)));
2737 assert_eq!(shrink.of_natural(twips(8_010)), Some(twips(300)));
2738 assert_eq!(shrink.of_natural(twips(8_020)), Some(twips(301)));
2739 assert_eq!(Shrink::default().of_natural(twips(8_000)), None);
2740 }
2741
2742 #[test]
2743 fn keeps_the_spaces_after_a_word_that_shrinks_its_line() {
2744 let mut f = frame(72);
2745 f.shrink = Shrink {
2746 permille: 400,
2747 stretch_permille: 0,
2748 natural: (0, 0),
2749 joints: JointGaps::default(),
2750 };
2751 let dashed = break_lines(&glyphs("aa bb c\u{2013} dd"), &f);
2754 assert_eq!(texts(&dashed), vec!["aa bb c\u{2013} ", "dd"]);
2755 }
2756
2757 #[test]
2758 fn a_justified_line_takes_a_word_only_when_its_spaces_shrink_by_at_most_half_the_stretch() {
2759 let mut f = frame(82);
2760 f.shrink = Shrink {
2761 permille: 500,
2762 stretch_permille: 500,
2763 natural: (0, 0),
2764 joints: JointGaps::default(),
2765 };
2766 assert_eq!(
2771 texts(&break_lines(&glyphs("a b c d e"), &f)),
2772 vec!["a b c d e"]
2773 );
2774 f.width = Length::from_units(81);
2775 f.first_width = f.width;
2776 assert_eq!(
2777 texts(&break_lines(&glyphs("a b c d e"), &f)),
2778 vec!["a b c d ", "e"]
2779 );
2780 f.shrink.stretch_permille = 0;
2782 assert_eq!(
2783 texts(&break_lines(&glyphs("a b c d e"), &f)),
2784 vec!["a b c d e"]
2785 );
2786 f.shrink.stretch_permille = 500;
2787 let u = Length::from_units;
2788 assert_eq!(
2789 f.shrink
2790 .over(u(20), (u(10), u(10)), (4, 1), JointCounts::default()),
2791 u(8)
2792 );
2793 assert_eq!(
2795 f.shrink
2796 .over(u(5), (u(10), u(10)), (4, 1), JointCounts::default()),
2797 u(5)
2798 );
2799 assert_eq!(
2801 f.shrink
2802 .over(u(5), (u(10), u(10)), (1, 1), JointCounts::default()),
2803 u(5)
2804 );
2805 assert_eq!(
2806 Shrink::default().over(u(10), (u(10), u(20)), (2, 1), JointCounts::default()),
2807 u(10)
2808 );
2809 }
2810
2811 #[test]
2812 fn a_justified_line_takes_a_word_less_often_when_its_letter_joints_count_as_gaps() {
2813 let mut shrink = Shrink {
2814 permille: 500,
2815 stretch_permille: 500,
2816 natural: (0, 0),
2817 joints: JointGaps { seen: 9, other: 3 },
2818 };
2819 let u = Length::from_units;
2820 let other = JointCounts { seen: 0, other: 1 };
2826 assert_eq!(shrink.over(u(20), (u(10), u(10)), (4, 1), other), u(5));
2827 let seen = JointCounts { seen: 1, other: 0 };
2828 assert_eq!(shrink.over(u(20), (u(7), u(7)), (4, 1), seen), u(2));
2829 shrink.joints = JointGaps::default();
2831 assert_eq!(shrink.over(u(20), (u(10), u(10)), (4, 1), other), u(8));
2832 }
2833
2834 #[test]
2835 fn trailing_spaces_do_not_force_a_break() {
2836 let lines = break_lines(&glyphs("aaaa b"), &frame(40));
2837 assert_eq!(texts(&lines), vec!["aaaa ", "b"]);
2838 assert_eq!(lines[0].width(), Length::from_units(40));
2839 }
2840
2841 #[test]
2842 fn places_an_object_as_a_word_of_its_own() {
2843 let object = Piece::Object {
2844 width: Length::from_units(50),
2845 height: Length::from_units(200),
2846 raised: Length::ZERO,
2847 picture: None,
2848 drawing: None,
2849 underlined: false,
2850 run_face: None,
2851 joins_before: false,
2852 };
2853 let mut pieces = glyphs("ab ");
2854 pieces.push(object);
2855 pieces.extend(glyphs(" cd"));
2856 let lines = break_lines(&pieces, &frame(100));
2857 assert_eq!(texts(&lines), vec!["ab | ", "cd"]);
2858 assert_eq!(lines[0].placed[3].advance, Length::from_units(50));
2859 assert_eq!(lines[0].width(), Length::from_units(80));
2860 let narrow = break_lines(&pieces, &frame(70));
2861 assert_eq!(texts(&narrow), vec!["ab ", "| ", "cd"]);
2862 }
2863
2864 #[test]
2865 fn attaches_a_joining_object_to_its_preceding_word_only() {
2866 let obj = |width: i64, joins_before: bool| Piece::Object {
2867 width: Length::from_units(width),
2868 height: Length::from_units(100),
2869 raised: Length::ZERO,
2870 picture: None,
2871 drawing: None,
2872 underlined: false,
2873 run_face: None,
2874 joins_before,
2875 };
2876 let mut pieces = glyphs("ab cd");
2877 pieces.push(obj(60, true));
2878 assert_eq!(texts(&break_lines(&pieces, &frame(85))), vec!["ab ", "cd|"]);
2879 let mut non_joining = glyphs("ab cd");
2880 non_joining.push(obj(60, false));
2881 assert_eq!(
2882 texts(&break_lines(&non_joining, &frame(85))),
2883 vec!["ab cd", "|"]
2884 );
2885 let mut after_text = glyphs("ab ");
2886 after_text.push(obj(50, true));
2887 after_text.extend(glyphs("ef"));
2888 assert_eq!(
2889 texts(&break_lines(&after_text, &frame(85))),
2890 vec!["ab |", "ef"]
2891 );
2892 let mut two_objs = glyphs("ab ");
2893 two_objs.push(obj(50, true));
2894 two_objs.push(obj(50, true));
2895 assert_eq!(
2896 texts(&break_lines(&two_objs, &frame(85))),
2897 vec!["ab |", "|"]
2898 );
2899 let mut hyphen = glyphs("ab cd-");
2900 hyphen.push(obj(60, true));
2901 assert_eq!(
2902 texts(&break_lines(&hyphen, &frame(85))),
2903 vec!["ab cd-", "|"]
2904 );
2905 let mut overlong = glyphs("ab cd");
2906 overlong.push(obj(75, true));
2907 assert_eq!(
2908 texts(&break_lines(&overlong, &frame(85))),
2909 vec!["ab ", "cd", "|"]
2910 );
2911 }
2912
2913 #[test]
2914 fn measures_an_object_after_a_tab_as_text_with_its_width() {
2915 let object = Piece::Object {
2916 width: Length::from_units(50),
2917 height: Length::from_units(200),
2918 raised: Length::ZERO,
2919 picture: None,
2920 drawing: None,
2921 underlined: false,
2922 run_face: None,
2923 joins_before: false,
2924 };
2925 let mut after = vec![object];
2926 after.extend(glyphs("ab "));
2927 assert_eq!(following_width(&after, None), Length::from_units(70));
2928 let mut spaced = vec![object];
2929 spaced.extend(glyphs(" "));
2930 assert_eq!(following_width(&spaced, None), Length::from_units(50));
2931 }
2932
2933 #[test]
2934 fn splits_a_word_that_is_too_long() {
2935 let lines = break_lines(&glyphs("abcdefg"), &frame(30));
2936 assert_eq!(texts(&lines), vec!["abc", "def", "g"]);
2937 let ends: Vec<LineEnd> = lines.iter().map(|l| l.end).collect();
2939 assert_eq!(ends, vec![LineEnd::Split, LineEnd::Split, LineEnd::Wrap]);
2940 assert_eq!(
2941 break_lines(&glyphs("ab cd"), &frame(30))[0].end,
2942 LineEnd::Wrap
2943 );
2944 }
2945
2946 #[test]
2947 fn honors_breaks_and_tabs() {
2948 let mut pieces = glyphs("a");
2949 pieces.push(Piece::Tab(None));
2950 pieces.extend(glyphs("b"));
2951 pieces.push(Piece::LineBreak(Some(FaceIndex::nth(3))));
2952 pieces.extend(glyphs("c"));
2953 pieces.push(Piece::PageBreak);
2954 let lines = break_lines(&pieces, &frame(100));
2955 assert_eq!(texts(&lines), vec!["a|b", "c"]);
2956 assert_eq!(lines[0].placed[1].advance, Length::from_units(15));
2957 assert_eq!(lines[0].placed[2].x, Length::from_units(25));
2958 assert_eq!(lines[1].end, LineEnd::PageBreak);
2959 assert_eq!(lines[0].end, LineEnd::Break(Some(FaceIndex::nth(3))));
2960 pieces.extend(glyphs("d"));
2961 assert_eq!(
2962 texts(&break_lines(&pieces, &frame(100))),
2963 vec!["a|b", "c", "d"]
2964 );
2965 assert_eq!(break_lines(&[], &frame(100)).len(), 1);
2966 }
2967
2968 fn narrow_first(leading: LeadingBreaks) -> Frame {
2972 let mut f = frame(100);
2973 f.first_width = Length::from_units(50);
2974 f.breaking.leading_breaks = leading;
2975 f
2976 }
2977
2978 #[test]
2979 fn starts_the_first_line_after_leading_page_breaks_where_the_frame_says_so() {
2980 let (none, first, all) = (
2981 LeadingBreaks::None,
2982 LeadingBreaks::First,
2983 LeadingBreaks::All,
2984 );
2985 let cases = [
2989 ((1, none), (2, 0)),
2990 ((1, first), (3, 1)),
2991 ((1, all), (3, 1)),
2992 ((2, none), (3, 0)),
2993 ((2, first), (3, 1)),
2994 ((3, first), (4, 1)),
2995 ((2, all), (4, 2)),
2996 ((0, all), (2, 0)),
2997 ((0, first), (2, 0)),
2998 ];
2999 for ((breaks, leading), expected) in cases {
3000 let mut pieces = vec![Piece::PageBreak; breaks];
3001 pieces.extend(glyphs("aaaa bbbb"));
3002 let lines = break_lines(&pieces, &narrow_first(leading));
3003 let found = (lines.len(), Line::first_index(&lines, leading));
3004 assert_eq!(found, expected, "{breaks} breaks, {leading:?}");
3005 }
3006 }
3007
3008 #[test]
3009 fn keeps_the_first_line_at_the_start_after_text_or_without_text() {
3010 let mut pieces = glyphs("c");
3013 pieces.push(Piece::PageBreak);
3014 pieces.extend(glyphs("aaaa bbbb"));
3015 let lines = break_lines(&pieces, &narrow_first(LeadingBreaks::All));
3016 assert_eq!(lines.len(), 2);
3017 assert_eq!(Line::first_index(&lines, LeadingBreaks::All), 0);
3018 let only = [Piece::PageBreak, Piece::PageBreak];
3020 for leading in [LeadingBreaks::First, LeadingBreaks::All] {
3021 let lines = break_lines(&only, &narrow_first(leading));
3022 assert_eq!(Line::first_index(&lines, leading), 0);
3023 }
3024 }
3025
3026 #[test]
3027 fn keeps_an_empty_line_after_a_column_break_that_ends_the_pieces() {
3028 let mut pieces = glyphs("a");
3029 pieces.push(Piece::ColumnBreak);
3030 let lines = break_lines(&pieces, &frame(100));
3031 assert_eq!(texts(&lines), vec!["a", ""]);
3032 assert_eq!(lines[0].end, LineEnd::ColumnBreak);
3033 let mut pieces = glyphs("a");
3035 pieces.push(Piece::PageBreak);
3036 assert_eq!(break_lines(&pieces, &frame(100)).len(), 1);
3037 }
3038
3039 #[test]
3040 fn gives_back_the_pieces_of_lines_with_their_breaks() {
3041 let mut pieces = glyphs("aaa bbb");
3042 pieces.push(Piece::LineBreak(Some(FaceIndex::nth(1))));
3043 pieces.extend(glyphs("ccc"));
3044 pieces.push(Piece::PageBreak);
3045 pieces.extend(glyphs("ddd"));
3046 let lines = break_lines(&pieces, &frame(100));
3047 assert_eq!(lines[0].end, LineEnd::Break(Some(FaceIndex::nth(1))));
3048 assert_eq!(lines[1].end, LineEnd::PageBreak);
3049 let again = Line::pieces(&lines);
3050 assert_eq!(again, pieces);
3051 let narrow = break_lines(&again, &frame(40));
3053 assert_eq!(texts(&narrow), vec!["aaa ", "bbb", "ccc", "ddd"]);
3054 assert_eq!(narrow[1].end, LineEnd::Break(Some(FaceIndex::nth(1))));
3055 assert_eq!(narrow[2].end, LineEnd::PageBreak);
3056 }
3057
3058 #[test]
3059 fn stretches_only_spaces_after_the_last_tab_and_the_first_glyph() {
3060 let line = |pieces: &[Piece]| break_lines(pieces, &frame(1000)).remove(0);
3061 assert_eq!(line(&glyphs(" a b")).first_stretched(), 2);
3062 assert_eq!(line(&glyphs("a b")).first_stretched(), 0);
3063 let mut pieces = glyphs("a b");
3064 pieces.push(Piece::Tab(None));
3065 pieces.extend(glyphs(" c d"));
3066 assert_eq!(line(&pieces).first_stretched(), 5);
3068 }
3069
3070 #[test]
3071 fn moves_a_tab_down_with_the_word_after_it() {
3072 let mut pieces = glyphs("aaaa");
3073 pieces.push(Piece::Tab(None));
3074 pieces.extend(glyphs("bbbbbb"));
3075 let lines = break_lines(&pieces, &frame(100));
3076 assert_eq!(texts(&lines), vec!["aaaa", "|bbbbbb"]);
3077 assert_eq!(lines[1].placed[0].advance, Length::from_units(25));
3078 assert_eq!(lines[1].placed[1].x, Length::from_units(25));
3079 let mut alone = vec![Piece::Tab(None)];
3081 alone.extend(glyphs(&"c".repeat(12)));
3082 let lines = break_lines(&alone, &frame(100));
3083 assert_eq!(texts(&lines)[0], "|");
3084 }
3085
3086 #[test]
3087 fn starts_a_new_line_with_a_tab_whose_default_stop_lies_past_the_end() {
3088 let mut pieces = glyphs("aa");
3092 pieces.extend([Piece::Tab(None); 3]);
3093 pieces.extend(glyphs(" bb"));
3094 let lines = break_lines(&pieces, &frame(60));
3095 assert_eq!(texts(&lines), vec!["aa||", "| bb"]);
3096 assert_eq!(lines[1].placed[2].x, Length::from_units(35));
3097 let mut pieces = glyphs("a");
3099 pieces.extend([Piece::Tab(None); 2]);
3100 let lines = break_lines(&pieces, &frame(50));
3101 assert_eq!(texts(&lines), vec!["a||"]);
3102 let mut pieces = glyphs("aaaa ");
3104 pieces.push(Piece::Tab(None));
3105 let lines = break_lines(&pieces, &frame(60));
3106 assert_eq!(texts(&lines), vec!["aaaa ", "|"]);
3107 }
3108
3109 #[test]
3110 fn aligns_text_at_right_center_and_decimal_stops() {
3111 let stop = |position, kind| TabStop {
3112 position: Length::from_units(position),
3113 kind,
3114 leader: Some('.'),
3115 };
3116 let mut f = frame(500);
3117 let mut run = |kind, text: &str| {
3118 f.tabs = Tabs::new([stop(200, kind)], Length::from_units(25), None);
3119 let mut pieces = glyphs("a");
3120 pieces.push(Piece::Tab(None));
3121 pieces.extend(glyphs(text));
3122 let lines = break_lines(&pieces, &f);
3123 (
3124 lines[0].placed[1].advance.units(),
3125 lines[0].placed[1].leader,
3126 )
3127 };
3128 assert_eq!(run(TabKind::Right, "bcd "), (160, Some('.')));
3129 assert_eq!(run(TabKind::Center, "bcd"), (175, Some('.')));
3130 assert_eq!(run(TabKind::Decimal, "12.5"), (170, Some('.')));
3131 assert_eq!(run(TabKind::Decimal, "125"), (160, Some('.')));
3132 assert_eq!(run(TabKind::Right, &"x".repeat(30)), (0, Some('.')));
3133 }
3134
3135 #[test]
3136 fn ends_text_after_a_center_or_decimal_stop_at_the_line_end_where_the_quirk_says() {
3137 let (past, ends) = (
3138 AlignedTabOverrun::RunsPast,
3139 AlignedTabOverrun::EndsAtAreaEnd,
3140 );
3141 assert!(aligned_tab(TabKind::Center, 80, "bcdef", past, 0).0 > 1);
3143 assert_eq!(
3144 aligned_tab(TabKind::Center, 80, "bcdef", ends, 0),
3145 (1, Some(40))
3146 );
3147 assert!(aligned_tab(TabKind::Decimal, 80, "12.345", past, 0).0 > 1);
3149 assert_eq!(
3150 aligned_tab(TabKind::Decimal, 80, "12.345", ends, 0),
3151 (1, Some(30))
3152 );
3153 assert_eq!(
3155 aligned_tab(TabKind::Center, 80, "bc", ends, 0),
3156 (1, Some(60))
3157 );
3158 }
3159
3160 #[test]
3161 fn ends_text_after_a_stop_past_the_line_end_at_the_line_end_where_the_quirk_says() {
3162 let ends = AlignedTabOverrun::EndsAtAreaEnd;
3163 assert_eq!(
3164 aligned_tab(TabKind::Center, 120, "bc", ends, 0),
3165 (1, Some(70))
3166 );
3167 assert_eq!(
3168 aligned_tab(TabKind::Right, 120, "bc", ends, 0),
3169 (1, Some(70))
3170 );
3171 }
3172
3173 #[test]
3174 fn wraps_only_the_last_trailing_tab_with_a_word_that_does_not_fit() {
3175 let stop = |position, kind| TabStop {
3176 position: Length::from_units(position),
3177 kind,
3178 leader: None,
3179 };
3180 let mut f = frame(100);
3182 f.tabs = Tabs::new(
3183 [stop(40, TabKind::Center), stop(80, TabKind::Right)],
3184 Length::from_units(50),
3185 None,
3186 );
3187 let mut pieces = vec![Piece::Tab(None), Piece::Tab(None), Piece::Tab(None)];
3190 pieces.extend(glyphs("ab"));
3191 let lines = break_lines(&pieces, &f);
3192 assert_eq!(
3193 (lines.len(), lines[0].placed.len(), lines[1].placed[1].x),
3194 (2, 2, Length::from_units(30)),
3195 );
3196
3197 let mut f2 = frame(100);
3200 f2.tabs = Tabs::new([stop(80, TabKind::Left)], Length::from_units(20), None);
3201 let mut pieces2 = glyphs("a");
3202 pieces2.push(Piece::Tab(None));
3203 pieces2.push(Piece::Tab(None));
3204 pieces2.extend(glyphs("bc"));
3205 let lines2 = break_lines(&pieces2, &f2);
3206 assert_eq!(
3207 (lines2.len(), lines2[0].placed.len(), lines2[1].placed[1].x),
3208 (2, 2, Length::from_units(80)),
3209 );
3210
3211 let mut f3 = frame(100);
3213 f3.tabs = Tabs::new([stop(100, TabKind::Left)], Length::from_units(50), None);
3214 let mut pieces3 = vec![Piece::Tab(None)];
3215 pieces3.extend(glyphs("ab"));
3216 let lines3 = break_lines(&pieces3, &f3);
3217 assert_eq!(
3218 (lines3.len(), lines3[0].placed.len(), lines3[1].placed[0].x),
3219 (2, 1, Length::ZERO),
3220 );
3221 }
3222
3223 #[test]
3224 fn takes_the_text_area_end_as_the_limit_of_a_stop_beside_a_right_indent() {
3225 let ends = AlignedTabOverrun::EndsAtAreaEnd;
3226 assert_eq!(
3230 aligned_tab(TabKind::Center, 70, "bcd", ends, 20),
3231 (1, Some(40))
3232 );
3233 assert_eq!(
3234 aligned_tab(TabKind::Center, 90, "bcd", ends, 20),
3235 (1, Some(60))
3236 );
3237 assert_eq!(
3238 aligned_tab(TabKind::Center, 90, "bcdefgh", ends, 20),
3239 (1, Some(20))
3240 );
3241 assert_eq!(
3242 aligned_tab(TabKind::Center, 120, "bc", ends, 20),
3243 (1, Some(50))
3244 );
3245 assert!(aligned_tab(TabKind::Center, 90, "bcdefghijk", ends, 20).0 > 1);
3247 }
3248
3249 #[test]
3250 fn keeps_text_after_a_stop_past_the_line_end_at_the_stop_where_the_mode_says() {
3251 let older = (AlignedTabOverrun::EndsAtAreaEnd, false);
3252 assert_eq!(
3254 aligned_tab_in(TabKind::Center, 120, "bcde", older, 0),
3255 (1, Some(90))
3256 );
3257 assert_eq!(
3259 aligned_tab_in(TabKind::Center, 100, "bcdefg", older, 0),
3260 (1, Some(60))
3261 );
3262 assert_eq!(
3263 aligned_tab_in(TabKind::Right, 130, "bc", older, 0),
3264 (1, Some(100))
3265 );
3266 assert_eq!(
3268 aligned_tab_in(TabKind::Center, 80, "bcdef", older, 0),
3269 (1, Some(40))
3270 );
3271 }
3272
3273 fn aligned_tab(
3276 kind: TabKind,
3277 position: i64,
3278 text: &str,
3279 overrun: AlignedTabOverrun,
3280 indent: i64,
3281 ) -> (usize, Option<i64>) {
3282 aligned_tab_in(kind, position, text, (overrun, true), indent)
3283 }
3284
3285 fn aligned_tab_in(
3287 kind: TabKind,
3288 position: i64,
3289 text: &str,
3290 (overrun, limits_past_end): (AlignedTabOverrun, bool),
3291 indent: i64,
3292 ) -> (usize, Option<i64>) {
3293 let mut f = frame(100 - indent);
3294 f.area_width = Length::from_units(100);
3295 f.breaking.ends_aligned_text = overrun == AlignedTabOverrun::EndsAtAreaEnd;
3296 f.limits_past_end = limits_past_end;
3297 let stop = TabStop {
3298 position: Length::from_units(position),
3299 kind,
3300 leader: None,
3301 };
3302 f.tabs = Tabs::new([stop], Length::from_units(25), None);
3303 let mut pieces = glyphs("a");
3304 pieces.push(Piece::Tab(None));
3305 pieces.extend(glyphs(text));
3306 let lines = break_lines(&pieces, &f);
3307 let tab = lines
3308 .first()
3309 .and_then(|line| line.placed.get(1))
3310 .map(|placed| placed.advance.units());
3311 (lines.len(), tab)
3312 }
3313
3314 #[test]
3315 fn runs_on_to_a_right_stop_past_the_line_end() {
3316 let stop = |kind| TabStop {
3317 position: Length::from_units(120),
3318 kind,
3319 leader: None,
3320 };
3321 let line = |kind, after: &str| {
3322 let mut f = frame(100);
3324 f.first_start = Length::from_units(10);
3325 f.tabs = Tabs::new([stop(kind)], Length::from_units(25), None);
3326 let mut pieces = glyphs("aaaa");
3327 pieces.push(Piece::Tab(None));
3328 pieces.extend(glyphs(after));
3329 texts(&break_lines(&pieces, &f))
3330 };
3331 assert_eq!(line(TabKind::Right, "bb"), ["aaaa|bb"]);
3332 assert_eq!(
3334 line(TabKind::Right, "bb cccccccc"),
3335 ["aaaa|bb ", "cccccccc"]
3336 );
3337 assert_ne!(line(TabKind::Left, "bb"), ["aaaa|bb"]);
3339 }
3340
3341 #[test]
3342 fn empty_paragraph_has_one_line() {
3343 let lines = break_lines(&[], &frame(100));
3344 assert_eq!(lines.len(), 1);
3345 assert_eq!(lines[0].width(), Length::ZERO);
3346 assert!(!is_space(&Piece::LineBreak(None)));
3347 }
3348
3349 #[test]
3350 fn an_object_wider_than_the_line_ends_its_paragraph_on_that_line() {
3351 let wide = Piece::Object {
3352 width: Length::from_units(150),
3353 height: Length::from_units(50),
3354 raised: Length::ZERO,
3355 picture: None,
3356 drawing: None,
3357 underlined: false,
3358 run_face: None,
3359 joins_before: false,
3360 };
3361 assert_eq!(texts(&break_lines(&[wide], &frame(100))), ["|"]);
3362 let mut pieces = vec![wide];
3364 pieces.extend(glyphs("aa"));
3365 assert_eq!(texts(&break_lines(&pieces, &frame(100))), ["|", "aa"]);
3366 assert_eq!(
3367 texts(&break_lines(&glyphs("abcdefghijkl"), &frame(100))),
3368 ["abcdefghij", "kl"]
3369 );
3370 }
3371
3372 #[test]
3373 fn punctuation_shrinks_up_to_r_times_the_stretch_per_gap_of_the_shorter_line() {
3374 let compression = super::Compression {
3375 ratio: 32,
3376 middle_dot: false,
3377 trailing_trim: super::TrailingTrim::None,
3378 };
3379 let u = Length::from_units;
3380 let halves = |count| super::Halves {
3381 count,
3382 em: u(1_000),
3383 };
3384 assert_eq!(compression.over(halves(10), (u(60), 19)), u(1_010));
3388 assert_eq!(compression.over(halves(10), (u(55), 19)), u(926));
3389 assert_eq!(compression.over(halves(11), (u(100), 19)), u(1_852));
3392 assert_eq!(compression.over(halves(1), (u(900), 2)), u(500));
3394 assert_eq!(compression.over(halves(10), (u(60), 0)), Length::ZERO);
3395 }
3396
3397 #[test]
3398 fn a_justified_line_takes_one_more_character_when_its_halves_may_shrink() {
3399 let pieces = glyphs("永、永、永、永永永");
3400 let frame = |width, compressing: bool| Frame {
3401 kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
3402 punctuation: compressing.then_some(super::Compression {
3403 ratio: 32,
3404 middle_dot: false,
3405 trailing_trim: super::TrailingTrim::None,
3406 }),
3407 ..frame(width)
3408 };
3409 assert_eq!(
3413 texts(&break_lines(&pieces, &frame(71, true))),
3414 ["永、永、永、永永", "永"]
3415 );
3416 assert_eq!(
3417 texts(&break_lines(&pieces, &frame(70, true))),
3418 ["永、永、永、永", "永永"]
3419 );
3420 assert_eq!(
3421 texts(&break_lines(&pieces, &frame(71, false))),
3422 ["永、永、永、永", "永永"]
3423 );
3424 }
3425
3426 #[test]
3427 fn japanese_middle_dot_carries_a_blank_half_only_when_middle_dot_is_enabled() {
3428 let pieces = glyphs("所属・役職");
3429 let make = |middle_dot| Frame {
3430 kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
3431 punctuation: Some(super::Compression {
3432 ratio: 32,
3433 middle_dot,
3434 trailing_trim: super::TrailingTrim::None,
3435 }),
3436 ..frame(46)
3437 };
3438 assert_eq!(texts(&break_lines(&pieces, &make(true))), ["所属・役職"]);
3439 assert_eq!(
3440 texts(&break_lines(&pieces, &make(false))),
3441 ["所属・役", "職"]
3442 );
3443 }
3444
3445 #[test]
3446 fn punctuation_compression_ignores_marks_before_tab() {
3447 let u = Length::from_units;
3448 let mut before_tab = glyphs("一、");
3449 before_tab.push(Piece::Tab(None));
3450 before_tab.extend(glyphs("甲乙丙"));
3451 let compressed = Frame {
3452 kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
3453 punctuation: Some(super::Compression {
3454 ratio: 32,
3455 middle_dot: false,
3456 trailing_trim: super::TrailingTrim::None,
3457 }),
3458 tabs: crate::tabs::Tabs::new([], u(40), None),
3459 ..frame(66)
3460 };
3461 assert_eq!(
3462 texts(&break_lines(&before_tab, &compressed)),
3463 ["一、|甲乙", "丙"]
3464 );
3465
3466 let mut labeled = glyphs("一、甲乙丙");
3469 for i in 0..2 {
3470 if let Some(Piece::Glyph(g)) = labeled.get_mut(i) {
3471 g.label = true;
3472 }
3473 }
3474 assert_eq!(
3475 texts(&break_lines(
3476 &labeled,
3477 &Frame {
3478 tabs: crate::tabs::Tabs::new([], u(40), None),
3479 ..Frame {
3480 width: u(46),
3481 first_width: u(46),
3482 ..compressed
3483 }
3484 }
3485 )),
3486 ["一、甲乙", "丙"]
3487 );
3488 }
3489
3490 #[test]
3491 fn trailing_auto_space_is_dropped_at_line_end_but_kept_inside_line() {
3492 let u = Length::from_units;
3493 let mut pieces = glyphs("甲8壬");
3495 if let Some(Piece::Glyph(g)) = pieces.get_mut(1) {
3496 g.advance = u(13);
3497 g.auto_space = u(3);
3498 g.trailing_auto_space = u(3);
3499 }
3500 let wrapped = break_lines(&pieces, &frame(20));
3503 assert_eq!(texts(&wrapped), ["甲8", "壬"]);
3504 assert_eq!(wrapped[0].width(), u(20));
3505 if let Some(Piece::Glyph(g)) = wrapped[0].placed.get(1).map(|p| p.piece) {
3506 assert_eq!(
3507 (g.advance, g.auto_space, g.trailing_auto_space),
3508 (u(10), u(0), u(0))
3509 );
3510 }
3511 let single = break_lines(&pieces, &frame(33));
3513 assert_eq!(texts(&single), ["甲8壬"]);
3514 assert_eq!(single[0].width(), u(33));
3515 }
3516
3517 #[test]
3518 fn punctuation_compression_ignores_closed_kerned_halves() {
3519 let u = Length::from_units;
3520 let pair_frame = |width| Frame {
3521 kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
3522 punctuation: Some(super::Compression {
3523 ratio: 32,
3524 middle_dot: false,
3525 trailing_trim: super::TrailingTrim::None,
3526 }),
3527 ..frame(width)
3528 };
3529 let mut pair = glyphs("甲」,乙");
3530 if let Some(Piece::Glyph(close)) = pair.get_mut(1) {
3531 close.advance = u(5);
3532 close.punctuation_half = crate::text::PunctuationHalf::Closed;
3533 }
3534 assert_eq!(texts(&break_lines(&pair, &pair_frame(30))), ["甲」,乙"]);
3535 assert_eq!(
3536 texts(&break_lines(&pair, &pair_frame(28))),
3537 ["甲」,", "乙"]
3538 );
3539
3540 let mut opens = glyphs("甲「「乙");
3541 if let Some(Piece::Glyph(first)) = opens.get_mut(1) {
3542 first.advance = u(5);
3543 first.punctuation_half = crate::text::PunctuationHalf::OpenShortened(u(5));
3544 }
3545 if let Some(Piece::Glyph(second)) = opens.get_mut(2) {
3546 second.punctuation_half = crate::text::PunctuationHalf::Closed;
3547 }
3548 assert_eq!(texts(&break_lines(&opens, &pair_frame(30))), ["甲「「乙"]);
3549 assert_eq!(
3550 texts(&break_lines(&opens, &pair_frame(28))),
3551 ["甲「「", "乙"]
3552 );
3553 }
3554
3555 #[test]
3556 fn trailing_closing_trim_fits_half_em_overrun_by_script() {
3557 let make = |width, trailing_trim| Frame {
3558 kinsoku: Some(crate::kinsoku::Kinsoku::of(
3559 crate::props::EastAsianScript::Simplified,
3560 )),
3561 punctuation: Some(super::Compression {
3562 ratio: 0,
3563 middle_dot: false,
3564 trailing_trim,
3565 }),
3566 ..frame(width)
3567 };
3568 let comma = glyphs("漢漢漢漢漢漢漢漢漢漢、後");
3570 assert_eq!(
3571 texts(&break_lines(
3572 &comma,
3573 &make(105, super::TrailingTrim::Closing)
3574 )),
3575 ["漢漢漢漢漢漢漢漢漢漢、", "後"]
3576 );
3577 assert_eq!(
3578 texts(&break_lines(
3579 &comma,
3580 &make(104, super::TrailingTrim::Closing)
3581 )),
3582 ["漢漢漢漢漢漢漢漢漢", "漢、後"]
3583 );
3584 assert_eq!(
3585 texts(&break_lines(&comma, &make(105, super::TrailingTrim::None))),
3586 ["漢漢漢漢漢漢漢漢漢", "漢、後"]
3587 );
3588 let semi = glyphs("漢漢漢漢漢漢漢漢漢漢;後");
3590 assert_eq!(
3591 texts(&break_lines(
3592 &semi,
3593 &make(105, super::TrailingTrim::Closing)
3594 )),
3595 ["漢漢漢漢漢漢漢漢漢漢;", "後"]
3596 );
3597 assert_eq!(
3598 texts(&break_lines(
3599 &semi,
3600 &make(105, super::TrailingTrim::NonJapaneseCentered)
3601 )),
3602 ["漢漢漢漢漢漢漢漢漢", "漢;後"]
3603 );
3604 }
3605
3606 #[test]
3607 fn overflow_punct_hangs_single_trailing_mark_and_ends_line() {
3608 use crate::kinsoku::Kinsoku;
3609 use crate::props::EastAsianScript;
3610 let cn = Kinsoku::of(EastAsianScript::Simplified);
3611 let ja = Kinsoku::of(EastAsianScript::Japanese);
3612 let free = Kinsoku::FREE.with_hanging_of(cn);
3613 for (text, kinsoku, want_texts, want_hung) in [
3614 (
3615 "漢漢漢漢漢漢漢漢漢漢、後",
3616 cn,
3617 &["漢漢漢漢漢漢漢漢漢漢、", "後"][..],
3618 true,
3619 ),
3620 (
3621 "漢漢漢漢漢漢漢漢漢漢、。後",
3622 cn,
3623 &["漢漢漢漢漢漢漢漢漢", "漢、。後"][..],
3624 false,
3625 ),
3626 (
3627 "漢漢漢漢漢漢漢漢漢漢、後",
3628 free,
3629 &["漢漢漢漢漢漢漢漢漢漢、", "後"][..],
3630 true,
3631 ),
3632 (
3633 "漢漢漢漢漢漢漢漢漢漢;後",
3634 ja,
3635 &["漢漢漢漢漢漢漢漢漢", "漢;後"][..],
3636 false,
3637 ),
3638 (
3639 "漢漢漢漢漢漢漢漢漢漢、",
3640 cn,
3641 &["漢漢漢漢漢漢漢漢漢漢、"][..],
3642 true,
3643 ),
3644 ] {
3645 let f = Frame {
3646 kinsoku: Some(kinsoku),
3647 overflow_punct: super::OverflowPunct::Hang,
3648 ..frame(102)
3649 };
3650 let lines = break_lines(&glyphs(text), &f);
3651 assert_eq!(texts(&lines), want_texts, "{text}");
3652 assert_eq!(lines.first().is_some_and(|l| l.hung), want_hung, "{text}");
3653 assert!(lines.iter().all(|l| !l.would_hang), "{text}");
3654 }
3655 }
3656
3657 #[test]
3658 fn closes_up_pairs_after_a_blank_right_half_or_before_an_opening_mark() {
3659 use crate::props::EastAsianScript::{Japanese, Simplified, Traditional};
3660 let check = |script, yes: &[&str], no: &[&str]| {
3661 let kerned = |pair: &str| {
3662 let mut chars = pair.chars();
3663 super::kerned_pair(chars.next().unwrap(), chars.next().unwrap(), script).is_some()
3664 };
3665 assert!(yes.iter().all(|pair| kerned(pair)));
3666 assert!(no.iter().all(|pair| !kerned(pair)));
3667 };
3668 check(
3669 Some(Japanese),
3670 &[
3671 "。」", ",(", "」「", ")。", "。。", "、、", ":「", "・(", "((", ")・",
3672 ],
3673 &[
3674 "!,", "!(", ")!", "!?", "?(", ")?", "::", "・・",
3675 ],
3676 );
3677 check(
3678 Some(Simplified),
3679 &[
3680 "!,", "!(", "!!", ")!", ":,", "::", ";;", ",,",
3681 ],
3682 &[
3683 "!?", "?(", ")?", "・(", ")・", "测(", ")测", "」a",
3684 ],
3685 );
3686 check(
3687 Some(Traditional),
3688 &["),", "。「", ":(", "):", "、("],
3689 &[",,", ",。", "。、", "!,", "!(", "・(", "?("],
3690 );
3691 check(None, &[")【", "】)"], &["),", "。「"]);
3692 }
3693
3694 #[test]
3695 fn a_tab_to_a_left_stop_past_the_line_end_starts_the_next_line_and_ends_at_its_end() {
3696 let stop = TabStop {
3698 position: Length::from_units(120),
3699 kind: TabKind::Left,
3700 leader: None,
3701 };
3702 let lay_out = |rule| {
3703 let mut f = frame(100);
3704 f.tabs = Tabs::new([stop], Length::from_units(25), None);
3705 f.breaking.left_stops_to_line_end = rule == LeftStopPastEnd::ToLineEnd;
3706 let mut pieces = glyphs("a");
3707 pieces.push(Piece::Tab(None));
3708 pieces.extend(glyphs("b"));
3709 let lines = break_lines(&pieces, &f);
3710 let tab = lines
3711 .iter()
3712 .flat_map(|line| &line.placed)
3713 .find(|placed| matches!(placed.piece, Piece::Tab(_)))
3714 .map(|placed| (placed.x.units(), placed.advance.units()));
3715 (texts(&lines), tab)
3716 };
3717 let (texts_to_stop, tab_to_stop) = lay_out(LeftStopPastEnd::ToStop);
3720 assert_eq!(texts_to_stop, ["a", "|b"]);
3721 assert_eq!(tab_to_stop, Some((0, 120)));
3722 let (texts_to_end, tab_to_end) = lay_out(LeftStopPastEnd::ToLineEnd);
3724 assert_eq!(texts_to_end, ["a", "|", "b"]);
3725 assert_eq!(tab_to_end, Some((0, 100)));
3726 }
3727
3728 #[test]
3729 fn a_tab_to_a_left_stop_inside_the_line_keeps_its_place_on_both_variants() {
3730 let stop = TabStop {
3731 position: Length::from_units(80),
3732 kind: TabKind::Left,
3733 leader: None,
3734 };
3735 for rule in [LeftStopPastEnd::ToStop, LeftStopPastEnd::ToLineEnd] {
3736 let mut f = frame(100);
3737 f.tabs = Tabs::new([stop], Length::from_units(25), None);
3738 f.breaking.left_stops_to_line_end = rule == LeftStopPastEnd::ToLineEnd;
3739 let mut pieces = glyphs("a");
3740 pieces.push(Piece::Tab(None));
3741 pieces.extend(glyphs("b"));
3742 assert_eq!(texts(&break_lines(&pieces, &f)), ["a|b"], "{rule:?}");
3743 }
3744 }
3745
3746 #[test]
3747 fn a_tab_to_a_hanging_indent_past_the_line_end_runs_on_on_both_variants() {
3748 let lay_out = |rule| {
3750 let mut f = frame(100);
3751 f.tabs = Tabs::new([], Length::from_units(25), Some(Length::from_units(120)));
3752 f.breaking.left_stops_to_line_end = rule == LeftStopPastEnd::ToLineEnd;
3753 let mut pieces = glyphs("a");
3754 pieces.push(Piece::Tab(None));
3755 pieces.extend(glyphs("b"));
3756 texts(&break_lines(&pieces, &f))
3757 };
3758 assert_eq!(
3759 lay_out(LeftStopPastEnd::ToLineEnd),
3760 lay_out(LeftStopPastEnd::ToStop)
3761 );
3762 }
3763
3764 #[test]
3765 fn overflow_punct_uses_mark_run_east_asian_language() {
3766 use crate::kinsoku::Kinsoku;
3767 use crate::props::{EastAsianLanguage, EastAsianScript};
3768 let tag = |text: &str, lang: Option<EastAsianLanguage>| -> Vec<Piece> {
3769 glyphs(text)
3770 .into_iter()
3771 .map(|p| match p {
3772 Piece::Glyph(mut g) => {
3773 g.east_asian_language = lang;
3774 Piece::Glyph(g)
3775 }
3776 other => other,
3777 })
3778 .collect()
3779 };
3780 let cn = Some(EastAsianLanguage::Script(EastAsianScript::Simplified));
3781 let ko = Some(EastAsianLanguage::Script(EastAsianScript::Korean));
3782 let non_ea = Some(EastAsianLanguage::NonEastAsian);
3783 let f_cn = Frame {
3784 kinsoku: Some(Kinsoku::of(EastAsianScript::Simplified)),
3785 overflow_punct: super::OverflowPunct::Hang,
3786 ..frame(100)
3787 };
3788 let non_ea_lines = break_lines(&tag("甲乙丙丁戊己庚辛壬癸、异", non_ea), &f_cn);
3790 assert_eq!(texts(&non_ea_lines), ["甲乙丙丁戊己庚辛壬癸", "、异"]);
3791 assert!(!non_ea_lines[0].hung);
3792 let f_free = Frame {
3794 kinsoku: Some(Kinsoku::FREE.with_restricted(true)),
3795 overflow_punct: super::OverflowPunct::Hang,
3796 ..frame(100)
3797 };
3798 let ea_lines = break_lines(&tag("甲乙丙丁戊己庚辛壬癸、异", cn), &f_free);
3799 assert_eq!(texts(&ea_lines), ["甲乙丙丁戊己庚辛壬癸、", "异"]);
3800 assert!(ea_lines[0].hung);
3801 let f_ko = Frame {
3803 kinsoku: None,
3804 overflow_punct: super::OverflowPunct::Hang,
3805 ..frame(100)
3806 };
3807 let ko_lines = break_lines(&tag("가나다라마바사아자차, 카타", ko), &f_ko);
3808 assert_eq!(texts(&ko_lines), ["가나다라마바사아자차, ", "카타"]);
3809 assert!(ko_lines[0].hung);
3810 }
3811
3812 #[test]
3813 fn overflow_punct_allows_space_shrink_before_hang() {
3814 use crate::kinsoku::Kinsoku;
3815 use crate::props::EastAsianScript;
3816 let f = Frame {
3817 kinsoku: Some(Kinsoku::of(EastAsianScript::Simplified)),
3818 overflow_punct: super::OverflowPunct::Hang,
3819 shrink: Shrink {
3820 permille: 250,
3821 ..Shrink::default()
3822 },
3823 ..frame(98)
3824 };
3825 let lines = break_lines(&glyphs("aaa bbb cc, next"), &f);
3828 assert_eq!(texts(&lines), ["aaa bbb cc, ", "next"]);
3829 assert!(lines[0].hung);
3830 }
3831}