Debian Codegraph @

helix-term/src/ui/document.rs

raw symbols SCIP
1 use std::cmp::min;
2
3 use helix_core::doc_formatter::{DocumentFormatter, FormattedGrapheme, GraphemeSource, TextFormat};
4 use helix_core::graphemes::Grapheme;
5 use helix_core::str_utils::char_to_byte_idx;
6 use helix_core::syntax::{self, HighlightEvent, Highlighter, OverlayHighlights};
7 use helix_core::text_annotations::TextAnnotations;
8 use helix_core::{visual_offset_from_block, Position, RopeSlice};
9 use helix_stdx::rope::RopeSliceExt;
10 use helix_view::editor::{WhitespaceConfig, WhitespaceRenderValue};
11 use helix_view::graphics::Rect;
12 use helix_view::theme::Style;
13 use helix_view::view::ViewPosition;
14 use helix_view::{Document, Theme};
15 use tui::buffer::Buffer as Surface;
16
17 use crate::ui::text_decorations::DecorationManager;
18
19 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
20 pub struct LinePos {
21 /// Indicates whether the given visual line
22 /// is the first visual line of the given document line
23 pub first_visual_line: bool,
24 /// The line index of the document line that contains the given visual line
25 pub doc_line: usize,
26 /// Vertical offset from the top of the inner view area
27 pub visual_line: u16,
28 }
29
30 #[allow(clippy::too_many_arguments)]
31 pub fn render_document(
32 surface: &mut Surface,
33 viewport: Rect,
34 doc: &Document,
35 offset: ViewPosition,
36 doc_annotations: &TextAnnotations,
37 syntax_highlighter: Option<Highlighter<'_>>,
38 overlay_highlights: Vec<syntax::OverlayHighlights>,
39 theme: &Theme,
40 decorations: DecorationManager,
41 ) {
42 let mut renderer = TextRenderer::new(
43 surface,
44 doc,
45 theme,
46 Position::new(offset.vertical_offset, offset.horizontal_offset),
47 viewport,
48 );
49 render_text(
50 &mut renderer,
51 doc.text().slice(..),
52 offset.anchor,
53 &doc.text_format(viewport.width, Some(theme)),
54 doc_annotations,
55 syntax_highlighter,
56 overlay_highlights,
57 theme,
58 decorations,
59 )
60 }
61
62 #[allow(clippy::too_many_arguments)]
63 pub fn render_text(
64 renderer: &mut TextRenderer,
65 text: RopeSlice<'_>,
66 anchor: usize,
67 text_fmt: &TextFormat,
68 text_annotations: &TextAnnotations,
69 syntax_highlighter: Option<Highlighter<'_>>,
70 overlay_highlights: Vec<syntax::OverlayHighlights>,
71 theme: &Theme,
72 mut decorations: DecorationManager,
73 ) {
74 let row_off = visual_offset_from_block(text, anchor, anchor, text_fmt, text_annotations)
75 .0
76 .row;
77
78 let mut formatter =
79 DocumentFormatter::new_at_prev_checkpoint(text, text_fmt, text_annotations, anchor);
80 let mut syntax_highlighter =
81 SyntaxHighlighter::new(syntax_highlighter, text, theme, renderer.text_style);
82 let mut overlay_highlighter = OverlayHighlighter::new(overlay_highlights, theme);
83
84 let mut last_line_pos = LinePos {
85 first_visual_line: false,
86 doc_line: usize::MAX,
87 visual_line: u16::MAX,
88 };
89 let mut last_line_end = 0;
90 let mut is_in_indent_area = true;
91 let mut last_line_indent_level = 0;
92 let mut reached_view_top = false;
93
94 loop {
95 let Some(mut grapheme) = formatter.next() else {
96 break;
97 };
98
99 // skip any graphemes on visual lines before the block start
100 if grapheme.visual_pos.row < row_off {
101 continue;
102 }
103 grapheme.visual_pos.row -= row_off;
104 if !reached_view_top {
105 decorations.prepare_for_rendering(grapheme.char_idx);
106 reached_view_top = true;
107 }
108
109 // if the end of the viewport is reached stop rendering
110 if grapheme.visual_pos.row as u16 >= renderer.viewport.height + renderer.offset.row as u16 {
111 break;
112 }
113
114 // apply decorations before rendering a new line
115 if grapheme.visual_pos.row as u16 != last_line_pos.visual_line {
116 // we initiate doc_line with usize::MAX because no file
117 // can reach that size (memory allocations are limited to isize::MAX)
118 // initially there is no "previous" line (so doc_line is set to usize::MAX)
119 // in that case we don't need to draw indent guides/virtual text
120 if last_line_pos.doc_line != usize::MAX {
121 // draw indent guides for the last line
122 renderer.draw_indent_guides(last_line_indent_level, last_line_pos.visual_line);
123 is_in_indent_area = true;
124 decorations.render_virtual_lines(renderer, last_line_pos, last_line_end)
125 }
126 last_line_pos = LinePos {
127 first_visual_line: grapheme.line_idx != last_line_pos.doc_line,
128 doc_line: grapheme.line_idx,
129 visual_line: grapheme.visual_pos.row as u16,
130 };
131 decorations.decorate_line(renderer, last_line_pos);
132 }
133
134 // acquire the correct grapheme style
135 while grapheme.char_idx >= syntax_highlighter.pos {
136 syntax_highlighter.advance();
137 }
138 while grapheme.char_idx >= overlay_highlighter.pos {
139 overlay_highlighter.advance();
140 }
141
142 let grapheme_style = if let GraphemeSource::VirtualText { highlight } = grapheme.source {
143 let mut style = renderer.text_style;
144 if let Some(highlight) = highlight {
145 style = style.patch(theme.highlight(highlight));
146 }
147 GraphemeStyle {
148 syntax_style: style,
149 overlay_style: Style::default(),
150 }
151 } else {
152 GraphemeStyle {
153 syntax_style: syntax_highlighter.style,
154 overlay_style: overlay_highlighter.style,
155 }
156 };
157 decorations.decorate_grapheme(renderer, &grapheme);
158
159 let virt = grapheme.is_virtual();
160 let grapheme_width = renderer.draw_grapheme(
161 &grapheme,
162 grapheme_style,
163 virt,
164 &mut last_line_indent_level,
165 &mut is_in_indent_area,
166 grapheme.visual_pos,
167 );
168 last_line_end = grapheme.visual_pos.col + grapheme_width;
169 }
170
171 renderer.draw_indent_guides(last_line_indent_level, last_line_pos.visual_line);
172 decorations.render_virtual_lines(renderer, last_line_pos, last_line_end)
173 }
174
175 #[derive(Debug)]
176 pub struct TextRenderer<'a> {
177 surface: &'a mut Surface,
178 pub text_style: Style,
179 pub whitespace_style: Style,
180 pub indent_guide_char: String,
181 pub indent_guide_style: Style,
182 pub newline: String,
183 pub nbsp: String,
184 pub nnbsp: String,
185 pub space: String,
186 pub tab: String,
187 pub virtual_tab: String,
188 pub indent_width: u16,
189 pub starting_indent: usize,
190 pub draw_indent_guides: bool,
191 pub viewport: Rect,
192 pub offset: Position,
193 }
194
195 pub struct GraphemeStyle {
196 syntax_style: Style,
197 overlay_style: Style,
198 }
199
200 impl<'a> TextRenderer<'a> {
201 pub fn new(
202 surface: &'a mut Surface,
203 doc: &Document,
204 theme: &Theme,
205 offset: Position,
206 viewport: Rect,
207 ) -> TextRenderer<'a> {
208 let editor_config = doc.config.load();
209 let WhitespaceConfig {
210 render: ws_render,
211 characters: ws_chars,
212 } = &editor_config.whitespace;
213
214 let tab_width = doc.tab_width();
215 let tab = if ws_render.tab() == WhitespaceRenderValue::All {
216 std::iter::once(ws_chars.tab)
217 .chain(std::iter::repeat_n(ws_chars.tabpad, tab_width - 1))
218 .collect()
219 } else {
220 " ".repeat(tab_width)
221 };
222 let virtual_tab = " ".repeat(tab_width);
223 let newline = if ws_render.newline() == WhitespaceRenderValue::All {
224 ws_chars.newline.into()
225 } else {
226 " ".to_owned()
227 };
228
229 let space = if ws_render.space() == WhitespaceRenderValue::All {
230 ws_chars.space.into()
231 } else {
232 " ".to_owned()
233 };
234 let nbsp = if ws_render.nbsp() == WhitespaceRenderValue::All {
235 ws_chars.nbsp.into()
236 } else {
237 " ".to_owned()
238 };
239 let nnbsp = if ws_render.nnbsp() == WhitespaceRenderValue::All {
240 ws_chars.nnbsp.into()
241 } else {
242 " ".to_owned()
243 };
244
245 let text_style = theme.get("ui.text");
246
247 let indent_width = doc.indent_style.indent_width(tab_width) as u16;
248
249 TextRenderer {
250 surface,
251 indent_guide_char: editor_config.indent_guides.character.into(),
252 newline,
253 nbsp,
254 nnbsp,
255 space,
256 tab,
257 virtual_tab,
258 whitespace_style: theme.get("ui.virtual.whitespace"),
259 indent_width,
260 starting_indent: offset.col / indent_width as usize
261 + !offset.col.is_multiple_of(indent_width as usize) as usize
262 + editor_config.indent_guides.skip_levels as usize,
263 indent_guide_style: text_style.patch(
264 theme
265 .try_get("ui.virtual.indent-guide")
266 .unwrap_or_else(|| theme.get("ui.virtual.whitespace")),
267 ),
268 text_style,
269 draw_indent_guides: editor_config.indent_guides.render,
270 viewport,
271 offset,
272 }
273 }
274 /// Draws a single `grapheme` at the current render position with a specified `style`.
275 pub fn draw_decoration_grapheme(
276 &mut self,
277 grapheme: Grapheme,
278 mut style: Style,
279 mut row: u16,
280 col: u16,
281 ) -> bool {
282 if (row as usize) < self.offset.row
283 || row >= self.viewport.height
284 || col >= self.viewport.width
285 {
286 return false;
287 }
288 row -= self.offset.row as u16;
289 // TODO is it correct to apply the whitspace style to all unicode white spaces?
290 if grapheme.is_whitespace() {
291 style = style.patch(self.whitespace_style);
292 }
293
294 let grapheme = match grapheme {
295 Grapheme::Tab { width } => {
296 let grapheme_tab_width = char_to_byte_idx(&self.virtual_tab, width);
297 &self.virtual_tab[..grapheme_tab_width]
298 }
299 Grapheme::Other { ref g } if g == "\u{00A0}" => " ",
300 Grapheme::Other { ref g } => g,
301 Grapheme::Newline => " ",
302 };
303
304 self.surface.set_string(
305 self.viewport.x + col,
306 self.viewport.y + row,
307 grapheme,
308 style,
309 );
310 true
311 }
312
313 /// Draws a single `grapheme` at the current render position with a specified `style`.
314 pub fn draw_grapheme(
315 &mut self,
316 grapheme: &FormattedGrapheme,
317 grapheme_style: GraphemeStyle,
318 is_virtual: bool,
319 last_indent_level: &mut usize,
320 is_in_indent_area: &mut bool,
321 mut position: Position,
322 ) -> usize {
323 if position.row < self.offset.row {
324 return 0;
325 }
326 position.row -= self.offset.row;
327 let cut_off_start = self.offset.col.saturating_sub(position.col);
328 let is_whitespace = grapheme.is_whitespace();
329
330 // TODO is it correct to apply the whitespace style to all unicode white spaces?
331 let mut style = grapheme_style.syntax_style;
332 if is_whitespace {
333 style = style.patch(self.whitespace_style);
334 }
335 style = style.patch(grapheme_style.overlay_style);
336
337 let width = grapheme.width();
338 let mut is_tab = false;
339 let space = if is_virtual { " " } else { &self.space };
340 let nbsp = if is_virtual { " " } else { &self.nbsp };
341 let nnbsp = if is_virtual { " " } else { &self.nnbsp };
342 let tab = if is_virtual {
343 &self.virtual_tab
344 } else {
345 &self.tab
346 };
347 let grapheme = match grapheme.raw {
348 Grapheme::Tab { width } => {
349 is_tab = true;
350 let grapheme_tab_width = char_to_byte_idx(tab, width);
351 &tab[..grapheme_tab_width]
352 }
353 // TODO special rendering for other whitespaces?
354 Grapheme::Other { ref g } if g == " " && !grapheme.source.is_eof() => space,
355 Grapheme::Other { ref g } if g == "\u{00A0}" => nbsp,
356 Grapheme::Other { ref g } if g == "\u{202F}" => nnbsp,
357 Grapheme::Other { ref g } => g,
358 Grapheme::Newline => &self.newline,
359 };
360
361 let in_bounds = self.column_in_bounds(position.col, width);
362
363 if in_bounds {
364 let x = self.viewport.x + (position.col - self.offset.col) as u16;
365 let y = self.viewport.y + position.row as u16;
366 if is_tab {
367 // A tab expands to `width` single-column cells; writing them
368 // individually keeps background styles (selection, cursorline)
369 // across the whole tab and avoids the redraw diff clipping
370 // `render-whitespace` pads. A single `set_grapheme` would pack
371 // them into one wide cell and leave the rest unstyled.
372 self.surface.set_tab(x, y, grapheme, style);
373 } else {
374 self.surface.set_grapheme(x, y, grapheme, width, style);
375 }
376 } else if cut_off_start != 0 && cut_off_start < width {
377 // partially on screen
378 let rect = Rect::new(
379 self.viewport.x,
380 self.viewport.y + position.row as u16,
381 (width - cut_off_start) as u16,
382 1,
383 );
384 self.surface.set_style(rect, style);
385 }
386 if *is_in_indent_area && !is_whitespace {
387 *last_indent_level = position.col;
388 *is_in_indent_area = false;
389 }
390
391 width
392 }
393
394 pub fn column_in_bounds(&self, colum: usize, width: usize) -> bool {
395 self.offset.col <= colum && colum + width <= self.offset.col + self.viewport.width as usize
396 }
397
398 /// Overlay indentation guides ontop of a rendered line
399 /// The indentation level is computed in `draw_lines`.
400 /// Therefore this function must always be called afterwards.
401 pub fn draw_indent_guides(&mut self, indent_level: usize, mut row: u16) {
402 if !self.draw_indent_guides || self.offset.row > row as usize {
403 return;
404 }
405 row -= self.offset.row as u16;
406
407 // Don't draw indent guides outside of view
408 let end_indent = min(
409 indent_level,
410 // Add indent_width - 1 to round up, since the first visible
411 // indent might be a bit after offset.col
412 self.offset.col + self.viewport.width as usize + (self.indent_width as usize - 1),
413 ) / self.indent_width as usize;
414
415 for i in self.starting_indent..end_indent {
416 let x = (self.viewport.x as usize + (i * self.indent_width as usize) - self.offset.col)
417 as u16;
418 let y = self.viewport.y + row;
419 debug_assert!(self.surface.in_bounds(x, y));
420 self.surface
421 .set_string(x, y, &self.indent_guide_char, self.indent_guide_style);
422 }
423 }
424
425 pub fn set_string(&mut self, x: u16, y: u16, string: &str, style: Style) {
426 if (y as usize) < self.offset.row {
427 return;
428 }
429 self.surface
430 .set_string(x, y + self.viewport.y, string, style)
431 }
432
433 pub fn set_stringn(&mut self, x: u16, y: u16, string: &str, width: usize, style: Style) {
434 if (y as usize) < self.offset.row {
435 return;
436 }
437 self.surface
438 .set_stringn(x, y + self.viewport.y, string, width, style);
439 }
440
441 /// Sets the style of an area **within the text viewport* this accounts
442 /// both for the renderers vertical offset and its viewport
443 pub fn set_style(&mut self, mut area: Rect, style: Style) {
444 area = area.clip_top(self.offset.row as u16);
445 area.y += self.viewport.y;
446 self.surface.set_style(area, style);
447 }
448
449 #[allow(clippy::too_many_arguments)]
450 pub fn set_string_truncated(
451 &mut self,
452 x: u16,
453 y: u16,
454 string: &str,
455 width: usize,
456 style: impl Fn(usize) -> Style, // Map a grapheme's string offset to a style
457 ellipsis: bool,
458 truncate_start: bool,
459 ) -> (u16, u16) {
460 if (y as usize) < self.offset.row {
461 return (x, y);
462 }
463 self.surface.set_string_truncated(
464 x,
465 y + self.viewport.y,
466 string,
467 width,
468 style,
469 ellipsis,
470 truncate_start,
471 )
472 }
473 }
474
475 struct SyntaxHighlighter<'h, 'r, 't> {
476 inner: Option<Highlighter<'h>>,
477 text: RopeSlice<'r>,
478 /// The character index of the next highlight event, or `usize::MAX` if the highlighter is
479 /// finished.
480 pos: usize,
481 theme: &'t Theme,
482 text_style: Style,
483 style: Style,
484 }
485
486 impl<'h, 'r, 't> SyntaxHighlighter<'h, 'r, 't> {
487 fn new(
488 inner: Option<Highlighter<'h>>,
489 text: RopeSlice<'r>,
490 theme: &'t Theme,
491 text_style: Style,
492 ) -> Self {
493 let mut highlighter = Self {
494 inner,
495 text,
496 pos: 0,
497 theme,
498 style: text_style,
499 text_style,
500 };
501 highlighter.update_pos();
502 highlighter
503 }
504
505 fn update_pos(&mut self) {
506 self.pos = self
507 .inner
508 .as_ref()
509 .and_then(|highlighter| {
510 let next_byte_idx = highlighter.next_event_offset();
511 (next_byte_idx != u32::MAX).then(|| {
512 // Move the byte index to the nearest character boundary (rounding up) and
513 // convert it to a character index.
514 self.text
515 .byte_to_char(self.text.ceil_char_boundary(next_byte_idx as usize))
516 })
517 })
518 .unwrap_or(usize::MAX);
519 }
520
521 fn advance(&mut self) {
522 let Some(highlighter) = self.inner.as_mut() else {
523 return;
524 };
525
526 let (event, highlights) = highlighter.advance();
527 let base = match event {
528 HighlightEvent::Refresh => self.text_style,
529 HighlightEvent::Push => self.style,
530 };
531
532 self.style = highlights.fold(base, |acc, highlight| {
533 acc.patch(self.theme.highlight(highlight))
534 });
535 self.update_pos();
536 }
537 }
538
539 struct OverlayHighlighter<'t> {
540 inner: syntax::OverlayHighlighter,
541 pos: usize,
542 theme: &'t Theme,
543 style: Style,
544 }
545
546 impl<'t> OverlayHighlighter<'t> {
547 fn new(overlays: Vec<OverlayHighlights>, theme: &'t Theme) -> Self {
548 let inner = syntax::OverlayHighlighter::new(overlays);
549 let mut highlighter = Self {
550 inner,
551 pos: 0,
552 theme,
553 style: Style::default(),
554 };
555 highlighter.update_pos();
556 highlighter
557 }
558
559 fn update_pos(&mut self) {
560 self.pos = self.inner.next_event_offset();
561 }
562
563 fn advance(&mut self) {
564 let (event, highlights) = self.inner.advance();
565 let base = match event {
566 HighlightEvent::Refresh => Style::default(),
567 HighlightEvent::Push => self.style,
568 };
569
570 self.style = highlights.fold(base, |acc, highlight| {
571 acc.patch(self.theme.highlight(highlight))
572 });
573 self.update_pos();
574 }
575 }