Debian Codegraph @

helix-core/src/doc_formatter.rs

raw symbols SCIP
1 //! The `DocumentFormatter` forms the bridge between the raw document text
2 //! and onscreen positioning. It yields the text graphemes as an iterator
3 //! and traverses (part) of the document text. During that traversal it
4 //! handles grapheme detection, softwrapping and annotations.
5 //! It yields `FormattedGrapheme`s and their corresponding visual coordinates.
6 //!
7 //! As both virtual text and softwrapping can insert additional lines into the document
8 //! it is generally not possible to find the start of the previous visual line.
9 //! Instead the `DocumentFormatter` starts at the last "checkpoint" (usually a linebreak)
10 //! called a "block" and the caller must advance it as needed.
11
12 use std::borrow::Cow;
13 use std::cmp::Ordering;
14 use std::fmt::Debug;
15 use std::mem::replace;
16
17 #[cfg(test)]
18 mod test;
19
20 use unicode_segmentation::{Graphemes, UnicodeSegmentation};
21
22 use helix_stdx::rope::{RopeGraphemes, RopeSliceExt};
23
24 use crate::graphemes::{Grapheme, GraphemeStr};
25 use crate::syntax::Highlight;
26 use crate::text_annotations::TextAnnotations;
27 use crate::{Position, RopeSlice};
28
29 #[derive(Debug, Clone, Copy)]
30 pub enum GraphemeSource {
31 Document {
32 codepoints: u32,
33 },
34 /// Inline virtual text can not be highlighted with a `Highlight` iterator
35 /// because it's not part of the document. Instead the `Highlight`
36 /// is emitted right by the document formatter
37 VirtualText {
38 highlight: Option<Highlight>,
39 },
40 }
41
42 impl GraphemeSource {
43 /// Returns whether this grapheme is virtual inline text
44 pub fn is_virtual(self) -> bool {
45 matches!(self, GraphemeSource::VirtualText { .. })
46 }
47
48 pub fn is_eof(self) -> bool {
49 // all doc chars except the EOF char have non-zero codepoints
50 matches!(self, GraphemeSource::Document { codepoints: 0 })
51 }
52
53 pub fn doc_chars(self) -> usize {
54 match self {
55 GraphemeSource::Document { codepoints } => codepoints as usize,
56 GraphemeSource::VirtualText { .. } => 0,
57 }
58 }
59 }
60
61 #[derive(Debug, Clone)]
62 pub struct FormattedGrapheme<'a> {
63 pub raw: Grapheme<'a>,
64 pub source: GraphemeSource,
65 pub visual_pos: Position,
66 /// Document line at the start of the grapheme
67 pub line_idx: usize,
68 /// Document char position at the start of the grapheme
69 pub char_idx: usize,
70 }
71
72 impl FormattedGrapheme<'_> {
73 pub fn is_virtual(&self) -> bool {
74 self.source.is_virtual()
75 }
76
77 pub fn doc_chars(&self) -> usize {
78 self.source.doc_chars()
79 }
80
81 pub fn is_whitespace(&self) -> bool {
82 self.raw.is_whitespace()
83 }
84
85 pub fn width(&self) -> usize {
86 self.raw.width()
87 }
88
89 pub fn is_word_boundary(&self) -> bool {
90 self.raw.is_word_boundary()
91 }
92 }
93
94 #[derive(Debug, Clone)]
95 struct GraphemeWithSource<'a> {
96 grapheme: Grapheme<'a>,
97 source: GraphemeSource,
98 }
99
100 impl<'a> GraphemeWithSource<'a> {
101 fn new(
102 g: GraphemeStr<'a>,
103 visual_x: usize,
104 tab_width: u16,
105 source: GraphemeSource,
106 ) -> GraphemeWithSource<'a> {
107 GraphemeWithSource {
108 grapheme: Grapheme::new(g, visual_x, tab_width),
109 source,
110 }
111 }
112 fn placeholder() -> Self {
113 GraphemeWithSource {
114 grapheme: Grapheme::Other { g: " ".into() },
115 source: GraphemeSource::Document { codepoints: 0 },
116 }
117 }
118
119 fn doc_chars(&self) -> usize {
120 self.source.doc_chars()
121 }
122
123 fn is_whitespace(&self) -> bool {
124 self.grapheme.is_whitespace()
125 }
126
127 fn is_newline(&self) -> bool {
128 matches!(self.grapheme, Grapheme::Newline)
129 }
130
131 fn is_eof(&self) -> bool {
132 self.source.is_eof()
133 }
134
135 fn width(&self) -> usize {
136 self.grapheme.width()
137 }
138
139 fn is_word_boundary(&self) -> bool {
140 self.grapheme.is_word_boundary()
141 }
142 }
143
144 #[derive(Debug, Clone)]
145 pub struct TextFormat {
146 pub soft_wrap: bool,
147 pub tab_width: u16,
148 pub max_wrap: u16,
149 pub max_indent_retain: u16,
150 pub wrap_indicator: Box<str>,
151 pub wrap_indicator_highlight: Option<Highlight>,
152 pub viewport_width: u16,
153 pub soft_wrap_at_text_width: bool,
154 }
155
156 // test implementation is basically only used for testing or when softwrap is always disabled
157 impl Default for TextFormat {
158 fn default() -> Self {
159 TextFormat {
160 soft_wrap: false,
161 tab_width: 4,
162 max_wrap: 3,
163 max_indent_retain: 4,
164 wrap_indicator: Box::from(" "),
165 viewport_width: 17,
166 wrap_indicator_highlight: None,
167 soft_wrap_at_text_width: false,
168 }
169 }
170 }
171
172 #[derive(Debug)]
173 pub struct DocumentFormatter<'t> {
174 text_fmt: &'t TextFormat,
175 annotations: &'t TextAnnotations<'t>,
176
177 /// The visual position at the end of the last yielded word boundary
178 visual_pos: Position,
179 graphemes: RopeGraphemes<'t>,
180 /// The character pos of the `graphemes` iter used for inserting annotations
181 char_pos: usize,
182 /// The line pos of the `graphemes` iter used for inserting annotations
183 line_pos: usize,
184 exhausted: bool,
185
186 inline_annotation_graphemes: Option<(Graphemes<'t>, Option<Highlight>)>,
187
188 // softwrap specific
189 /// The indentation of the current line
190 /// Is set to `None` if the indentation level is not yet known
191 /// because no non-whitespace graphemes have been encountered yet
192 indent_level: Option<usize>,
193 /// In case a long word needs to be split a single grapheme might need to be wrapped
194 /// while the rest of the word stays on the same line
195 peeked_grapheme: Option<GraphemeWithSource<'t>>,
196 /// A first-in first-out (fifo) buffer for the Graphemes of any given word
197 word_buf: Vec<GraphemeWithSource<'t>>,
198 /// The index of the next grapheme that will be yielded from the `word_buf`
199 word_i: usize,
200 }
201
202 impl<'t> DocumentFormatter<'t> {
203 /// Creates a new formatter at the last block before `char_idx`.
204 /// A block is a chunk which always ends with a linebreak.
205 /// This is usually just a normal line break.
206 /// However very long lines are always wrapped at constant intervals that can be cheaply calculated
207 /// to avoid pathological behaviour.
208 pub fn new_at_prev_checkpoint(
209 text: RopeSlice<'t>,
210 text_fmt: &'t TextFormat,
211 annotations: &'t TextAnnotations,
212 char_idx: usize,
213 ) -> Self {
214 // TODO divide long lines into blocks to avoid bad performance for long lines
215 let block_line_idx = text.char_to_line(char_idx.min(text.len_chars()));
216 let block_char_idx = text.line_to_char(block_line_idx);
217 annotations.reset_pos(block_char_idx);
218
219 DocumentFormatter {
220 text_fmt,
221 annotations,
222 visual_pos: Position { row: 0, col: 0 },
223 graphemes: text.slice(block_char_idx..).graphemes(),
224 char_pos: block_char_idx,
225 exhausted: false,
226 indent_level: None,
227 peeked_grapheme: None,
228 word_buf: Vec::with_capacity(64),
229 word_i: 0,
230 line_pos: block_line_idx,
231 inline_annotation_graphemes: None,
232 }
233 }
234
235 fn next_inline_annotation_grapheme(
236 &mut self,
237 char_pos: usize,
238 ) -> Option<(&'t str, Option<Highlight>)> {
239 loop {
240 if let Some(&mut (ref mut annotation, highlight)) =
241 self.inline_annotation_graphemes.as_mut()
242 {
243 if let Some(grapheme) = annotation.next() {
244 return Some((grapheme, highlight));
245 }
246 }
247
248 if let Some((annotation, highlight)) =
249 self.annotations.next_inline_annotation_at(char_pos)
250 {
251 self.inline_annotation_graphemes = Some((
252 UnicodeSegmentation::graphemes(&*annotation.text, true),
253 highlight,
254 ))
255 } else {
256 return None;
257 }
258 }
259 }
260
261 fn advance_grapheme(&mut self, col: usize, char_pos: usize) -> Option<GraphemeWithSource<'t>> {
262 let (grapheme, source) =
263 if let Some((grapheme, highlight)) = self.next_inline_annotation_grapheme(char_pos) {
264 (grapheme.into(), GraphemeSource::VirtualText { highlight })
265 } else if let Some(grapheme) = self.graphemes.next() {
266 let codepoints = grapheme.len_chars() as u32;
267
268 let overlay = self.annotations.overlay_at(char_pos);
269 let grapheme = match overlay {
270 Some((overlay, _)) => overlay.grapheme.as_str().into(),
271 None => Cow::from(grapheme).into(),
272 };
273
274 (grapheme, GraphemeSource::Document { codepoints })
275 } else {
276 if self.exhausted {
277 return None;
278 }
279 self.exhausted = true;
280 // EOF grapheme is required for rendering
281 // and correct position computations
282 return Some(GraphemeWithSource {
283 grapheme: Grapheme::Other { g: " ".into() },
284 source: GraphemeSource::Document { codepoints: 0 },
285 });
286 };
287
288 let grapheme = GraphemeWithSource::new(grapheme, col, self.text_fmt.tab_width, source);
289
290 Some(grapheme)
291 }
292
293 /// Move a word to the next visual line
294 fn wrap_word(&mut self) -> usize {
295 // softwrap this word to the next line
296 let indent_carry_over = if let Some(indent) = self.indent_level {
297 if indent as u16 <= self.text_fmt.max_indent_retain {
298 indent as u16
299 } else {
300 0
301 }
302 } else {
303 // ensure the indent stays 0
304 self.indent_level = Some(0);
305 0
306 };
307
308 let virtual_lines =
309 self.annotations
310 .virtual_lines_at(self.char_pos, self.visual_pos, self.line_pos);
311 self.visual_pos.col = indent_carry_over as usize;
312 self.visual_pos.row += 1 + virtual_lines;
313 let mut i = 0;
314 let mut word_width = 0;
315 let wrap_indicator = UnicodeSegmentation::graphemes(&*self.text_fmt.wrap_indicator, true)
316 .map(|g| {
317 i += 1;
318 let grapheme = GraphemeWithSource::new(
319 g.into(),
320 self.visual_pos.col + word_width,
321 self.text_fmt.tab_width,
322 GraphemeSource::VirtualText {
323 highlight: self.text_fmt.wrap_indicator_highlight,
324 },
325 );
326 word_width += grapheme.width();
327 grapheme
328 });
329 self.word_buf.splice(0..0, wrap_indicator);
330
331 for grapheme in &mut self.word_buf[i..] {
332 let visual_x = self.visual_pos.col + word_width;
333 grapheme
334 .grapheme
335 .change_position(visual_x, self.text_fmt.tab_width);
336 word_width += grapheme.width();
337 }
338 if let Some(grapheme) = &mut self.peeked_grapheme {
339 let visual_x = self.visual_pos.col + word_width;
340 grapheme
341 .grapheme
342 .change_position(visual_x, self.text_fmt.tab_width);
343 }
344 word_width
345 }
346
347 fn peek_grapheme(&mut self, col: usize, char_pos: usize) -> Option<&GraphemeWithSource<'t>> {
348 if self.peeked_grapheme.is_none() {
349 self.peeked_grapheme = self.advance_grapheme(col, char_pos);
350 }
351 self.peeked_grapheme.as_ref()
352 }
353
354 fn next_grapheme(&mut self, col: usize, char_pos: usize) -> Option<GraphemeWithSource<'t>> {
355 self.peek_grapheme(col, char_pos);
356 self.peeked_grapheme.take()
357 }
358
359 fn advance_to_next_word(&mut self) {
360 self.word_buf.clear();
361 let mut word_width = 0;
362 let mut word_chars = 0;
363
364 if self.exhausted {
365 return;
366 }
367
368 loop {
369 let mut col = self.visual_pos.col + word_width;
370 let char_pos = self.char_pos + word_chars;
371 match col.cmp(&(self.text_fmt.viewport_width as usize)) {
372 // The EOF char and newline chars are always selectable in helix. That means
373 // that wrapping happens "too-early" if a word fits a line perfectly. This
374 // is intentional so that all selectable graphemes are always visible (and
375 // therefore the cursor never disappears). However if the user manually set a
376 // lower softwrap width then this is undesirable. Just increasing the viewport-
377 // width by one doesn't work because if a line is wrapped multiple times then
378 // some words may extend past the specified width.
379 //
380 // So we special case a word that ends exactly at line bounds and is followed
381 // by a newline/eof character here.
382 Ordering::Equal
383 if self.text_fmt.soft_wrap_at_text_width
384 && self
385 .peek_grapheme(col, char_pos)
386 .is_some_and(|grapheme| grapheme.is_newline() || grapheme.is_eof()) => {
387 }
388 Ordering::Equal if word_width > self.text_fmt.max_wrap as usize => return,
389 Ordering::Greater if word_width > self.text_fmt.max_wrap as usize => {
390 self.peeked_grapheme = self.word_buf.pop();
391 return;
392 }
393 Ordering::Equal | Ordering::Greater => {
394 word_width = self.wrap_word();
395 col = self.visual_pos.col + word_width;
396 }
397 Ordering::Less => (),
398 }
399
400 let Some(grapheme) = self.next_grapheme(col, char_pos) else {
401 return;
402 };
403 word_chars += grapheme.doc_chars();
404
405 // Track indentation
406 if !grapheme.is_whitespace() && self.indent_level.is_none() {
407 self.indent_level = Some(self.visual_pos.col);
408 } else if grapheme.grapheme == Grapheme::Newline {
409 self.indent_level = None;
410 }
411
412 let is_word_boundary = grapheme.is_word_boundary();
413 word_width += grapheme.width();
414 self.word_buf.push(grapheme);
415
416 if is_word_boundary {
417 return;
418 }
419 }
420 }
421
422 /// returns the char index at the end of the last yielded grapheme
423 pub fn next_char_pos(&self) -> usize {
424 self.char_pos
425 }
426 /// returns the visual position at the end of the last yielded grapheme
427 pub fn next_visual_pos(&self) -> Position {
428 self.visual_pos
429 }
430 }
431
432 impl<'t> Iterator for DocumentFormatter<'t> {
433 type Item = FormattedGrapheme<'t>;
434
435 fn next(&mut self) -> Option<Self::Item> {
436 let grapheme = if self.text_fmt.soft_wrap {
437 if self.word_i >= self.word_buf.len() {
438 self.advance_to_next_word();
439 self.word_i = 0;
440 }
441 let grapheme = replace(
442 self.word_buf.get_mut(self.word_i)?,
443 GraphemeWithSource::placeholder(),
444 );
445 self.word_i += 1;
446 grapheme
447 } else {
448 self.advance_grapheme(self.visual_pos.col, self.char_pos)?
449 };
450
451 let grapheme = FormattedGrapheme {
452 raw: grapheme.grapheme,
453 source: grapheme.source,
454 visual_pos: self.visual_pos,
455 line_idx: self.line_pos,
456 char_idx: self.char_pos,
457 };
458
459 self.char_pos += grapheme.doc_chars();
460 if !grapheme.is_virtual() {
461 self.annotations.process_virtual_text_anchors(&grapheme);
462 }
463 if grapheme.raw == Grapheme::Newline {
464 // move to end of newline char
465 self.visual_pos.col += 1;
466 let virtual_lines =
467 self.annotations
468 .virtual_lines_at(self.char_pos, self.visual_pos, self.line_pos);
469 self.visual_pos.row += 1 + virtual_lines;
470 self.visual_pos.col = 0;
471 if !grapheme.is_virtual() {
472 self.line_pos += 1;
473 }
474 } else {
475 self.visual_pos.col += grapheme.width();
476 }
477 Some(grapheme)
478 }
479 }