1use crate::properties::{display_width, is_open_punctuation};
2use crate::unicode::{graphemes, line_breaks, LineBreakKind};
3use core::ops::Range;
4
5#[derive(Clone, Debug, Eq, PartialEq)]
6pub struct Line<'a> {
7 text: &'a str,
8 range: Range<usize>,
9 width: usize,
10 height: usize,
11 spacing: usize,
12}
13
14impl<'a> Line<'a> {
15 pub const fn text(&self) -> &'a str {
16 self.text
17 }
18
19 pub fn range(&self) -> Range<usize> {
20 self.range.clone()
21 }
22
23 pub const fn width(&self) -> usize {
24 self.width
25 }
26
27 pub const fn height(&self) -> usize {
28 self.height
29 }
30
31 pub const fn spacing(&self) -> usize {
32 self.spacing
33 }
34
35 pub(crate) fn set_metrics(&mut self, height: usize, spacing: usize) {
36 self.height = height;
37 self.spacing = spacing;
38 }
39}
40
41pub(crate) struct Lines<'a> {
42 text: &'a str,
43 cursor: usize,
44 max_width: usize,
45 tab_width: usize,
46}
47
48impl<'a> Lines<'a> {
49 pub(crate) const fn new(text: &'a str, max_width: usize, tab_width: usize) -> Self {
50 Self {
51 text,
52 cursor: 0,
53 max_width,
54 tab_width,
55 }
56 }
57
58 fn next_start(&self) -> usize {
59 if self.cursor == 0 {
60 return 0;
61 }
62 let mut start = self.cursor;
63 while let Some(character) = self.text[start..].chars().next() {
64 if !matches!(character, ' ' | '\t') {
65 break;
66 }
67 start += character.len_utf8();
68 }
69 start
70 }
71
72 fn emit(&mut self, start: usize, candidate: Candidate) -> Line<'a> {
73 self.cursor = start + candidate.offset;
74 let end = start + candidate.visible_offset;
75 Line {
76 text: &self.text[start..end],
77 range: start..end,
78 width: candidate.visible_width,
79 height: 0,
80 spacing: 0,
81 }
82 }
83}
84
85impl<'a> Iterator for Lines<'a> {
86 type Item = Line<'a>;
87
88 fn next(&mut self) -> Option<Self::Item> {
89 let start = self.next_start();
90 if start == self.text.len() {
91 self.cursor = start;
92 return None;
93 }
94
95 let remaining = &self.text[start..];
96 let mut breaks = line_breaks(remaining).peekable();
97 let mut width = 0usize;
98 let mut last_fit = None;
99 let mut last_allowed = None;
100 let mut last_open = None;
101 let mut only_open = true;
102 let mut previous_open = false;
103 let mut visible_offset = 0;
104 let mut visible_width = 0;
105
106 for cluster in graphemes(remaining) {
107 let open = cluster.text.chars().next().is_some_and(is_open_punctuation);
108 if open && !previous_open && !only_open {
109 last_open = Some(Candidate {
110 offset: cluster.range.start,
111 visible_offset,
112 visible_width,
113 });
114 }
115 if !open {
116 only_open = false;
117 }
118 previous_open = open;
119
120 let next_width = width.saturating_add(display_width(cluster.text, self.tab_width));
121 if next_width > self.max_width {
122 let whitespace = cluster.text.chars().all(char::is_whitespace);
123 let candidate = if whitespace {
124 last_fit.or(last_allowed)
125 } else {
126 latest(last_allowed, last_open).or(last_fit)
127 };
128 if let Some(candidate) = candidate {
129 return Some(self.emit(start, candidate));
130 }
131 }
132
133 width = next_width;
134 if !cluster.text.chars().all(char::is_whitespace) {
135 visible_offset = cluster.range.end;
136 visible_width = width;
137 }
138 let candidate = Candidate {
139 offset: cluster.range.end,
140 visible_offset,
141 visible_width,
142 };
143 if width <= self.max_width || last_fit.is_none() {
144 last_fit = Some(candidate);
145 }
146
147 while breaks
148 .peek()
149 .is_some_and(|line_break| line_break.offset <= cluster.range.end)
150 {
151 let line_break = breaks.next().unwrap();
152 if line_break.offset != cluster.range.end {
153 continue;
154 }
155 match line_break.kind {
156 LineBreakKind::Mandatory => return Some(self.emit(start, candidate)),
157 LineBreakKind::Allowed if width <= self.max_width => {
158 last_allowed = Some(candidate);
159 }
160 LineBreakKind::Allowed => {}
161 }
162 }
163
164 if width > self.max_width {
165 return Some(self.emit(start, candidate));
166 }
167 }
168
169 last_fit.map(|candidate| self.emit(start, candidate))
170 }
171}
172
173#[derive(Clone, Copy)]
174struct Candidate {
175 offset: usize,
176 visible_offset: usize,
177 visible_width: usize,
178}
179
180fn latest(left: Option<Candidate>, right: Option<Candidate>) -> Option<Candidate> {
181 match (left, right) {
182 (Some(left), Some(right)) => Some(if left.offset >= right.offset {
183 left
184 } else {
185 right
186 }),
187 (left, right) => left.or(right),
188 }
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194 use std::prelude::v1::*;
195
196 fn slices(text: &str, width: usize) -> Vec<&str> {
197 Lines::new(text, width, 4).map(|line| line.text()).collect()
198 }
199
200 #[test]
201 fn preserves_text_across_emergency_breaks() {
202 let text = "an \"apple\" tree";
203
204 for width in 0..=text.len() {
205 let mut rendered = String::new();
206 let mut count = 0;
207 for line in Lines::new(text, width, 4) {
208 rendered.push_str(line.text());
209 count += 1;
210 }
211 assert!(count <= text.chars().count());
212 assert_eq!(
213 rendered
214 .chars()
215 .filter(|character| !character.is_whitespace())
216 .collect::<String>(),
217 text.chars()
218 .filter(|character| !character.is_whitespace())
219 .collect::<String>()
220 );
221 }
222 }
223
224 #[test]
225 fn respects_graphemes_and_mandatory_breaks() {
226 assert_eq!(slices("a\u{301}b", 1), ["a\u{301}", "b"]);
227 assert_eq!(slices("a\r\n\r\nb", 8), ["a", "", "b"]);
228 }
229
230 #[test]
231 fn reports_visible_range_and_width() {
232 let line = Lines::new("ab cd", 3, 4).next().unwrap();
233
234 assert_eq!(line.text(), "ab");
235 assert_eq!(line.range(), 0..2);
236 assert_eq!(line.width(), 2);
237 }
238}