Debian Codegraph @

helix-view/src/gutter.rs

raw symbols SCIP
1 use std::fmt::Write;
2
3 use helix_core::syntax::config::LanguageServerFeature;
4
5 use crate::{
6 editor::GutterType,
7 graphics::{Style, UnderlineStyle},
8 Document, Editor, Theme, View,
9 };
10
11 fn count_digits(n: usize) -> usize {
12 (usize::checked_ilog10(n).unwrap_or(0) + 1) as usize
13 }
14
15 pub type GutterFn<'doc> = Box<dyn FnMut(usize, bool, bool, &mut String) -> Option<Style> + 'doc>;
16 pub type Gutter =
17 for<'doc> fn(&'doc Editor, &'doc Document, &View, &Theme, bool, usize) -> GutterFn<'doc>;
18
19 impl GutterType {
20 pub fn style<'doc>(
21 self,
22 editor: &'doc Editor,
23 doc: &'doc Document,
24 view: &View,
25 theme: &Theme,
26 is_focused: bool,
27 ) -> GutterFn<'doc> {
28 match self {
29 GutterType::Diagnostics => {
30 diagnostics_or_breakpoints(editor, doc, view, theme, is_focused)
31 }
32 GutterType::LineNumbers => line_numbers(editor, doc, view, theme, is_focused),
33 GutterType::Spacer => padding(editor, doc, view, theme, is_focused),
34 GutterType::Diff => diff(editor, doc, view, theme, is_focused),
35 GutterType::CodeActionHint => code_action_hint(editor, doc, view, theme, is_focused),
36 }
37 }
38
39 pub fn width(self, view: &View, doc: &Document) -> usize {
40 match self {
41 GutterType::Diagnostics => 1,
42 GutterType::LineNumbers => line_numbers_width(view, doc),
43 GutterType::Spacer => 1,
44 GutterType::Diff => 1,
45 GutterType::CodeActionHint => 1,
46 }
47 }
48 }
49
50 pub fn diagnostic<'doc>(
51 _editor: &'doc Editor,
52 doc: &'doc Document,
53 _view: &View,
54 theme: &Theme,
55 _is_focused: bool,
56 ) -> GutterFn<'doc> {
57 let warning = theme.get("warning");
58 let error = theme.get("error");
59 let info = theme.get("info");
60 let hint = theme.get("hint");
61 let diagnostics = &doc.diagnostics;
62
63 Box::new(
64 move |line: usize, _selected: bool, first_visual_line: bool, out: &mut String| {
65 if !first_visual_line {
66 return None;
67 }
68 use helix_core::diagnostic::Severity;
69 let first_diag_idx_maybe_on_line = diagnostics.partition_point(|d| d.line < line);
70 let diagnostics_on_line = diagnostics[first_diag_idx_maybe_on_line..]
71 .iter()
72 .take_while(|d| {
73 d.line == line
74 && d.provider.language_server_id().is_none_or(|id| {
75 doc.language_servers_with_feature(LanguageServerFeature::Diagnostics)
76 .any(|ls| ls.id() == id)
77 })
78 });
79 diagnostics_on_line.max_by_key(|d| d.severity).map(|d| {
80 write!(out, "●").ok();
81 match d.severity {
82 Some(Severity::Error) => error,
83 Some(Severity::Warning) | None => warning,
84 Some(Severity::Info) => info,
85 Some(Severity::Hint) => hint,
86 }
87 })
88 },
89 )
90 }
91
92 pub fn diff<'doc>(
93 _editor: &'doc Editor,
94 doc: &'doc Document,
95 _view: &View,
96 theme: &Theme,
97 _is_focused: bool,
98 ) -> GutterFn<'doc> {
99 let added = theme.get("diff.plus.gutter");
100 let deleted = theme.get("diff.minus.gutter");
101 let modified = theme.get("diff.delta.gutter");
102 if let Some(diff_handle) = doc.diff_handle() {
103 let hunks = diff_handle.load();
104 let mut hunk_i = 0;
105 let mut hunk = hunks.nth_hunk(hunk_i);
106 Box::new(
107 move |line: usize, _selected: bool, first_visual_line: bool, out: &mut String| {
108 // truncating the line is fine here because we don't compute diffs
109 // for files with more lines than i32::MAX anyways
110 // we need to special case removals here
111 // these technically do not have a range of lines to highlight (`hunk.after.start == hunk.after.end`).
112 // However we still want to display these hunks correctly we must not yet skip to the next hunk here
113 while hunk.after.end < line as u32
114 || !hunk.is_pure_removal() && line as u32 == hunk.after.end
115 {
116 hunk_i += 1;
117 hunk = hunks.nth_hunk(hunk_i);
118 }
119
120 if hunk.after.start > line as u32 {
121 return None;
122 }
123
124 let (icon, style) = if hunk.is_pure_insertion() {
125 ("▍", added)
126 } else if hunk.is_pure_removal() {
127 if !first_visual_line {
128 return None;
129 }
130 ("▔", deleted)
131 } else {
132 ("▍", modified)
133 };
134
135 write!(out, "{}", icon).unwrap();
136 Some(style)
137 },
138 )
139 } else {
140 Box::new(move |_, _, _, _| None)
141 }
142 }
143
144 pub fn line_numbers<'doc>(
145 editor: &'doc Editor,
146 doc: &'doc Document,
147 view: &View,
148 theme: &Theme,
149 is_focused: bool,
150 ) -> GutterFn<'doc> {
151 let text = doc.text().slice(..);
152 let width = line_numbers_width(view, doc);
153
154 let last_line_in_view = view.estimate_last_doc_line(doc);
155
156 // Whether to draw the line number for the last line of the
157 // document or not. We only draw it if it's not an empty line.
158 let draw_last = text.line_to_byte(last_line_in_view) < text.len_bytes();
159
160 let linenr = theme.get("ui.linenr");
161 let linenr_select = theme.get("ui.linenr.selected");
162
163 let current_line = doc
164 .text()
165 .char_to_line(doc.selection(view.id).primary().cursor(text));
166
167 let line_number = editor.config().line_number;
168 let mode = editor.mode;
169
170 Box::new(
171 move |line: usize, selected: bool, first_visual_line: bool, out: &mut String| {
172 if line == last_line_in_view && !draw_last {
173 write!(out, "{:>1$}", '~', width).unwrap();
174 Some(linenr)
175 } else {
176 use crate::{document::Mode, editor::LineNumber};
177
178 let relative = line_number == LineNumber::Relative
179 && mode != Mode::Insert
180 && is_focused
181 && current_line != line;
182
183 let display_num = if relative {
184 current_line.abs_diff(line)
185 } else {
186 line + 1
187 };
188
189 let style = if selected && is_focused {
190 linenr_select
191 } else {
192 linenr
193 };
194
195 if first_visual_line {
196 write!(out, "{:>1$}", display_num, width).unwrap();
197 } else {
198 write!(out, "{:>1$}", " ", width).unwrap();
199 }
200
201 first_visual_line.then_some(style)
202 }
203 },
204 )
205 }
206
207 /// The width of a "line-numbers" gutter
208 ///
209 /// The width of the gutter depends on the number of lines in the document,
210 /// whether there is content on the last line (the `~` line), and the
211 /// `editor.gutters.line-numbers.min-width` settings.
212 fn line_numbers_width(view: &View, doc: &Document) -> usize {
213 let text = doc.text();
214 let last_line = text.len_lines().saturating_sub(1);
215 let draw_last = text.line_to_byte(last_line) < text.len_bytes();
216 let last_drawn = if draw_last { last_line + 1 } else { last_line };
217 let digits = count_digits(last_drawn);
218 let n_min = view.gutters.line_numbers.min_width;
219 digits.max(n_min)
220 }
221
222 pub fn padding<'doc>(
223 _editor: &'doc Editor,
224 _doc: &'doc Document,
225 _view: &View,
226 _theme: &Theme,
227 _is_focused: bool,
228 ) -> GutterFn<'doc> {
229 Box::new(|_line: usize, _selected: bool, _first_visual_line: bool, _out: &mut String| None)
230 }
231
232 pub fn breakpoints<'doc>(
233 editor: &'doc Editor,
234 doc: &'doc Document,
235 _view: &View,
236 theme: &Theme,
237 _is_focused: bool,
238 ) -> GutterFn<'doc> {
239 let error = theme.get("error");
240 let info = theme.get("info");
241 let breakpoint_style = theme.get("ui.debug.breakpoint");
242
243 let breakpoints = doc.path().and_then(|path| editor.breakpoints.get(path));
244
245 let breakpoints = match breakpoints {
246 Some(breakpoints) => breakpoints,
247 None => return Box::new(move |_, _, _, _| None),
248 };
249
250 Box::new(
251 move |line: usize, _selected: bool, first_visual_line: bool, out: &mut String| {
252 if !first_visual_line {
253 return None;
254 }
255 let breakpoint = breakpoints
256 .iter()
257 .find(|breakpoint| breakpoint.line == line)?;
258
259 let style = if breakpoint.condition.is_some() && breakpoint.log_message.is_some() {
260 error.underline_style(UnderlineStyle::Line)
261 } else if breakpoint.condition.is_some() {
262 error
263 } else if breakpoint.log_message.is_some() {
264 info
265 } else {
266 breakpoint_style
267 };
268
269 let sym = if breakpoint.verified { "●" } else { "◯" };
270 write!(out, "{}", sym).unwrap();
271 Some(style)
272 },
273 )
274 }
275
276 fn execution_pause_indicator<'doc>(
277 editor: &'doc Editor,
278 doc: &'doc Document,
279 theme: &Theme,
280 is_focused: bool,
281 ) -> GutterFn<'doc> {
282 let style = theme.get("ui.debug.active");
283 let current_stack_frame = editor.current_stack_frame();
284 let frame_line = current_stack_frame.map(|frame| frame.line.saturating_sub(1));
285 let frame_source_path = current_stack_frame.map(|frame| {
286 frame
287 .source
288 .as_ref()
289 .and_then(|source| source.path.as_deref())
290 });
291
292 let should_display_for_current_doc =
293 doc.path().is_some() && frame_source_path.unwrap_or(None) == doc.path();
294
295 Box::new(
296 move |line: usize, _selected: bool, first_visual_line: bool, out: &mut String| {
297 if !first_visual_line
298 || !is_focused
299 || line != frame_line?
300 || !should_display_for_current_doc
301 {
302 return None;
303 }
304
305 let sym = "▶";
306 write!(out, "{}", sym).unwrap();
307 Some(style)
308 },
309 )
310 }
311
312 pub fn diagnostics_or_breakpoints<'doc>(
313 editor: &'doc Editor,
314 doc: &'doc Document,
315 view: &View,
316 theme: &Theme,
317 is_focused: bool,
318 ) -> GutterFn<'doc> {
319 let mut diagnostics = diagnostic(editor, doc, view, theme, is_focused);
320 let mut breakpoints = breakpoints(editor, doc, view, theme, is_focused);
321 let mut execution_pause_indicator = execution_pause_indicator(editor, doc, theme, is_focused);
322
323 Box::new(move |line, selected, first_visual_line: bool, out| {
324 execution_pause_indicator(line, selected, first_visual_line, out)
325 .or_else(|| breakpoints(line, selected, first_visual_line, out))
326 .or_else(|| diagnostics(line, selected, first_visual_line, out))
327 })
328 }
329
330 pub fn code_action_hint<'doc>(
331 _editor: &'doc Editor,
332 doc: &'doc Document,
333 view: &View,
334 theme: &Theme,
335 is_focused: bool,
336 ) -> GutterFn<'doc> {
337 let style = theme.get("ui.text");
338 let text = doc.text().slice(..);
339 let show_hint = doc.code_action_hints(view.id);
340 let current_line = doc
341 .text()
342 .char_to_line(doc.selection(view.id).primary().cursor(text));
343
344 Box::new(
345 move |line: usize, _selected: bool, first_visual_line: bool, out: &mut String| {
346 (is_focused && show_hint && current_line == line && first_visual_line).then(|| {
347 write!(out, "⋮").unwrap();
348 style
349 })
350 },
351 )
352 }
353
354 #[cfg(test)]
355 mod tests {
356 use std::sync::Arc;
357
358 use super::*;
359 use crate::document::Document;
360 use crate::editor::{Config, GutterConfig, GutterLineNumbersConfig};
361 use crate::graphics::Rect;
362 use crate::DocumentId;
363 use arc_swap::ArcSwap;
364 use helix_core::{syntax, Rope};
365
366 #[test]
367 fn test_default_gutter_widths() {
368 let mut view = View::new(DocumentId::default(), GutterConfig::default());
369 view.area = Rect::new(40, 40, 40, 40);
370
371 let rope = Rope::from_str("abc\n\tdef");
372 let doc = Document::from(
373 rope,
374 None,
375 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
376 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
377 );
378
379 assert_eq!(view.gutters.layout.len(), 5);
380 assert_eq!(view.gutters.layout[0].width(&view, &doc), 1);
381 assert_eq!(view.gutters.layout[1].width(&view, &doc), 1);
382 assert_eq!(view.gutters.layout[2].width(&view, &doc), 3);
383 assert_eq!(view.gutters.layout[3].width(&view, &doc), 1);
384 assert_eq!(view.gutters.layout[4].width(&view, &doc), 1);
385 }
386
387 #[test]
388 fn test_configured_gutter_widths() {
389 let gutters = GutterConfig {
390 layout: vec![GutterType::Diagnostics],
391 ..Default::default()
392 };
393
394 let mut view = View::new(DocumentId::default(), gutters);
395 view.area = Rect::new(40, 40, 40, 40);
396
397 let rope = Rope::from_str("abc\n\tdef");
398 let doc = Document::from(
399 rope,
400 None,
401 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
402 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
403 );
404
405 assert_eq!(view.gutters.layout.len(), 1);
406 assert_eq!(view.gutters.layout[0].width(&view, &doc), 1);
407
408 let gutters = GutterConfig {
409 layout: vec![GutterType::Diagnostics, GutterType::LineNumbers],
410 line_numbers: GutterLineNumbersConfig { min_width: 10 },
411 };
412
413 let mut view = View::new(DocumentId::default(), gutters);
414 view.area = Rect::new(40, 40, 40, 40);
415
416 let rope = Rope::from_str("abc\n\tdef");
417 let doc = Document::from(
418 rope,
419 None,
420 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
421 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
422 );
423
424 assert_eq!(view.gutters.layout.len(), 2);
425 assert_eq!(view.gutters.layout[0].width(&view, &doc), 1);
426 assert_eq!(view.gutters.layout[1].width(&view, &doc), 10);
427 }
428
429 #[test]
430 fn test_line_numbers_gutter_width_resizes() {
431 let gutters = GutterConfig {
432 layout: vec![GutterType::Diagnostics, GutterType::LineNumbers],
433 line_numbers: GutterLineNumbersConfig { min_width: 1 },
434 };
435
436 let mut view = View::new(DocumentId::default(), gutters);
437 view.area = Rect::new(40, 40, 40, 40);
438
439 let rope = Rope::from_str("a\nb");
440 let doc_short = Document::from(
441 rope,
442 None,
443 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
444 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
445 );
446
447 let rope = Rope::from_str("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np");
448 let doc_long = Document::from(
449 rope,
450 None,
451 Arc::new(ArcSwap::new(Arc::new(Config::default()))),
452 Arc::new(ArcSwap::from_pointee(syntax::Loader::default())),
453 );
454
455 assert_eq!(view.gutters.layout.len(), 2);
456 assert_eq!(view.gutters.layout[1].width(&view, &doc_short), 1);
457 assert_eq!(view.gutters.layout[1].width(&view, &doc_long), 2);
458 }
459 }