Debian Codegraph @

helix-term/src/ui/editor.rs

raw symbols SCIP
1 use crate::{
2 commands::{self, OnKeyCallback, OnKeyCallbackKind},
3 compositor::{Component, Context, Event, EventResult},
4 events::{OnModeSwitch, PostCommand},
5 handlers::completion::CompletionItem,
6 key,
7 keymap::{KeymapResult, Keymaps},
8 ui::{
9 document::{render_document, LinePos, TextRenderer},
10 statusline,
11 text_decorations::{self, Decoration, DecorationManager, InlineDiagnostics},
12 Completion, ProgressSpinners,
13 },
14 };
15
16 use helix_core::{
17 diagnostic::NumberOrString,
18 graphemes::{next_grapheme_boundary, prev_grapheme_boundary},
19 movement::Direction,
20 syntax::{self, OverlayHighlights},
21 text_annotations::TextAnnotations,
22 unicode::width::UnicodeWidthStr,
23 visual_offset_from_block, Change, Position, Range, Selection, Transaction,
24 };
25 use helix_view::{
26 annotations::diagnostics::DiagnosticFilter,
27 document::{Mode, SCRATCH_BUFFER_NAME},
28 editor::{CompleteAction, CursorShapeConfig},
29 graphics::{Color, CursorKind, Modifier, Rect, Style},
30 input::{KeyEvent, MouseButton, MouseEvent, MouseEventKind},
31 keyboard::{KeyCode, KeyModifiers},
32 Document, Editor, Theme, View,
33 };
34 use std::{mem::take, num::NonZeroUsize, ops, path::PathBuf, rc::Rc};
35
36 use tui::{buffer::Buffer as Surface, text::Span};
37
38 pub struct EditorView {
39 pub keymaps: Keymaps,
40 on_next_key: Option<(OnKeyCallback, OnKeyCallbackKind)>,
41 pseudo_pending: Vec<KeyEvent>,
42 pub(crate) last_insert: (commands::MappableCommand, Vec<InsertEvent>),
43 pub(crate) completion: Option<Completion>,
44 spinners: ProgressSpinners,
45 /// Tracks if the terminal window is focused by reaction to terminal focus events
46 terminal_focused: bool,
47 }
48
49 #[derive(Debug, Clone)]
50 pub enum InsertEvent {
51 Key(KeyEvent),
52 CompletionApply {
53 trigger_offset: usize,
54 changes: Vec<Change>,
55 },
56 TriggerCompletion,
57 RequestCompletion,
58 }
59
60 impl EditorView {
61 pub fn new(keymaps: Keymaps) -> Self {
62 Self {
63 keymaps,
64 on_next_key: None,
65 pseudo_pending: Vec::new(),
66 last_insert: (commands::MappableCommand::normal_mode, Vec::new()),
67 completion: None,
68 spinners: ProgressSpinners::default(),
69 terminal_focused: true,
70 }
71 }
72
73 pub fn spinners_mut(&mut self) -> &mut ProgressSpinners {
74 &mut self.spinners
75 }
76
77 pub fn render_view(
78 &self,
79 editor: &Editor,
80 doc: &Document,
81 view: &View,
82 viewport: Rect,
83 surface: &mut Surface,
84 is_focused: bool,
85 ) {
86 let inner = view.inner_area(doc);
87 let area = view.area;
88 let theme = &editor.theme;
89 let config = editor.config();
90 let loader = editor.syn_loader.load();
91
92 let view_offset = doc.view_offset(view.id);
93
94 let text_annotations = view.text_annotations(doc, Some(theme));
95 let mut decorations = DecorationManager::default();
96
97 if is_focused && config.cursorline {
98 decorations.add_decoration(Self::cursorline(doc, view, theme));
99 }
100
101 if is_focused && config.cursorcolumn {
102 Self::highlight_cursorcolumn(doc, view, surface, theme, inner, &text_annotations);
103 }
104
105 // Set DAP highlights, if needed.
106 if let Some(frame) = editor.current_stack_frame() {
107 let dap_line = frame.line.saturating_sub(1);
108 let style = theme.get("ui.highlight.frameline");
109 let line_decoration = move |renderer: &mut TextRenderer, pos: LinePos| {
110 if pos.doc_line != dap_line {
111 return;
112 }
113 renderer.set_style(Rect::new(inner.x, pos.visual_line, inner.width, 1), style);
114 };
115
116 decorations.add_decoration(line_decoration);
117 }
118
119 let syntax_highlighter =
120 Self::doc_syntax_highlighter(doc, view_offset.anchor, inner.height, &loader);
121 let mut overlays = Vec::new();
122
123 overlays.push(Self::overlay_syntax_highlights(
124 doc,
125 view_offset.anchor,
126 inner.height,
127 &text_annotations,
128 ));
129
130 if doc
131 .language_config()
132 .and_then(|config| config.rainbow_brackets)
133 .unwrap_or(config.rainbow_brackets)
134 {
135 if let Some(overlay) =
136 Self::doc_rainbow_highlights(doc, view_offset.anchor, inner.height, theme, &loader)
137 {
138 overlays.push(overlay);
139 }
140 }
141
142 if let Some(overlay) = Self::doc_document_link_highlights(doc, theme) {
143 overlays.push(overlay);
144 }
145
146 Self::doc_diagnostics_highlights_into(doc, theme, &mut overlays);
147
148 if is_focused {
149 if config.lsp.auto_document_highlight {
150 if let Some(overlay) = Self::doc_document_highlights(doc, view, theme) {
151 overlays.push(overlay);
152 }
153 }
154 if let Some(tabstops) = Self::tabstop_highlights(doc, theme) {
155 overlays.push(tabstops);
156 }
157 overlays.push(Self::doc_selection_highlights(
158 editor.mode(),
159 doc,
160 view,
161 theme,
162 &config.cursor_shape,
163 self.terminal_focused,
164 ));
165 if let Some(overlay) = Self::highlight_focused_view_elements(view, doc, theme) {
166 overlays.push(overlay);
167 }
168 }
169
170 let gutter_overflow = view.gutter_offset(doc) == 0;
171 if !gutter_overflow {
172 Self::render_gutter(
173 editor,
174 doc,
175 view,
176 view.area,
177 theme,
178 is_focused & self.terminal_focused,
179 &mut decorations,
180 );
181 }
182
183 Self::render_rulers(editor, doc, view, inner, surface, theme);
184
185 let primary_cursor = doc
186 .selection(view.id)
187 .primary()
188 .cursor(doc.text().slice(..));
189 if is_focused {
190 decorations.add_decoration(text_decorations::Cursor {
191 cache: &editor.cursor_cache,
192 primary_cursor,
193 });
194 }
195 let width = view.inner_width(doc);
196 let config = doc.config.load();
197 let enable_cursor_line = view
198 .diagnostics_handler
199 .show_cursorline_diagnostics(doc, view.id);
200 let inline_diagnostic_config = config.inline_diagnostics.prepare(width, enable_cursor_line);
201 decorations.add_decoration(InlineDiagnostics::new(
202 doc,
203 theme,
204 primary_cursor,
205 inline_diagnostic_config,
206 config.end_of_line_diagnostics,
207 ));
208 render_document(
209 surface,
210 inner,
211 doc,
212 view_offset,
213 &text_annotations,
214 syntax_highlighter,
215 overlays,
216 theme,
217 decorations,
218 );
219
220 // if we're not at the edge of the screen, draw a right border
221 if viewport.right() != view.area.right() {
222 let x = area.right();
223 let border_style = theme.get("ui.window");
224 for y in area.top()..area.bottom() {
225 surface[(x, y)]
226 .set_symbol(tui::symbols::line::VERTICAL)
227 //.set_symbol(" ")
228 .set_style(border_style);
229 }
230 }
231
232 if config.inline_diagnostics.disabled()
233 && config.end_of_line_diagnostics == DiagnosticFilter::Disable
234 {
235 Self::render_diagnostics(doc, view, inner, surface, theme);
236 }
237
238 let statusline_area = view
239 .area
240 .clip_top(view.area.height.saturating_sub(1))
241 .clip_bottom(1); // -1 from bottom to remove commandline
242
243 let mut context =
244 statusline::RenderContext::new(editor, doc, view, is_focused, &self.spinners);
245
246 statusline::render(&mut context, statusline_area, surface);
247 }
248
249 pub fn render_rulers(
250 editor: &Editor,
251 doc: &Document,
252 view: &View,
253 viewport: Rect,
254 surface: &mut Surface,
255 theme: &Theme,
256 ) {
257 let editor_rulers = &editor.config().rulers;
258 let ruler_theme = theme
259 .try_get("ui.virtual.ruler")
260 .unwrap_or_else(|| Style::default().bg(Color::Red));
261
262 let rulers = doc
263 .language_config()
264 .and_then(|config| config.rulers.as_ref())
265 .unwrap_or(editor_rulers);
266
267 let view_offset = doc.view_offset(view.id);
268
269 rulers
270 .iter()
271 // View might be horizontally scrolled, convert from absolute distance
272 // from the 1st column to relative distance from left of viewport
273 .filter_map(|ruler| ruler.checked_sub(1 + view_offset.horizontal_offset as u16))
274 .filter(|ruler| ruler < &viewport.width)
275 .map(|ruler| viewport.clip_left(ruler).with_width(1))
276 .for_each(|area| surface.set_style(area, ruler_theme))
277 }
278
279 fn viewport_byte_range(
280 text: helix_core::RopeSlice,
281 row: usize,
282 height: u16,
283 ) -> std::ops::Range<usize> {
284 // Calculate viewport byte ranges:
285 // Saturating subs to make it inclusive zero indexing.
286 let last_line = text.len_lines().saturating_sub(1);
287 let last_visible_line = (row + height as usize).saturating_sub(1).min(last_line);
288 let start = text.line_to_byte(row.min(last_line));
289 let end = text.line_to_byte(last_visible_line + 1);
290
291 start..end
292 }
293
294 /// Get the syntax highlighter for a document in a view represented by the first line
295 /// and column (`offset`) and the last line. This is done instead of using a view
296 /// directly to enable rendering syntax highlighted docs anywhere (eg. picker preview)
297 pub fn doc_syntax_highlighter<'editor>(
298 doc: &'editor Document,
299 anchor: usize,
300 height: u16,
301 loader: &'editor syntax::Loader,
302 ) -> Option<syntax::Highlighter<'editor>> {
303 let syntax = doc.syntax()?;
304 let text = doc.text().slice(..);
305 let row = text.char_to_line(anchor.min(text.len_chars()));
306 let range = Self::viewport_byte_range(text, row, height);
307 let range = range.start as u32..range.end as u32;
308
309 let highlighter = syntax.highlighter(text, loader, range);
310 Some(highlighter)
311 }
312
313 pub fn overlay_syntax_highlights(
314 doc: &Document,
315 anchor: usize,
316 height: u16,
317 text_annotations: &TextAnnotations,
318 ) -> OverlayHighlights {
319 let text = doc.text().slice(..);
320 let row = text.char_to_line(anchor.min(text.len_chars()));
321
322 let mut range = Self::viewport_byte_range(text, row, height);
323 range = text.byte_to_char(range.start)..text.byte_to_char(range.end);
324
325 text_annotations.collect_overlay_highlights(range)
326 }
327
328 pub fn doc_rainbow_highlights(
329 doc: &Document,
330 anchor: usize,
331 height: u16,
332 theme: &Theme,
333 loader: &syntax::Loader,
334 ) -> Option<OverlayHighlights> {
335 let syntax = doc.syntax()?;
336 let text = doc.text().slice(..);
337 let row = text.char_to_line(anchor.min(text.len_chars()));
338 let visible_range = Self::viewport_byte_range(text, row, height);
339 let start = syntax::child_for_byte_range(
340 &syntax.tree().root_node(),
341 visible_range.start as u32..visible_range.end as u32,
342 )
343 .map_or(visible_range.start as u32, |node| node.start_byte());
344 let range = start..visible_range.end as u32;
345
346 Some(syntax.rainbow_highlights(text, theme.rainbow_length(), loader, range))
347 }
348
349 /// Get highlight spans for document diagnostics
350 pub fn doc_diagnostics_highlights_into(
351 doc: &Document,
352 theme: &Theme,
353 overlay_highlights: &mut Vec<OverlayHighlights>,
354 ) {
355 // Skip redundant work if no diagnostics.
356 if doc.diagnostics().is_empty() {
357 return;
358 }
359
360 use helix_core::diagnostic::{DiagnosticTag, Range, Severity};
361 let get_scope_of = |scope| {
362 theme
363 .find_highlight_exact(scope)
364 // get one of the themes below as fallback values
365 .or_else(|| theme.find_highlight_exact("diagnostic"))
366 .or_else(|| theme.find_highlight_exact("ui.cursor"))
367 .or_else(|| theme.find_highlight_exact("ui.selection"))
368 .expect(
369 "at least one of the following scopes must be defined in the theme: `diagnostic`, `ui.cursor`, or `ui.selection`",
370 )
371 };
372
373 // Diagnostic tags
374 let unnecessary = theme.find_highlight_exact("diagnostic.unnecessary");
375 let deprecated = theme.find_highlight_exact("diagnostic.deprecated");
376
377 let mut default_vec = Vec::new();
378 let mut info_vec = Vec::new();
379 let mut hint_vec = Vec::new();
380 let mut warning_vec = Vec::new();
381 let mut error_vec = Vec::new();
382 let mut unnecessary_vec = Vec::new();
383 let mut deprecated_vec = Vec::new();
384
385 let push_diagnostic = |vec: &mut Vec<ops::Range<usize>>, range: Range| {
386 // If any diagnostic overlaps ranges with the prior diagnostic,
387 // merge the two together. Otherwise push a new span.
388 match vec.last_mut() {
389 Some(existing_range) if range.start <= existing_range.end => {
390 // This branch merges overlapping diagnostics, assuming that the current
391 // diagnostic starts on range.start or later. If this assertion fails,
392 // we will discard some part of `diagnostic`. This implies that
393 // `doc.diagnostics()` is not sorted by `diagnostic.range`.
394 debug_assert!(existing_range.start <= range.start);
395 existing_range.end = range.end.max(existing_range.end)
396 }
397 _ => vec.push(range.start..range.end),
398 }
399 };
400
401 for diagnostic in doc.diagnostics() {
402 // Separate diagnostics into different Vecs by severity.
403 let vec = match diagnostic.severity {
404 Some(Severity::Info) => &mut info_vec,
405 Some(Severity::Hint) => &mut hint_vec,
406 Some(Severity::Warning) => &mut warning_vec,
407 Some(Severity::Error) => &mut error_vec,
408 _ => &mut default_vec,
409 };
410
411 // If the diagnostic has tags and a non-warning/error severity, skip rendering
412 // the diagnostic as info/hint/default and only render it as unnecessary/deprecated
413 // instead. For warning/error diagnostics, render both the severity highlight and
414 // the tag highlight.
415 if diagnostic.tags.is_empty()
416 || matches!(
417 diagnostic.severity,
418 Some(Severity::Warning | Severity::Error)
419 )
420 {
421 push_diagnostic(vec, diagnostic.range);
422 }
423
424 for tag in &diagnostic.tags {
425 match tag {
426 DiagnosticTag::Unnecessary => {
427 if unnecessary.is_some() {
428 push_diagnostic(&mut unnecessary_vec, diagnostic.range)
429 }
430 }
431 DiagnosticTag::Deprecated => {
432 if deprecated.is_some() {
433 push_diagnostic(&mut deprecated_vec, diagnostic.range)
434 }
435 }
436 }
437 }
438 }
439
440 overlay_highlights.push(OverlayHighlights::Homogeneous {
441 highlight: get_scope_of("diagnostic"),
442 ranges: default_vec,
443 });
444 if let Some(highlight) = unnecessary {
445 overlay_highlights.push(OverlayHighlights::Homogeneous {
446 highlight,
447 ranges: unnecessary_vec,
448 });
449 }
450 if let Some(highlight) = deprecated {
451 overlay_highlights.push(OverlayHighlights::Homogeneous {
452 highlight,
453 ranges: deprecated_vec,
454 });
455 }
456 overlay_highlights.extend([
457 OverlayHighlights::Homogeneous {
458 highlight: get_scope_of("diagnostic.info"),
459 ranges: info_vec,
460 },
461 OverlayHighlights::Homogeneous {
462 highlight: get_scope_of("diagnostic.hint"),
463 ranges: hint_vec,
464 },
465 OverlayHighlights::Homogeneous {
466 highlight: get_scope_of("diagnostic.warning"),
467 ranges: warning_vec,
468 },
469 OverlayHighlights::Homogeneous {
470 highlight: get_scope_of("diagnostic.error"),
471 ranges: error_vec,
472 },
473 ]);
474 }
475
476 pub fn doc_document_highlights(
477 doc: &Document,
478 view: &View,
479 theme: &Theme,
480 ) -> Option<OverlayHighlights> {
481 let ranges = doc.document_highlights(view.id)?;
482 if ranges.is_empty() {
483 return None;
484 }
485
486 let highlight = theme
487 .find_highlight_exact("ui.highlight")
488 .or_else(|| theme.find_highlight_exact("ui.selection"))
489 .or_else(|| theme.find_highlight_exact("ui.cursor"))?;
490
491 Some(OverlayHighlights::Homogeneous {
492 highlight,
493 ranges: ranges.to_vec(),
494 })
495 }
496
497 pub fn doc_document_link_highlights(
498 doc: &Document,
499 theme: &Theme,
500 ) -> Option<OverlayHighlights> {
501 let highlight = theme
502 .find_highlight_exact("markup.link.url")
503 .or_else(|| theme.find_highlight_exact("markup.link"))?;
504
505 if doc.document_links.is_empty() {
506 return None;
507 }
508
509 let mut ranges: Vec<ops::Range<usize>> = Vec::new();
510 for link in &doc.document_links {
511 if link.start >= link.end {
512 continue;
513 }
514
515 match ranges.last_mut() {
516 Some(existing_range) if link.start <= existing_range.end => {
517 existing_range.end = existing_range.end.max(link.end);
518 }
519 _ => ranges.push(link.start..link.end),
520 }
521 }
522
523 if ranges.is_empty() {
524 return None;
525 }
526
527 Some(OverlayHighlights::Homogeneous { highlight, ranges })
528 }
529
530 /// Get highlight spans for selections in a document view.
531 pub fn doc_selection_highlights(
532 mode: Mode,
533 doc: &Document,
534 view: &View,
535 theme: &Theme,
536 cursor_shape_config: &CursorShapeConfig,
537 is_terminal_focused: bool,
538 ) -> OverlayHighlights {
539 let text = doc.text().slice(..);
540 let selection = doc.selection(view.id);
541 let primary_idx = selection.primary_index();
542
543 let cursorkind = cursor_shape_config.from_mode(mode);
544 let cursor_is_block = cursorkind == CursorKind::Block;
545
546 let selection_scope = theme
547 .find_highlight_exact("ui.selection")
548 .expect("could not find `ui.selection` scope in the theme!");
549 let primary_selection_scope = theme
550 .find_highlight_exact("ui.selection.primary")
551 .unwrap_or(selection_scope);
552
553 let base_cursor_scope = theme
554 .find_highlight_exact("ui.cursor")
555 .unwrap_or(selection_scope);
556 let base_primary_cursor_scope = theme
557 .find_highlight("ui.cursor.primary")
558 .unwrap_or(base_cursor_scope);
559
560 let cursor_scope = match mode {
561 Mode::Insert => theme.find_highlight_exact("ui.cursor.insert"),
562 Mode::Select => theme.find_highlight_exact("ui.cursor.select"),
563 Mode::Normal => theme.find_highlight_exact("ui.cursor.normal"),
564 }
565 .unwrap_or(base_cursor_scope);
566
567 let primary_cursor_scope = match mode {
568 Mode::Insert => theme.find_highlight_exact("ui.cursor.primary.insert"),
569 Mode::Select => theme.find_highlight_exact("ui.cursor.primary.select"),
570 Mode::Normal => theme.find_highlight_exact("ui.cursor.primary.normal"),
571 }
572 .unwrap_or(base_primary_cursor_scope);
573
574 let mut spans = Vec::new();
575 for (i, range) in selection.iter().enumerate() {
576 let selection_is_primary = i == primary_idx;
577 let (cursor_scope, selection_scope) = if selection_is_primary {
578 (primary_cursor_scope, primary_selection_scope)
579 } else {
580 (cursor_scope, selection_scope)
581 };
582
583 // Special-case: cursor at end of the rope.
584 if range.head == range.anchor && range.head == text.len_chars() {
585 if !selection_is_primary || (cursor_is_block && is_terminal_focused) {
586 // Bar and underline cursors are drawn by the terminal
587 // BUG: If the editor area loses focus while having a bar or
588 // underline cursor (eg. when a regex prompt has focus) then
589 // the primary cursor will be invisible. This doesn't happen
590 // with block cursors since we manually draw *all* cursors.
591 spans.push((cursor_scope, range.head..range.head + 1));
592 }
593 continue;
594 }
595
596 let range = range.min_width_1(text);
597 if range.head > range.anchor {
598 // Standard case.
599 let cursor_start = prev_grapheme_boundary(text, range.head);
600 // non block cursors look like they exclude the cursor
601 let selection_end =
602 if selection_is_primary && !cursor_is_block && mode != Mode::Insert {
603 range.head
604 } else {
605 cursor_start
606 };
607 spans.push((selection_scope, range.anchor..selection_end));
608 // add block cursors
609 // skip primary cursor if terminal is unfocused - terminal cursor is used in that case
610 if !selection_is_primary || (cursor_is_block && is_terminal_focused) {
611 spans.push((cursor_scope, cursor_start..range.head));
612 }
613 } else {
614 // Reverse case.
615 let cursor_end = next_grapheme_boundary(text, range.head);
616 // add block cursors
617 // skip primary cursor if terminal is unfocused - terminal cursor is used in that case
618 if !selection_is_primary || (cursor_is_block && is_terminal_focused) {
619 spans.push((cursor_scope, range.head..cursor_end));
620 }
621 // non block cursors look like they exclude the cursor
622 let selection_start = if selection_is_primary
623 && !cursor_is_block
624 && !(mode == Mode::Insert && cursor_end == range.anchor)
625 {
626 range.head
627 } else {
628 cursor_end
629 };
630 spans.push((selection_scope, selection_start..range.anchor));
631 }
632 }
633
634 OverlayHighlights::Heterogenous { highlights: spans }
635 }
636
637 /// Render brace match, etc (meant for the focused view only)
638 pub fn highlight_focused_view_elements(
639 view: &View,
640 doc: &Document,
641 theme: &Theme,
642 ) -> Option<OverlayHighlights> {
643 // Highlight matching braces
644 let syntax = doc.syntax()?;
645 let highlight = theme.find_highlight_exact("ui.cursor.match")?;
646 let text = doc.text().slice(..);
647 let pos = doc.selection(view.id).primary().cursor(text);
648 let pos = helix_core::match_brackets::find_matching_bracket(syntax, text, pos)?;
649 Some(OverlayHighlights::single(highlight, pos..pos + 1))
650 }
651
652 pub fn tabstop_highlights(doc: &Document, theme: &Theme) -> Option<OverlayHighlights> {
653 let snippet = doc.active_snippet.as_ref()?;
654 let highlight = theme.find_highlight_exact("tabstop")?;
655 let mut ranges = Vec::new();
656 for tabstop in snippet.tabstops() {
657 ranges.extend(tabstop.ranges.iter().map(|range| range.start..range.end));
658 }
659 Some(OverlayHighlights::Homogeneous { highlight, ranges })
660 }
661
662 /// Render bufferline at the top
663 pub fn render_bufferline(editor: &Editor, viewport: Rect, surface: &mut Surface) {
664 let scratch = PathBuf::from(SCRATCH_BUFFER_NAME); // default filename to use for scratch buffer
665 surface.clear_with(
666 viewport,
667 editor
668 .theme
669 .try_get("ui.bufferline.background")
670 .unwrap_or_else(|| editor.theme.get("ui.statusline")),
671 );
672
673 let bufferline_active = editor
674 .theme
675 .try_get("ui.bufferline.active")
676 .unwrap_or_else(|| editor.theme.get("ui.statusline.active"));
677
678 let bufferline_inactive = editor
679 .theme
680 .try_get("ui.bufferline")
681 .unwrap_or_else(|| editor.theme.get("ui.statusline.inactive"));
682
683 let mut x = viewport.x;
684 let current_doc = view!(editor).doc;
685
686 for doc in editor.documents() {
687 let fname = doc
688 .path()
689 .unwrap_or(&scratch)
690 .file_name()
691 .unwrap_or_default()
692 .to_str()
693 .unwrap_or_default();
694
695 let style = if current_doc == doc.id() {
696 bufferline_active
697 } else {
698 bufferline_inactive
699 };
700
701 let text = format!(" {}{} ", fname, if doc.is_modified() { "[+]" } else { "" });
702 let used_width = viewport.x.saturating_sub(x);
703 let rem_width = surface.area.width.saturating_sub(used_width);
704
705 x = surface
706 .set_stringn(x, viewport.y, &text, rem_width as usize, style)
707 .0;
708
709 if x >= surface.area.right() {
710 break;
711 }
712 }
713 }
714
715 pub fn render_gutter<'d>(
716 editor: &'d Editor,
717 doc: &'d Document,
718 view: &View,
719 viewport: Rect,
720 theme: &Theme,
721 is_focused: bool,
722 decoration_manager: &mut DecorationManager<'d>,
723 ) {
724 let text = doc.text().slice(..);
725 let cursors: Rc<[_]> = doc
726 .selection(view.id)
727 .iter()
728 .map(|range| range.cursor_line(text))
729 .collect();
730
731 let mut offset = 0;
732
733 let gutter_style = theme.get("ui.gutter");
734 let gutter_selected_style = theme.get("ui.gutter.selected");
735 let gutter_style_virtual = theme.get("ui.gutter.virtual");
736 let gutter_selected_style_virtual = theme.get("ui.gutter.selected.virtual");
737
738 for gutter_type in view.gutters() {
739 let mut gutter = gutter_type.style(editor, doc, view, theme, is_focused);
740 let width = gutter_type.width(view, doc);
741 // avoid lots of small allocations by reusing a text buffer for each line
742 let mut text = String::with_capacity(width);
743 let cursors = cursors.clone();
744 let gutter_decoration = move |renderer: &mut TextRenderer, pos: LinePos| {
745 // TODO handle softwrap in gutters
746 let selected = cursors.contains(&pos.doc_line);
747 let x = viewport.x + offset;
748 let y = pos.visual_line;
749
750 let gutter_style = match (selected, pos.first_visual_line) {
751 (false, true) => gutter_style,
752 (true, true) => gutter_selected_style,
753 (false, false) => gutter_style_virtual,
754 (true, false) => gutter_selected_style_virtual,
755 };
756
757 if let Some(style) =
758 gutter(pos.doc_line, selected, pos.first_visual_line, &mut text)
759 {
760 renderer.set_stringn(x, y, &text, width, gutter_style.patch(style));
761 } else {
762 renderer.set_style(
763 Rect {
764 x,
765 y,
766 width: width as u16,
767 height: 1,
768 },
769 gutter_style,
770 );
771 }
772 text.clear();
773 };
774 decoration_manager.add_decoration(gutter_decoration);
775
776 offset += width as u16;
777 }
778 }
779
780 pub fn render_diagnostics(
781 doc: &Document,
782 view: &View,
783 viewport: Rect,
784 surface: &mut Surface,
785 theme: &Theme,
786 ) {
787 use helix_core::diagnostic::Severity;
788 use tui::{
789 layout::Alignment,
790 text::Text,
791 widgets::{Paragraph, Widget, Wrap},
792 };
793
794 let cursor = doc
795 .selection(view.id)
796 .primary()
797 .cursor(doc.text().slice(..));
798
799 let diagnostics = doc.diagnostics().iter().filter(|diagnostic| {
800 diagnostic.range.start <= cursor && diagnostic.range.end >= cursor
801 });
802
803 let warning = theme.get("warning");
804 let error = theme.get("error");
805 let info = theme.get("info");
806 let hint = theme.get("hint");
807
808 let mut lines = Vec::new();
809 let background_style = theme.get("ui.background");
810 for diagnostic in diagnostics {
811 let style = Style::reset()
812 .patch(background_style)
813 .patch(match diagnostic.severity {
814 Some(Severity::Error) => error,
815 Some(Severity::Warning) | None => warning,
816 Some(Severity::Info) => info,
817 Some(Severity::Hint) => hint,
818 });
819 let text = Text::styled(&diagnostic.message, style);
820 lines.extend(text.lines);
821 let code = diagnostic.code.as_ref().map(|x| match x {
822 NumberOrString::Number(n) => format!("({n})"),
823 NumberOrString::String(s) => format!("({s})"),
824 });
825 if let Some(code) = code {
826 let span = Span::styled(code, style);
827 lines.push(span.into());
828 }
829 }
830
831 let text = Text::from(lines);
832 let paragraph = Paragraph::new(&text)
833 .alignment(Alignment::Right)
834 .wrap(Wrap { trim: true });
835 let width = 100.min(viewport.width);
836 let height = 15.min(viewport.height);
837 paragraph.render(
838 Rect::new(viewport.right() - width, viewport.y + 1, width, height),
839 surface,
840 );
841 }
842
843 /// Apply the highlighting on the lines where a cursor is active
844 pub fn cursorline(doc: &Document, view: &View, theme: &Theme) -> impl Decoration {
845 let text = doc.text().slice(..);
846 // TODO only highlight the visual line that contains the cursor instead of the full visual line
847 let primary_line = doc.selection(view.id).primary().cursor_line(text);
848
849 // The secondary_lines do contain the primary_line, it doesn't matter
850 // as the else-if clause in the loop later won't test for the
851 // secondary_lines if primary_line == line.
852 // It's used inside a loop so the collect isn't needless:
853 // https://github.com/rust-lang/rust-clippy/issues/6164
854 #[allow(clippy::needless_collect)]
855 let secondary_lines: Vec<_> = doc
856 .selection(view.id)
857 .iter()
858 .map(|range| range.cursor_line(text))
859 .collect();
860
861 let primary_style = theme.get("ui.cursorline.primary");
862 let secondary_style = theme.get("ui.cursorline.secondary");
863 let viewport = view.area;
864
865 move |renderer: &mut TextRenderer, pos: LinePos| {
866 let area = Rect::new(viewport.x, pos.visual_line, viewport.width, 1);
867 if primary_line == pos.doc_line {
868 renderer.set_style(area, primary_style);
869 } else if secondary_lines.binary_search(&pos.doc_line).is_ok() {
870 renderer.set_style(area, secondary_style);
871 }
872 }
873 }
874
875 /// Apply the highlighting on the columns where a cursor is active
876 pub fn highlight_cursorcolumn(
877 doc: &Document,
878 view: &View,
879 surface: &mut Surface,
880 theme: &Theme,
881 viewport: Rect,
882 text_annotations: &TextAnnotations,
883 ) {
884 let text = doc.text().slice(..);
885
886 // Manual fallback behaviour:
887 // ui.cursorcolumn.{p/s} -> ui.cursorcolumn -> ui.cursorline.{p/s}
888 let primary_style = theme
889 .try_get_exact("ui.cursorcolumn.primary")
890 .or_else(|| theme.try_get_exact("ui.cursorcolumn"))
891 .unwrap_or_else(|| theme.get("ui.cursorline.primary"));
892 let secondary_style = theme
893 .try_get_exact("ui.cursorcolumn.secondary")
894 .or_else(|| theme.try_get_exact("ui.cursorcolumn"))
895 .unwrap_or_else(|| theme.get("ui.cursorline.secondary"));
896
897 let inner_area = view.inner_area(doc);
898
899 let selection = doc.selection(view.id);
900 let view_offset = doc.view_offset(view.id);
901 let primary = selection.primary();
902 let text_format = doc.text_format(viewport.width, None);
903 for range in selection.iter() {
904 let is_primary = primary == *range;
905 let cursor = range.cursor(text);
906
907 let Position { col, .. } =
908 visual_offset_from_block(text, cursor, cursor, &text_format, text_annotations).0;
909
910 // if the cursor is horizontally in the view
911 if col >= view_offset.horizontal_offset
912 && inner_area.width > (col - view_offset.horizontal_offset) as u16
913 {
914 let area = Rect::new(
915 inner_area.x + (col - view_offset.horizontal_offset) as u16,
916 view.area.y,
917 1,
918 view.area.height,
919 );
920 if is_primary {
921 surface.set_style(area, primary_style)
922 } else {
923 surface.set_style(area, secondary_style)
924 }
925 }
926 }
927 }
928
929 /// Handle events by looking them up in `self.keymaps`. Returns None
930 /// if event was handled (a command was executed or a subkeymap was
931 /// activated). Only KeymapResult::{NotFound, Cancelled} is returned
932 /// otherwise.
933 fn handle_keymap_event(
934 &mut self,
935 mode: Mode,
936 cxt: &mut commands::Context,
937 event: KeyEvent,
938 ) -> Option<KeymapResult> {
939 let mut last_mode = mode;
940 self.pseudo_pending.extend(self.keymaps.pending());
941 let key_result = self.keymaps.get(mode, event);
942 cxt.editor.autoinfo = self.keymaps.sticky().map(|node| node.infobox());
943
944 let mut execute_command = |command: &commands::MappableCommand| {
945 command.execute(cxt);
946 helix_event::dispatch(PostCommand { command, cx: cxt });
947
948 let current_mode = cxt.editor.mode();
949 if current_mode != last_mode {
950 helix_event::dispatch(OnModeSwitch {
951 old_mode: last_mode,
952 new_mode: current_mode,
953 cx: cxt,
954 });
955
956 // HAXX: if we just entered insert mode from normal, clear key buf
957 // and record the command that got us into this mode.
958 if current_mode == Mode::Insert {
959 // how we entered insert mode is important, and we should track that so
960 // we can repeat the side effect.
961 self.last_insert.0 = command.clone();
962 self.last_insert.1.clear();
963 }
964 }
965
966 last_mode = current_mode;
967 };
968
969 match &key_result {
970 KeymapResult::Matched(command) => {
971 execute_command(command);
972 }
973 KeymapResult::Pending(node) => cxt.editor.autoinfo = Some(node.infobox()),
974 KeymapResult::MatchedSequence(commands) => {
975 for command in commands {
976 execute_command(command);
977 }
978 }
979 KeymapResult::NotFound | KeymapResult::Cancelled(_) => return Some(key_result),
980 }
981 None
982 }
983
984 fn insert_mode(&mut self, cx: &mut commands::Context, event: KeyEvent) {
985 if let Some(keyresult) = self.handle_keymap_event(Mode::Insert, cx, event) {
986 match keyresult {
987 KeymapResult::NotFound => {
988 if !self.on_next_key(OnKeyCallbackKind::Fallback, cx, event) {
989 if let Some(ch) = event.char() {
990 commands::insert::insert_char(cx, ch)
991 }
992 }
993 }
994 KeymapResult::Cancelled(pending) => {
995 for ev in pending {
996 match ev.char() {
997 Some(ch) => commands::insert::insert_char(cx, ch),
998 None => {
999 if let KeymapResult::Matched(command) =
1000 self.keymaps.get(Mode::Insert, ev)
1001 {
1002 command.execute(cx);
1003 }
1004 }
1005 }
1006 }
1007 }
1008 _ => unreachable!(),
1009 }
1010 }
1011 }
1012
1013 fn command_mode(&mut self, mode: Mode, cxt: &mut commands::Context, event: KeyEvent) {
1014 match (event, cxt.editor.count) {
1015 // If the count is already started and the input is a number, always continue the count.
1016 (key!(i @ '0'..='9'), Some(count)) => {
1017 let i = i.to_digit(10).unwrap() as usize;
1018 let count = count.get() * 10 + i;
1019 if count > 100_000_000 {
1020 return;
1021 }
1022 cxt.editor.count = NonZeroUsize::new(count);
1023 }
1024 // A non-zero digit will start the count if that number isn't used by a keymap.
1025 (key!(i @ '1'..='9'), None) if !self.keymaps.contains_key(mode, event) => {
1026 let i = i.to_digit(10).unwrap() as usize;
1027 cxt.editor.count = NonZeroUsize::new(i);
1028 }
1029 // special handling for repeat operator
1030 (key!('.'), _) if self.keymaps.pending().is_empty() => {
1031 for _ in 0..cxt.editor.count.map_or(1, NonZeroUsize::into) {
1032 // first execute whatever put us into insert mode
1033 self.last_insert.0.execute(cxt);
1034 let mut last_savepoint = None;
1035 let mut last_request_savepoint = None;
1036 // then replay the inputs
1037 for key in self.last_insert.1.clone() {
1038 match key {
1039 InsertEvent::Key(key) => self.insert_mode(cxt, key),
1040 InsertEvent::CompletionApply {
1041 trigger_offset,
1042 changes,
1043 } => {
1044 let (view, doc) = current!(cxt.editor);
1045
1046 if let Some(last_savepoint) = last_savepoint.as_deref() {
1047 doc.restore(view, last_savepoint, true);
1048 }
1049
1050 let text = doc.text().slice(..);
1051 let cursor = doc.selection(view.id).primary().cursor(text);
1052
1053 let shift_position = |pos: usize| -> usize {
1054 (pos + cursor).saturating_sub(trigger_offset)
1055 };
1056
1057 let tx = Transaction::change(
1058 doc.text(),
1059 changes.iter().cloned().map(|(start, end, t)| {
1060 (shift_position(start), shift_position(end), t)
1061 }),
1062 );
1063 doc.apply(&tx, view.id);
1064 }
1065 InsertEvent::TriggerCompletion => {
1066 last_savepoint = take(&mut last_request_savepoint);
1067 }
1068 InsertEvent::RequestCompletion => {
1069 let (view, doc) = current!(cxt.editor);
1070 last_request_savepoint = Some(doc.savepoint(view));
1071 }
1072 }
1073 }
1074 }
1075 cxt.editor.count = None;
1076 }
1077 _ => {
1078 // set the count
1079 cxt.count = cxt.editor.count;
1080 // TODO: edge case: 0j -> reset to 1
1081 // if this fails, count was Some(0)
1082 // debug_assert!(cxt.count != 0);
1083
1084 // set the register
1085 cxt.register = cxt.editor.selected_register.take();
1086
1087 let res = self.handle_keymap_event(mode, cxt, event);
1088 if matches!(&res, Some(KeymapResult::NotFound)) {
1089 self.on_next_key(OnKeyCallbackKind::Fallback, cxt, event);
1090 }
1091 if self.keymaps.pending().is_empty() {
1092 cxt.editor.count = None
1093 } else {
1094 cxt.editor.selected_register = cxt.register.take();
1095 }
1096 }
1097 }
1098 }
1099
1100 #[allow(clippy::too_many_arguments)]
1101 pub fn set_completion(
1102 &mut self,
1103 editor: &mut Editor,
1104 items: Vec<CompletionItem>,
1105 trigger_offset: usize,
1106 size: Rect,
1107 ) -> Option<Rect> {
1108 let mut completion = Completion::new(editor, items, trigger_offset);
1109
1110 if completion.is_empty() {
1111 // skip if we got no completion results
1112 return None;
1113 }
1114
1115 let area = completion.area(size, editor);
1116 editor.last_completion = Some(CompleteAction::Triggered);
1117 self.last_insert.1.push(InsertEvent::TriggerCompletion);
1118
1119 // TODO : propagate required size on resize to completion too
1120 self.completion = Some(completion);
1121 Some(area)
1122 }
1123
1124 pub fn clear_completion(&mut self, editor: &mut Editor) -> Option<OnKeyCallback> {
1125 self.completion = None;
1126 let mut on_next_key: Option<OnKeyCallback> = None;
1127 editor.handlers.completions.request_controller.restart();
1128 editor.handlers.completions.active_completions.clear();
1129 if let Some(last_completion) = editor.last_completion.take() {
1130 match last_completion {
1131 CompleteAction::Triggered => (),
1132 CompleteAction::Applied {
1133 trigger_offset,
1134 changes,
1135 placeholder,
1136 } => {
1137 self.last_insert.1.push(InsertEvent::CompletionApply {
1138 trigger_offset,
1139 changes,
1140 });
1141 on_next_key = placeholder.then_some(Box::new(|cx, key| {
1142 if let Some(c) = key.char() {
1143 let (view, doc) = current!(cx.editor);
1144 if let Some(snippet) = &doc.active_snippet {
1145 doc.apply(&snippet.delete_placeholder(doc.text()), view.id);
1146 }
1147 commands::insert::insert_char(cx, c);
1148 }
1149 }))
1150 }
1151 CompleteAction::Selected { savepoint } => {
1152 let (view, doc) = current!(editor);
1153 doc.restore(view, &savepoint, false);
1154 }
1155 }
1156 }
1157 on_next_key
1158 }
1159
1160 pub fn handle_idle_timeout(&mut self, cx: &mut commands::Context) -> EventResult {
1161 commands::compute_inlay_hints_for_all_views(cx.editor, cx.jobs);
1162
1163 EventResult::Ignored(None)
1164 }
1165 }
1166
1167 /// Whether the focused doc's workspace is in restricted mode and running `trust` would
1168 /// change something visible at the workspace level.
1169 fn workspace_trust_indicator_visible(editor: &Editor) -> bool {
1170 if editor.workspace_trust.implicit_level()
1171 == helix_loader::workspace_trust::ImplicitTrustLevel::Insecure
1172 {
1173 return false;
1174 }
1175 let (_, doc) = helix_view::current_ref!(editor);
1176 editor
1177 .workspace_trust
1178 .workspace_restricted(doc.workspace_root())
1179 }
1180
1181 impl EditorView {
1182 /// must be called whenever the editor processed input that
1183 /// is not a `KeyEvent`. In these cases any pending keys/on next
1184 /// key callbacks must be canceled.
1185 fn handle_non_key_input(&mut self, cxt: &mut commands::Context) {
1186 cxt.editor.status_msg = None;
1187 cxt.editor.reset_idle_timer();
1188 // HACKS: create a fake key event that will never trigger any actual map
1189 // and therefore simply acts as "dismiss"
1190 let null_key_event = KeyEvent {
1191 code: KeyCode::Null,
1192 modifiers: KeyModifiers::empty(),
1193 };
1194 // dismiss any pending keys
1195 if let Some((on_next_key, _)) = self.on_next_key.take() {
1196 on_next_key(cxt, null_key_event);
1197 }
1198 self.handle_keymap_event(cxt.editor.mode, cxt, null_key_event);
1199 self.pseudo_pending.clear();
1200 }
1201
1202 fn handle_mouse_event(
1203 &mut self,
1204 event: &MouseEvent,
1205 cxt: &mut commands::Context,
1206 ) -> EventResult {
1207 if event.kind != MouseEventKind::Moved {
1208 self.handle_non_key_input(cxt)
1209 }
1210
1211 let config = cxt.editor.config();
1212 let MouseEvent {
1213 kind,
1214 row,
1215 column,
1216 modifiers,
1217 ..
1218 } = *event;
1219
1220 let pos_and_view = |editor: &Editor, row, column, ignore_virtual_text| {
1221 editor.tree.views().find_map(|(view, _focus)| {
1222 view.pos_at_screen_coords(
1223 &editor.documents[&view.doc],
1224 row,
1225 column,
1226 ignore_virtual_text,
1227 )
1228 .map(|pos| (pos, view.id))
1229 })
1230 };
1231
1232 let gutter_coords_and_view = |editor: &Editor, row, column| {
1233 editor.tree.views().find_map(|(view, _focus)| {
1234 view.gutter_coords_at_screen_coords(row, column)
1235 .map(|coords| (coords, view.id))
1236 })
1237 };
1238
1239 match kind {
1240 MouseEventKind::Down(MouseButton::Left) => {
1241 let editor = &mut cxt.editor;
1242
1243 if let Some((pos, view_id)) = pos_and_view(editor, row, column, true) {
1244 editor.focus(view_id);
1245
1246 let prev_view_id = view!(editor).id;
1247 let doc = doc_mut!(editor, &view!(editor, view_id).doc);
1248
1249 if modifiers == KeyModifiers::ALT {
1250 let selection = doc.selection(view_id).clone();
1251 doc.set_selection(view_id, selection.push(Range::point(pos)));
1252 } else if editor.mode == Mode::Select {
1253 // Discards non-primary selections for consistent UX with normal mode
1254 let primary = doc.selection(view_id).primary().put_cursor(
1255 doc.text().slice(..),
1256 pos,
1257 true,
1258 );
1259 editor.mouse_down_range = Some(primary);
1260 doc.set_selection(view_id, Selection::single(primary.anchor, primary.head));
1261 } else {
1262 doc.set_selection(view_id, Selection::point(pos));
1263 }
1264
1265 if view_id != prev_view_id {
1266 self.clear_completion(editor);
1267 }
1268
1269 editor.ensure_cursor_in_view(view_id);
1270
1271 return EventResult::Consumed(None);
1272 }
1273
1274 if let Some((coords, view_id)) = gutter_coords_and_view(editor, row, column) {
1275 editor.focus(view_id);
1276
1277 let (view, doc) = current!(cxt.editor);
1278
1279 let Some(path) = doc.path().map(ToOwned::to_owned) else {
1280 return EventResult::Ignored(None);
1281 };
1282
1283 if let Some(char_idx) =
1284 view.pos_at_visual_coords(doc, coords.row as u16, coords.col as u16, true)
1285 {
1286 let line = doc.text().char_to_line(char_idx);
1287 commands::dap_toggle_breakpoint_impl(cxt, path, line);
1288 return EventResult::Consumed(None);
1289 }
1290 }
1291
1292 EventResult::Ignored(None)
1293 }
1294
1295 MouseEventKind::Drag(MouseButton::Left) => {
1296 let (view, doc) = current!(cxt.editor);
1297
1298 let pos = match view.pos_at_screen_coords(doc, row, column, true) {
1299 Some(pos) => pos,
1300 None => return EventResult::Ignored(None),
1301 };
1302
1303 let mut selection = doc.selection(view.id).clone();
1304 let primary = selection.primary_mut();
1305 *primary = primary.put_cursor(doc.text().slice(..), pos, true);
1306 doc.set_selection(view.id, selection);
1307 let view_id = view.id;
1308 cxt.editor.ensure_cursor_in_view(view_id);
1309 EventResult::Consumed(None)
1310 }
1311
1312 MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => {
1313 let current_view = cxt.editor.tree.focus;
1314
1315 let direction = match event.kind {
1316 MouseEventKind::ScrollUp => Direction::Backward,
1317 MouseEventKind::ScrollDown => Direction::Forward,
1318 _ => unreachable!(),
1319 };
1320
1321 match pos_and_view(cxt.editor, row, column, false) {
1322 Some((_, view_id)) => cxt.editor.tree.focus = view_id,
1323 None => return EventResult::Ignored(None),
1324 }
1325
1326 let offset = config.scroll_lines.unsigned_abs();
1327 commands::scroll(cxt, offset, direction, false);
1328
1329 cxt.editor.tree.focus = current_view;
1330 cxt.editor.ensure_cursor_in_view(current_view);
1331
1332 EventResult::Consumed(None)
1333 }
1334
1335 MouseEventKind::Up(MouseButton::Left) => {
1336 if !config.middle_click_paste {
1337 return EventResult::Ignored(None);
1338 }
1339
1340 let (view, doc) = current!(cxt.editor);
1341
1342 let should_yank = match cxt.editor.mouse_down_range.take() {
1343 Some(down_range) => doc.selection(view.id).primary() != down_range,
1344 None => {
1345 // This should not happen under normal cases. We fall back to the original
1346 // behavior of yanking on non-single-char selections.
1347 doc.selection(view.id)
1348 .primary()
1349 .slice(doc.text().slice(..))
1350 .len_chars()
1351 > 1
1352 }
1353 };
1354
1355 if should_yank {
1356 commands::yank_main_selection_to_register(
1357 cxt.editor,
1358 config.mouse_yank_register,
1359 );
1360 EventResult::Consumed(None)
1361 } else {
1362 EventResult::Ignored(None)
1363 }
1364 }
1365
1366 MouseEventKind::Up(MouseButton::Right) => {
1367 if let Some((pos, view_id)) = gutter_coords_and_view(cxt.editor, row, column) {
1368 cxt.editor.focus(view_id);
1369
1370 if let Some((pos, _)) = pos_and_view(cxt.editor, row, column, true) {
1371 doc_mut!(cxt.editor).set_selection(view_id, Selection::point(pos));
1372 } else {
1373 let (view, doc) = current!(cxt.editor);
1374
1375 if let Some(pos) = view.pos_at_visual_coords(doc, pos.row as u16, 0, true) {
1376 doc.set_selection(view_id, Selection::point(pos));
1377 match modifiers {
1378 KeyModifiers::ALT => {
1379 commands::MappableCommand::dap_edit_log.execute(cxt)
1380 }
1381 _ => commands::MappableCommand::dap_edit_condition.execute(cxt),
1382 };
1383 }
1384 }
1385
1386 cxt.editor.ensure_cursor_in_view(view_id);
1387 return EventResult::Consumed(None);
1388 }
1389 EventResult::Ignored(None)
1390 }
1391
1392 MouseEventKind::Up(MouseButton::Middle) => {
1393 let editor = &mut cxt.editor;
1394 if !config.middle_click_paste {
1395 return EventResult::Ignored(None);
1396 }
1397
1398 if modifiers == KeyModifiers::ALT {
1399 commands::replace_selections_with_register(
1400 cxt.editor,
1401 config.mouse_yank_register,
1402 cxt.count(),
1403 );
1404
1405 return EventResult::Consumed(None);
1406 }
1407
1408 if let Some((pos, view_id)) = pos_and_view(editor, row, column, true) {
1409 let doc = doc_mut!(editor, &view!(editor, view_id).doc);
1410 doc.set_selection(view_id, Selection::point(pos));
1411 cxt.editor.focus(view_id);
1412
1413 commands::paste(
1414 cxt.editor,
1415 config.mouse_yank_register,
1416 commands::Paste::Before,
1417 cxt.count(),
1418 );
1419
1420 return EventResult::Consumed(None);
1421 }
1422
1423 EventResult::Ignored(None)
1424 }
1425
1426 _ => EventResult::Ignored(None),
1427 }
1428 }
1429 fn on_next_key(
1430 &mut self,
1431 kind: OnKeyCallbackKind,
1432 ctx: &mut commands::Context,
1433 event: KeyEvent,
1434 ) -> bool {
1435 if let Some((on_next_key, kind_)) = self.on_next_key.take() {
1436 if kind == kind_ {
1437 on_next_key(ctx, event);
1438 true
1439 } else {
1440 self.on_next_key = Some((on_next_key, kind_));
1441 false
1442 }
1443 } else {
1444 false
1445 }
1446 }
1447 }
1448
1449 impl Component for EditorView {
1450 fn handle_event(
1451 &mut self,
1452 event: &Event,
1453 context: &mut crate::compositor::Context,
1454 ) -> EventResult {
1455 let mut cx = commands::Context {
1456 editor: context.editor,
1457 count: None,
1458 register: None,
1459 callback: Vec::new(),
1460 on_next_key_callback: None,
1461 jobs: context.jobs,
1462 };
1463
1464 match event {
1465 Event::Paste(contents) => {
1466 self.handle_non_key_input(&mut cx);
1467 cx.count = cx.editor.count;
1468 commands::paste_bracketed_value(&mut cx, contents.clone());
1469 cx.editor.count = None;
1470
1471 let config = cx.editor.config();
1472 let mode = cx.editor.mode();
1473 let (view, doc) = current!(cx.editor);
1474 view.ensure_cursor_in_view(doc, config.scrolloff);
1475
1476 // Store a history state if not in insert mode. Otherwise wait till we exit insert
1477 // to include any edits to the paste in the history state.
1478 if mode != Mode::Insert {
1479 doc.append_changes_to_history(view);
1480 }
1481
1482 EventResult::Consumed(None)
1483 }
1484 Event::Resize(_width, _height) => {
1485 // Ignore this event, we handle resizing just before rendering to screen.
1486 // Handling it here but not re-rendering will cause flashing
1487 EventResult::Consumed(None)
1488 }
1489 Event::Key(mut key) => {
1490 cx.editor.reset_idle_timer();
1491 canonicalize_key(&mut key);
1492
1493 // clear status
1494 cx.editor.status_msg = None;
1495
1496 let mode = cx.editor.mode();
1497
1498 if !self.on_next_key(OnKeyCallbackKind::PseudoPending, &mut cx, key) {
1499 match mode {
1500 Mode::Insert => {
1501 // let completion swallow the event if necessary
1502 let mut consumed = false;
1503 if let Some(completion) = &mut self.completion {
1504 let res = {
1505 // use a fake context here
1506 let mut cx = Context {
1507 editor: cx.editor,
1508 jobs: cx.jobs,
1509 scroll: None,
1510 };
1511
1512 if let EventResult::Consumed(callback) =
1513 completion.handle_event(event, &mut cx)
1514 {
1515 consumed = true;
1516 Some(callback)
1517 } else if let EventResult::Consumed(callback) =
1518 completion.handle_event(&Event::Key(key!(Enter)), &mut cx)
1519 {
1520 Some(callback)
1521 } else {
1522 None
1523 }
1524 };
1525
1526 if let Some(callback) = res {
1527 if callback.is_some() {
1528 // assume close_fn
1529 if let Some(cb) = self.clear_completion(cx.editor) {
1530 if consumed {
1531 cx.on_next_key_callback =
1532 Some((cb, OnKeyCallbackKind::Fallback))
1533 } else {
1534 self.on_next_key =
1535 Some((cb, OnKeyCallbackKind::Fallback));
1536 }
1537 }
1538 }
1539 }
1540 }
1541
1542 // if completion didn't take the event, we pass it onto commands
1543 if !consumed {
1544 self.insert_mode(&mut cx, key);
1545
1546 // record last_insert key
1547 self.last_insert.1.push(InsertEvent::Key(key));
1548 }
1549 }
1550 mode => self.command_mode(mode, &mut cx, key),
1551 }
1552 }
1553
1554 self.on_next_key = cx.on_next_key_callback.take();
1555 match self.on_next_key {
1556 Some((_, OnKeyCallbackKind::PseudoPending)) => self.pseudo_pending.push(key),
1557 _ => self.pseudo_pending.clear(),
1558 }
1559
1560 // appease borrowck
1561 let callbacks = take(&mut cx.callback);
1562
1563 // if the command consumed the last view, skip the render.
1564 // on the next loop cycle the Application will then terminate.
1565 if cx.editor.should_close() {
1566 return EventResult::Ignored(None);
1567 }
1568
1569 let config = cx.editor.config();
1570 let mode = cx.editor.mode();
1571 let (view, doc) = current!(cx.editor);
1572
1573 view.ensure_cursor_in_view(doc, config.scrolloff);
1574
1575 // Store a history state if not in insert mode. This also takes care of
1576 // committing changes when leaving insert mode.
1577 if mode != Mode::Insert {
1578 doc.append_changes_to_history(view);
1579 }
1580 let callback = if callbacks.is_empty() {
1581 None
1582 } else {
1583 let callback: crate::compositor::Callback = Box::new(move |compositor, cx| {
1584 for callback in callbacks {
1585 callback(compositor, cx)
1586 }
1587 });
1588 Some(callback)
1589 };
1590
1591 EventResult::Consumed(callback)
1592 }
1593
1594 Event::Mouse(event) => self.handle_mouse_event(event, &mut cx),
1595 Event::IdleTimeout => self.handle_idle_timeout(&mut cx),
1596 Event::FocusGained => {
1597 self.terminal_focused = true;
1598 EventResult::Consumed(None)
1599 }
1600 Event::FocusLost => {
1601 if context.editor.config().auto_save.focus_lost {
1602 let options = commands::WriteAllOptions {
1603 force: false,
1604 write_scratch: false,
1605 auto_format: false,
1606 code_actions: false,
1607 };
1608 if let Err(e) = commands::typed::write_all_impl(context, options) {
1609 context.editor.set_error(format!("{}", e));
1610 }
1611 }
1612 self.terminal_focused = false;
1613 EventResult::Consumed(None)
1614 }
1615 }
1616 }
1617
1618 fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
1619 // clear with background color
1620 surface.set_style(area, cx.editor.theme.get("ui.background"));
1621 let config = cx.editor.config();
1622
1623 // check if bufferline should be rendered
1624 use helix_view::editor::BufferLine;
1625 let use_bufferline = match config.bufferline {
1626 BufferLine::Always => true,
1627 BufferLine::Multiple if cx.editor.documents.len() > 1 => true,
1628 _ => false,
1629 };
1630
1631 // -1 for commandline and -1 for bufferline
1632 let mut editor_area = area.clip_bottom(1);
1633 if use_bufferline {
1634 editor_area = editor_area.clip_top(1);
1635 }
1636
1637 // if the terminal size suddenly changed, we need to trigger a resize
1638 cx.editor.resize(editor_area);
1639
1640 if use_bufferline {
1641 Self::render_bufferline(cx.editor, area.with_height(1), surface);
1642 }
1643
1644 for (view, is_focused) in cx.editor.tree.views() {
1645 let doc = cx.editor.document(view.doc).unwrap();
1646 self.render_view(cx.editor, doc, view, area, surface, is_focused);
1647 }
1648
1649 if config.auto_info {
1650 if let Some(mut info) = cx.editor.autoinfo.take() {
1651 info.render(area, surface, cx);
1652 cx.editor.autoinfo = Some(info)
1653 }
1654 }
1655
1656 let key_width = 15u16; // for showing pending keys
1657 let mut status_msg_width = 0;
1658
1659 // render status msg
1660 if let Some((status_msg, severity)) = &cx.editor.status_msg {
1661 status_msg_width = status_msg.width();
1662 use helix_view::editor::Severity;
1663 let style = if *severity == Severity::Error {
1664 cx.editor.theme.get("error")
1665 } else {
1666 cx.editor.theme.get("ui.text")
1667 };
1668
1669 surface.set_string(
1670 area.x,
1671 area.y + area.height.saturating_sub(1),
1672 status_msg,
1673 style,
1674 );
1675 }
1676
1677 if area.width.saturating_sub(status_msg_width as u16) > key_width {
1678 let mut disp = String::new();
1679 if let Some(count) = cx.editor.count {
1680 disp.push_str(&count.to_string())
1681 }
1682 for key in self.keymaps.pending() {
1683 disp.push_str(&key.key_sequence_format());
1684 }
1685 for key in &self.pseudo_pending {
1686 disp.push_str(&key.key_sequence_format());
1687 }
1688 let style = cx.editor.theme.get("ui.text");
1689 let macro_width = if cx.editor.macro_recording.is_some() {
1690 3
1691 } else {
1692 0
1693 };
1694 let restricted = workspace_trust_indicator_visible(cx.editor);
1695 let trust_width = if restricted { 3 } else { 0 };
1696 surface.set_string(
1697 area.x
1698 + area
1699 .width
1700 .saturating_sub(key_width + macro_width + trust_width),
1701 area.y + area.height.saturating_sub(1),
1702 disp.get(disp.len().saturating_sub(key_width as usize)..)
1703 .unwrap_or(&disp),
1704 style,
1705 );
1706 if restricted {
1707 let style = style
1708 .fg(helix_view::graphics::Color::Yellow)
1709 .add_modifier(Modifier::BOLD);
1710 surface.set_string(
1711 area.x
1712 .saturating_add(area.width.saturating_sub(3 + macro_width)),
1713 area.y + area.height.saturating_sub(1),
1714 "[⚠]",
1715 style,
1716 );
1717 }
1718 if let Some((reg, _)) = cx.editor.macro_recording {
1719 let disp = format!("[{}]", reg);
1720 let style = style
1721 .fg(helix_view::graphics::Color::Yellow)
1722 .add_modifier(Modifier::BOLD);
1723 surface.set_string(
1724 area.x + area.width.saturating_sub(3),
1725 area.y + area.height.saturating_sub(1),
1726 &disp,
1727 style,
1728 );
1729 }
1730 }
1731
1732 if let Some(completion) = self.completion.as_mut() {
1733 completion.render(area, surface, cx);
1734 }
1735 }
1736
1737 fn cursor(&self, _area: Rect, editor: &Editor) -> (Option<Position>, CursorKind) {
1738 match editor.cursor() {
1739 // all block cursors are drawn manually
1740 (pos, CursorKind::Block) => {
1741 if self.terminal_focused {
1742 (pos, CursorKind::Hidden)
1743 } else {
1744 // use terminal cursor when terminal loses focus
1745 (pos, CursorKind::Underline)
1746 }
1747 }
1748 cursor => cursor,
1749 }
1750 }
1751 }
1752
1753 fn canonicalize_key(key: &mut KeyEvent) {
1754 if let KeyEvent {
1755 code: KeyCode::Char(_),
1756 modifiers: _,
1757 } = key
1758 {
1759 key.modifiers.remove(KeyModifiers::SHIFT)
1760 }
1761 }