Debian Codegraph @

helix-term/src/application.rs

raw symbols SCIP
1 use arc_swap::{access::Map, ArcSwap};
2 use futures_util::Stream;
3 use helix_core::{diagnostic::Severity, pos_at_coords, syntax, Range, Selection};
4 use helix_lsp::{
5 lsp::{self, notification::Notification},
6 util::lsp_range_to_range,
7 LanguageServerId, LspProgressMap,
8 };
9 use helix_stdx::path::get_relative_path;
10 use helix_view::{
11 align_view,
12 document::{DocumentOpenError, DocumentSavedEventResult},
13 editor::{ConfigEvent, EditorEvent},
14 graphics::Rect,
15 theme,
16 tree::Layout,
17 Align, Editor,
18 };
19 use serde_json::json;
20 use tui::backend::Backend;
21
22 use crate::{
23 args::Args,
24 compositor::{Compositor, Event},
25 config::Config,
26 handlers,
27 job::Jobs,
28 keymap::Keymaps,
29 ui::{self, overlay::overlaid},
30 };
31
32 use log::{debug, error, info, warn};
33 use std::{
34 io::{stdin, IsTerminal},
35 path::Path,
36 sync::Arc,
37 };
38
39 #[cfg_attr(windows, allow(unused_imports))]
40 use anyhow::{Context, Error};
41
42 #[cfg(not(windows))]
43 use {signal_hook::consts::signal, signal_hook_tokio::Signals};
44 #[cfg(windows)]
45 type Signals = futures_util::stream::Empty<()>;
46
47 #[cfg(all(not(windows), not(feature = "integration")))]
48 use tui::backend::TerminaBackend;
49
50 #[cfg(all(windows, not(feature = "integration")))]
51 use tui::backend::CrosstermBackend;
52
53 #[cfg(feature = "integration")]
54 use tui::backend::TestBackend;
55
56 #[cfg(all(not(windows), not(feature = "integration")))]
57 type TerminalBackend = TerminaBackend;
58 #[cfg(all(windows, not(feature = "integration")))]
59 type TerminalBackend = CrosstermBackend<std::io::Stdout>;
60 #[cfg(feature = "integration")]
61 type TerminalBackend = TestBackend;
62
63 #[cfg(not(windows))]
64 type TerminalEvent = termina::Event;
65 #[cfg(windows)]
66 type TerminalEvent = crossterm::event::Event;
67
68 type Terminal = tui::terminal::Terminal<TerminalBackend>;
69
70 pub struct Application {
71 compositor: Compositor,
72 terminal: Terminal,
73 pub editor: Editor,
74
75 config: Arc<ArcSwap<Config>>,
76
77 signals: Signals,
78 jobs: Jobs,
79 lsp_progress: LspProgressMap,
80
81 theme_mode: Option<theme::Mode>,
82 }
83
84 #[cfg(feature = "integration")]
85 fn setup_integration_logging() {
86 let level = std::env::var("HELIX_LOG_LEVEL")
87 .map(|lvl| lvl.parse().unwrap())
88 .unwrap_or(log::LevelFilter::Info);
89
90 crate::logging::init_stdout(level);
91 }
92
93 impl Application {
94 pub fn new(
95 args: Args,
96 config: Config,
97 lang_loader: syntax::Loader,
98 workspace_trust: helix_loader::workspace_trust::WorkspaceTrust,
99 ) -> Result<Self, Error> {
100 #[cfg(feature = "integration")]
101 setup_integration_logging();
102
103 use helix_view::editor::Action;
104
105 let mut theme_parent_dirs = vec![helix_loader::config_dir()];
106 theme_parent_dirs.extend(helix_loader::runtime_dirs().iter().cloned());
107 let theme_loader = theme::Loader::new(&theme_parent_dirs);
108
109 #[cfg(all(not(windows), not(feature = "integration")))]
110 let backend = TerminaBackend::new((&config.editor).into())
111 .context("failed to create terminal backend")?;
112 #[cfg(all(windows, not(feature = "integration")))]
113 let backend = CrosstermBackend::new(std::io::stdout(), (&config.editor).into());
114
115 #[cfg(feature = "integration")]
116 let backend = TestBackend::new(120, 150);
117
118 let theme_mode = backend.get_theme_mode();
119 let mut terminal = Terminal::new(backend)?;
120 let area = terminal.size();
121 let mut compositor = Compositor::new(area);
122 let config = Arc::new(ArcSwap::from_pointee(config));
123 let handlers = handlers::setup(config.clone());
124 let mut editor = Editor::new(
125 area,
126 Arc::new(theme_loader),
127 Arc::new(ArcSwap::from_pointee(lang_loader)),
128 Arc::new(Map::new(Arc::clone(&config), |config: &Config| {
129 &config.editor
130 })),
131 handlers,
132 workspace_trust,
133 );
134 Self::load_configured_theme(&mut editor, &config.load(), &mut terminal, theme_mode);
135
136 let keys = Box::new(Map::new(Arc::clone(&config), |config: &Config| {
137 &config.keys
138 }));
139 let editor_view = Box::new(ui::EditorView::new(Keymaps::new(keys)));
140 compositor.push(editor_view);
141
142 let jobs = Jobs::new();
143
144 if args.load_tutor {
145 let path = helix_loader::runtime_file(Path::new("tutor"));
146 editor.open(&path, Action::VerticalSplit)?;
147 // Unset path to prevent accidentally saving to the original tutor file.
148 doc_mut!(editor).set_path(None);
149 } else if !args.files.is_empty() {
150 let mut files_it = args.files.into_iter().peekable();
151
152 // If the first file is a directory, skip it and open a picker
153 if let Some((first, _)) = files_it.next_if(|(p, _)| p.is_dir()) {
154 let picker = ui::file_picker(&editor, first);
155 compositor.push(Box::new(overlaid(picker)));
156 }
157
158 // If there are any more files specified, open them
159 if files_it.peek().is_some() {
160 let mut nr_of_files = 0;
161 for (file, pos) in files_it {
162 nr_of_files += 1;
163 if file.is_dir() {
164 return Err(anyhow::anyhow!(
165 "expected a path to file, but found a directory: {file:?}. (to open a directory pass it as first argument)"
166 ));
167 } else {
168 // If the user passes in either `--vsplit` or
169 // `--hsplit` as a command line argument, all the given
170 // files will be opened according to the selected
171 // option. If neither of those two arguments are passed
172 // in, just load the files normally.
173 let action = match args.split {
174 _ if nr_of_files == 1 => Action::VerticalSplit,
175 Some(Layout::Vertical) => Action::VerticalSplit,
176 Some(Layout::Horizontal) => Action::HorizontalSplit,
177 None => Action::Load,
178 };
179 let old_id = editor.document_id_by_path(&file);
180 let doc_id = match editor.open(&file, action) {
181 // Ignore irregular files during application init.
182 Err(DocumentOpenError::IrregularFile) => {
183 nr_of_files -= 1;
184 continue;
185 }
186 Err(err) => return Err(anyhow::anyhow!(err)),
187 // We can't open more than 1 buffer for 1 file, in this case we already have opened this file previously
188 Ok(doc_id) if old_id == Some(doc_id) => {
189 nr_of_files -= 1;
190 doc_id
191 }
192 Ok(doc_id) => doc_id,
193 };
194 // with Action::Load all documents have the same view
195 // NOTE: this isn't necessarily true anymore. If
196 // `--vsplit` or `--hsplit` are used, the file which is
197 // opened last is focused on.
198 let view_id = editor.tree.focus;
199 let doc = doc_mut!(editor, &doc_id);
200 let selection = pos
201 .into_iter()
202 .map(|coords| {
203 Range::point(pos_at_coords(doc.text().slice(..), coords, true))
204 })
205 .collect();
206 doc.set_selection(view_id, selection);
207 }
208 }
209
210 // if all files were invalid, replace with empty buffer
211 if nr_of_files == 0 {
212 editor.new_file(Action::VerticalSplit);
213 } else {
214 editor.set_status(format!(
215 "Loaded {} file{}.",
216 nr_of_files,
217 if nr_of_files == 1 { "" } else { "s" } // avoid "Loaded 1 files." grammo
218 ));
219 // align the view to center after all files are loaded,
220 // does not affect views without pos since it is at the top
221 let (view, doc) = current!(editor);
222 align_view(doc, view, Align::Center);
223 }
224 } else {
225 editor.new_file(Action::VerticalSplit);
226 }
227 } else if stdin().is_terminal() || cfg!(feature = "integration") {
228 editor.new_file(Action::VerticalSplit);
229 } else {
230 editor
231 .new_file_from_stdin(Action::VerticalSplit)
232 .unwrap_or_else(|_| editor.new_file(Action::VerticalSplit));
233 }
234
235 #[cfg(windows)]
236 let signals = futures_util::stream::empty();
237 #[cfg(not(windows))]
238 let signals = Signals::new([
239 signal::SIGTSTP,
240 signal::SIGCONT,
241 signal::SIGUSR1,
242 signal::SIGTERM,
243 signal::SIGINT,
244 ])
245 .context("build signal handler")?;
246
247 let app = Self {
248 compositor,
249 terminal,
250 editor,
251 config,
252 signals,
253 jobs,
254 lsp_progress: LspProgressMap::new(),
255 theme_mode,
256 };
257
258 Ok(app)
259 }
260
261 async fn render(&mut self) {
262 if self.compositor.full_redraw {
263 self.terminal.clear().expect("Cannot clear the terminal");
264 self.compositor.full_redraw = false;
265 }
266
267 let mut cx = crate::compositor::Context {
268 editor: &mut self.editor,
269 jobs: &mut self.jobs,
270 scroll: None,
271 };
272
273 helix_event::start_frame();
274 cx.editor.needs_redraw = false;
275
276 let area = self
277 .terminal
278 .autoresize()
279 .expect("Unable to determine terminal size");
280
281 // TODO: need to recalculate view tree if necessary
282
283 let surface = self.terminal.current_buffer_mut();
284
285 self.compositor.render(area, surface, &mut cx);
286 let (pos, kind) = self.compositor.cursor(area, &self.editor);
287 // reset cursor cache
288 self.editor.cursor_cache.reset();
289
290 let pos = pos.map(|pos| (pos.col as u16, pos.row as u16));
291 self.terminal.draw(pos, kind).unwrap();
292 }
293
294 pub async fn event_loop<S>(&mut self, input_stream: &mut S)
295 where
296 S: Stream<Item = std::io::Result<TerminalEvent>> + Unpin,
297 {
298 self.render().await;
299
300 loop {
301 if !self.event_loop_until_idle(input_stream).await {
302 break;
303 }
304 }
305 }
306
307 pub async fn event_loop_until_idle<S>(&mut self, input_stream: &mut S) -> bool
308 where
309 S: Stream<Item = std::io::Result<TerminalEvent>> + Unpin,
310 {
311 loop {
312 if self.editor.should_close() {
313 return false;
314 }
315
316 use futures_util::StreamExt;
317
318 tokio::select! {
319 biased;
320
321 Some(signal) = self.signals.next() => {
322 if !self.handle_signals(signal).await {
323 return false;
324 };
325 }
326 Some(event) = input_stream.next() => {
327 self.handle_terminal_events(event).await;
328 }
329 Some(callback) = self.jobs.callbacks.recv() => {
330 if let Some(job) = self.jobs.handle_callback(&mut self.editor, &mut self.compositor, Ok(Some(callback))) {
331 self.jobs.add(job);
332 }
333 self.render().await;
334 }
335 Some(msg) = self.jobs.status_messages.recv() => {
336 let severity = match msg.severity{
337 helix_event::status::Severity::Hint => Severity::Hint,
338 helix_event::status::Severity::Info => Severity::Info,
339 helix_event::status::Severity::Warning => Severity::Warning,
340 helix_event::status::Severity::Error => Severity::Error,
341 };
342 // TODO: show multiple status messages at once to avoid clobbering
343 self.editor.status_msg = Some((msg.message, severity));
344 helix_event::request_redraw();
345 }
346 Some(callback) = self.jobs.wait_futures.next() => {
347 if let Some(job) = self.jobs.handle_callback(&mut self.editor, &mut self.compositor, callback) {
348 self.jobs.add(job);
349 }
350 self.render().await;
351 }
352 event = self.editor.wait_event() => {
353 let _idle_handled = self.handle_editor_event(event).await;
354
355 #[cfg(feature = "integration")]
356 {
357 // Don't report idle while a save is still in flight, or an assertion on the post-save document state (e.g. its path,
358 // set in `handle_document_write`) can run before the `DocumentSavedEvent` is processed. Slow file I/O on Windows
359 // (atomic_save's rename/fsync dance over the still-open temp file) makes this race observable.
360 // Errors produce an event too, so it cannot hang.
361 if _idle_handled && self.editor.write_count == 0 {
362 return true;
363 }
364 }
365 }
366 }
367
368 // for integration tests only, reset the idle timer after every
369 // event to signal when test events are done processing
370 #[cfg(feature = "integration")]
371 {
372 self.editor.reset_idle_timer();
373 }
374 }
375 }
376
377 pub fn handle_config_events(&mut self, config_event: ConfigEvent) {
378 let old_editor_config = self.editor.config();
379
380 match config_event {
381 ConfigEvent::Refresh => self.refresh_config(),
382
383 // Since only the Application can make changes to Editor's config,
384 // the Editor must send up a new copy of a modified config so that
385 // the Application can apply it.
386 ConfigEvent::Update(editor_config) => {
387 let mut app_config = (*self.config.load().clone()).clone();
388 app_config.editor = *editor_config;
389 if let Err(err) = self.terminal.reconfigure((&app_config.editor).into()) {
390 self.editor.set_error(err.to_string());
391 };
392 self.config.store(Arc::new(app_config));
393 }
394 ConfigEvent::ThemeChanged => {
395 let _ = self.terminal.backend_mut().set_background_color(
396 self.editor
397 .theme
398 .try_get_exact("ui.background")
399 .and_then(|style| style.bg),
400 );
401 return;
402 }
403 }
404
405 // Update all the relevant members in the editor after updating
406 // the configuration.
407 self.editor.refresh_config(&old_editor_config);
408
409 // reset view position in case softwrap was enabled/disabled
410 let scrolloff = self.editor.config().scrolloff;
411 for (view, _) in self.editor.tree.views() {
412 let doc = doc_mut!(self.editor, &view.doc);
413 view.ensure_cursor_in_view(doc, scrolloff);
414 }
415 }
416
417 fn refresh_config(&mut self) {
418 let mut refresh_config = || -> Result<(), Error> {
419 let default_config = Config::load_default()
420 .map_err(|err| anyhow::anyhow!("Failed to load config: {}", err))?;
421
422 // Apply any change to editor.workspace_trust before reading local language config.
423 self.editor
424 .workspace_trust
425 .set_config((&default_config.editor.workspace_trust).into());
426
427 // Update the syntax language loader before setting the theme. Setting the theme will
428 // call `Loader::set_scopes` which must be done before the documents are re-parsed for
429 // the sake of locals highlighting.
430 let lang_loader = helix_core::config::user_lang_loader(&self.editor.workspace_trust)?;
431 self.editor.syn_loader.store(Arc::new(lang_loader));
432 Self::load_configured_theme(
433 &mut self.editor,
434 &default_config,
435 &mut self.terminal,
436 self.theme_mode,
437 );
438
439 // Re-parse any open documents with the new language config.
440 let lang_loader = self.editor.syn_loader.load();
441 for document in self.editor.documents.values_mut() {
442 // Re-detect .editorconfig
443 document.detect_editor_config();
444 document.detect_language(&lang_loader);
445 let diagnostics = Editor::doc_diagnostics(
446 &self.editor.language_servers,
447 &self.editor.diagnostics,
448 document,
449 );
450 document.replace_diagnostics(diagnostics, &[], None);
451 }
452
453 self.terminal.reconfigure((&default_config.editor).into())?;
454 // Store new config
455 self.config.store(Arc::new(default_config));
456 Ok(())
457 };
458
459 match refresh_config() {
460 Ok(_) => {
461 self.editor.set_status("Config refreshed");
462 }
463 Err(err) => {
464 self.editor.set_error(err.to_string());
465 }
466 }
467 }
468
469 /// Load the theme set in configuration
470 fn load_configured_theme(
471 editor: &mut Editor,
472 config: &Config,
473 terminal: &mut Terminal,
474 mode: Option<theme::Mode>,
475 ) {
476 let true_color = terminal.backend().supports_true_color()
477 || config.editor.true_color
478 || crate::true_color();
479 let theme = config
480 .theme
481 .as_ref()
482 .and_then(|theme_config| {
483 let theme = theme_config.choose(mode);
484 editor
485 .theme_loader
486 .load(theme)
487 .map_err(|e| {
488 log::warn!("failed to load theme `{}` - {}", theme, e);
489 e
490 })
491 .ok()
492 .filter(|theme| {
493 let colors_ok = true_color || theme.is_16_color();
494 if !colors_ok {
495 log::warn!(
496 "loaded theme `{}` but cannot use it because true color \
497 support is not enabled",
498 theme.name()
499 );
500 }
501 colors_ok
502 })
503 })
504 .unwrap_or_else(|| editor.theme_loader.default_theme(true_color));
505 let _ = editor.set_theme(theme);
506 }
507
508 #[cfg(windows)]
509 // no signal handling available on windows
510 pub async fn handle_signals(&mut self, _signal: ()) -> bool {
511 true
512 }
513
514 #[cfg(not(windows))]
515 pub async fn handle_signals(&mut self, signal: i32) -> bool {
516 match signal {
517 signal::SIGTSTP => {
518 self.restore_term().unwrap();
519
520 // SAFETY:
521 //
522 // - helix must have permissions to send signals to all processes in its signal
523 // group, either by already having the requisite permission, or by having the
524 // user's UID / EUID / SUID match that of the receiving process(es).
525 let res = unsafe {
526 // A pid of 0 sends the signal to the entire process group, allowing the user to
527 // regain control of their terminal if the editor was spawned under another process
528 // (e.g. when running `git commit`).
529 //
530 // We have to send SIGSTOP (not SIGTSTP) to the entire process group, because,
531 // as mentioned above, the terminal will get stuck if `helix` was spawned from
532 // an external process and that process waits for `helix` to complete. This may
533 // be an issue with signal-hook-tokio, but the author of signal-hook believes it
534 // could be a tokio issue instead:
535 // https://github.com/vorner/signal-hook/issues/132
536 libc::kill(0, signal::SIGSTOP)
537 };
538
539 if res != 0 {
540 let err = std::io::Error::last_os_error();
541 eprintln!("{}", err);
542 let res = err.raw_os_error().unwrap_or(1);
543 std::process::exit(res);
544 }
545 }
546 signal::SIGCONT => {
547 // Copy/Paste from same issue from neovim:
548 // https://github.com/neovim/neovim/issues/12322
549 // https://github.com/neovim/neovim/pull/13084
550 for retries in 1..=10 {
551 match self.terminal.claim() {
552 Ok(()) => break,
553 Err(err) if retries == 10 => panic!("Failed to claim terminal: {}", err),
554 Err(_) => continue,
555 }
556 }
557
558 // redraw the terminal
559 let area = self.terminal.size();
560 self.compositor.resize(area);
561 self.terminal.clear().expect("couldn't clear terminal");
562
563 self.render().await;
564 }
565 signal::SIGUSR1 => {
566 self.refresh_config();
567 self.render().await;
568 }
569 signal::SIGTERM | signal::SIGINT => {
570 self.restore_term().unwrap();
571 return false;
572 }
573 _ => unreachable!(),
574 }
575
576 true
577 }
578
579 pub async fn handle_idle_timeout(&mut self) {
580 let mut cx = crate::compositor::Context {
581 editor: &mut self.editor,
582 jobs: &mut self.jobs,
583 scroll: None,
584 };
585 let should_render = self.compositor.handle_event(&Event::IdleTimeout, &mut cx);
586 if should_render || self.editor.needs_redraw {
587 self.render().await;
588 }
589 }
590
591 pub fn handle_document_write(&mut self, doc_save_event: DocumentSavedEventResult) {
592 let doc_save_event = match doc_save_event {
593 Ok(event) => event,
594 Err(err) => {
595 self.editor.set_error(err.to_string());
596 return;
597 }
598 };
599
600 let doc = match self.editor.document_mut(doc_save_event.doc_id) {
601 None => {
602 warn!(
603 "received document saved event for non-existent doc id: {}",
604 doc_save_event.doc_id
605 );
606
607 return;
608 }
609 Some(doc) => doc,
610 };
611
612 debug!(
613 "document {:?} saved with revision {}",
614 doc.path(),
615 doc_save_event.revision
616 );
617
618 doc.set_last_saved_revision(doc_save_event.revision, doc_save_event.save_time);
619
620 let lines = doc_save_event.text.len_lines();
621 let size = doc_save_event.text.len_bytes();
622
623 enum Size {
624 Bytes(u16),
625 HumanReadable(f32, &'static str),
626 }
627
628 impl std::fmt::Display for Size {
629 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
630 match self {
631 Self::Bytes(bytes) => write!(f, "{bytes}B"),
632 Self::HumanReadable(size, suffix) => write!(f, "{size:.1}{suffix}"),
633 }
634 }
635 }
636
637 let size = if size < 1024 {
638 Size::Bytes(size as u16)
639 } else {
640 const SUFFIX: [&str; 4] = ["B", "KiB", "MiB", "GiB"];
641 let mut size = size as f32;
642 let mut i = 0;
643 while i < SUFFIX.len() - 1 && size >= 1024.0 {
644 size /= 1024.0;
645 i += 1;
646 }
647 Size::HumanReadable(size, SUFFIX[i])
648 };
649
650 self.editor
651 .set_doc_path(doc_save_event.doc_id, &doc_save_event.path);
652 // TODO: fix being overwritten by lsp
653 self.editor.set_status(format!(
654 "'{}' written, {lines}L {size}",
655 get_relative_path(&doc_save_event.path).to_string_lossy(),
656 ));
657 }
658
659 #[inline(always)]
660 pub async fn handle_editor_event(&mut self, event: EditorEvent) -> bool {
661 log::debug!("received editor event: {:?}", event);
662
663 match event {
664 EditorEvent::DocumentSaved(event) => {
665 self.handle_document_write(event);
666 self.render().await;
667 }
668 EditorEvent::ConfigEvent(event) => {
669 self.handle_config_events(event);
670 self.render().await;
671 }
672 EditorEvent::LanguageServerMessage((id, call)) => {
673 self.handle_language_server_message(call, id).await;
674 // limit render calls for fast language server messages
675 helix_event::request_redraw();
676 }
677 EditorEvent::DebuggerEvent((id, payload)) => {
678 let needs_render = self.editor.handle_debugger_message(id, payload).await;
679 if needs_render {
680 self.render().await;
681 }
682 }
683 EditorEvent::Redraw => {
684 self.render().await;
685 }
686 EditorEvent::IdleTimer => {
687 self.editor.clear_idle_timer();
688 self.handle_idle_timeout().await;
689
690 #[cfg(feature = "integration")]
691 {
692 return true;
693 }
694 }
695 }
696
697 false
698 }
699
700 pub async fn handle_terminal_events(&mut self, event: std::io::Result<TerminalEvent>) {
701 #[cfg(not(windows))]
702 use termina::escape::csi;
703
704 let mut cx = crate::compositor::Context {
705 editor: &mut self.editor,
706 jobs: &mut self.jobs,
707 scroll: None,
708 };
709 // Handle key events
710 let should_redraw = match event.unwrap() {
711 #[cfg(not(windows))]
712 termina::Event::WindowResized(termina::WindowSize { rows, cols, .. }) => {
713 self.terminal
714 .resize(Rect::new(0, 0, cols, rows))
715 .expect("Unable to resize terminal");
716
717 let area = self.terminal.size();
718
719 self.compositor.resize(area);
720
721 self.compositor
722 .handle_event(&Event::Resize(cols, rows), &mut cx)
723 }
724 #[cfg(not(windows))]
725 // Ignore keyboard release events.
726 termina::Event::Key(termina::event::KeyEvent {
727 kind: termina::event::KeyEventKind::Release,
728 ..
729 }) => false,
730 #[cfg(not(windows))]
731 termina::Event::Csi(csi::Csi::Mode(csi::Mode::ReportTheme(mode))) => {
732 let config = self.config.load();
733 let mode = mode.into();
734 let mode_changed = self.theme_mode.as_ref().is_none_or(|m| m != &mode);
735 if mode_changed && config.theme.as_ref().is_some_and(|t| t.is_adaptive()) {
736 self.theme_mode = Some(mode);
737 Self::load_configured_theme(
738 &mut self.editor,
739 &config,
740 &mut self.terminal,
741 self.theme_mode,
742 );
743 true
744 } else {
745 false
746 }
747 }
748 #[cfg(windows)]
749 TerminalEvent::Resize(width, height) => {
750 self.terminal
751 .resize(Rect::new(0, 0, width, height))
752 .expect("Unable to resize terminal");
753
754 let area = self.terminal.size();
755
756 self.compositor.resize(area);
757
758 self.compositor
759 .handle_event(&Event::Resize(width, height), &mut cx)
760 }
761 #[cfg(windows)]
762 // Ignore keyboard release events.
763 crossterm::event::Event::Key(crossterm::event::KeyEvent {
764 kind: crossterm::event::KeyEventKind::Release,
765 ..
766 }) => false,
767 #[cfg(not(windows))]
768 event if event.is_escape() => false,
769 event => self.compositor.handle_event(&event.into(), &mut cx),
770 };
771
772 if should_redraw && !self.editor.should_close() {
773 self.render().await;
774 }
775 }
776
777 pub async fn handle_language_server_message(
778 &mut self,
779 call: helix_lsp::Call,
780 server_id: LanguageServerId,
781 ) {
782 use helix_lsp::{Call, MethodCall, Notification};
783
784 macro_rules! language_server {
785 () => {
786 match self.editor.language_server_by_id(server_id) {
787 Some(language_server) => language_server,
788 None => {
789 warn!("can't find language server with id `{}`", server_id);
790 return;
791 }
792 }
793 };
794 }
795
796 match call {
797 Call::Notification(helix_lsp::jsonrpc::Notification { method, params, .. }) => {
798 let notification = match Notification::parse(&method, params) {
799 Ok(notification) => notification,
800 Err(helix_lsp::Error::Unhandled) => {
801 info!("Ignoring Unhandled notification from Language Server");
802 return;
803 }
804 Err(err) => {
805 error!(
806 "Ignoring unknown notification from Language Server: {}",
807 err
808 );
809 return;
810 }
811 };
812
813 match notification {
814 Notification::Initialized => {
815 let language_server = language_server!();
816
817 // Trigger a workspace/didChangeConfiguration notification after initialization.
818 // This might not be required by the spec but Neovim does this as well, so it's
819 // probably a good idea for compatibility.
820 if let Some(config) = language_server.config() {
821 language_server.did_change_configuration(config.clone());
822 }
823
824 helix_event::dispatch(helix_view::events::LanguageServerInitialized {
825 editor: &mut self.editor,
826 server_id,
827 });
828 }
829 Notification::PublishDiagnostics(params) => {
830 let uri = match helix_core::Uri::try_from(params.uri) {
831 Ok(uri) => uri,
832 Err(err) => {
833 log::error!("{err}");
834 return;
835 }
836 };
837 let language_server = language_server!();
838 if !language_server.is_initialized() {
839 log::error!("Discarding publishDiagnostic notification sent by an uninitialized server: {}", language_server.name());
840 return;
841 }
842 let provider = helix_core::diagnostic::DiagnosticProvider::Lsp {
843 server_id,
844 identifier: None,
845 };
846 self.editor.handle_lsp_diagnostics(
847 &provider,
848 uri,
849 params.version,
850 params.diagnostics,
851 );
852 }
853 Notification::ShowMessage(params) => {
854 self.handle_show_message(params.typ, params.message);
855 }
856 Notification::LogMessage(params) => {
857 log::info!("window/logMessage: {:?}", params);
858 }
859 Notification::ProgressMessage(params)
860 if !self
861 .compositor
862 .has_component(std::any::type_name::<ui::Prompt>()) =>
863 {
864 let editor_view = self
865 .compositor
866 .find::<ui::EditorView>()
867 .expect("expected at least one EditorView");
868 let lsp::ProgressParams {
869 token,
870 value: lsp::ProgressParamsValue::WorkDone(work),
871 } = params;
872 let (title, message, percentage) = match &work {
873 lsp::WorkDoneProgress::Begin(lsp::WorkDoneProgressBegin {
874 title,
875 message,
876 percentage,
877 ..
878 }) => (Some(title), message, percentage),
879 lsp::WorkDoneProgress::Report(lsp::WorkDoneProgressReport {
880 message,
881 percentage,
882 ..
883 }) => (None, message, percentage),
884 lsp::WorkDoneProgress::End(lsp::WorkDoneProgressEnd { message }) => {
885 if message.is_some() {
886 (None, message, &None)
887 } else {
888 self.lsp_progress.end_progress(server_id, &token);
889 if !self.lsp_progress.is_progressing(server_id) {
890 editor_view.spinners_mut().get_or_create(server_id).stop();
891 handlers::diagnostics::request_all_document_diagnostics_for_language_server(
892 &mut self.editor,
893 server_id,
894 );
895 }
896 self.editor.clear_status();
897
898 // we want to render to clear any leftover spinners or messages
899 return;
900 }
901 }
902 };
903
904 if self.editor.config().lsp.display_progress_messages {
905 let title =
906 title.or_else(|| self.lsp_progress.title(server_id, &token));
907 if title.is_some() || percentage.is_some() || message.is_some() {
908 use std::fmt::Write as _;
909 let mut status = format!("{}: ", language_server!().name());
910 if let Some(percentage) = percentage {
911 write!(status, "{percentage:>2}% ").unwrap();
912 }
913 if let Some(title) = title {
914 status.push_str(title);
915 }
916 if title.is_some() && message.is_some() {
917 status.push_str(" ⋅ ");
918 }
919 if let Some(message) = message {
920 status.push_str(message);
921 }
922 self.editor.set_status(status);
923 }
924 }
925
926 match work {
927 lsp::WorkDoneProgress::Begin(begin_status) => {
928 self.lsp_progress
929 .begin(server_id, token.clone(), begin_status);
930 }
931 lsp::WorkDoneProgress::Report(report_status) => {
932 self.lsp_progress
933 .update(server_id, token.clone(), report_status);
934 }
935 lsp::WorkDoneProgress::End(_) => {
936 self.lsp_progress.end_progress(server_id, &token);
937 if !self.lsp_progress.is_progressing(server_id) {
938 editor_view.spinners_mut().get_or_create(server_id).stop();
939 handlers::diagnostics::request_all_document_diagnostics_for_language_server(
940 &mut self.editor,
941 server_id,
942 );
943 };
944 }
945 }
946 }
947 Notification::ProgressMessage(_params) => {
948 // do nothing
949 }
950 Notification::Exit => {
951 let status =
952 format!("Language server exited: {}", language_server!().name());
953 self.editor.set_status(status);
954
955 // LSPs may produce diagnostics for files that haven't been opened in helix,
956 // we need to clear those and remove the entries from the list if this leads to
957 // an empty diagnostic list for said files
958 for diags in self.editor.diagnostics.values_mut() {
959 diags.retain(|(_, provider)| {
960 provider.language_server_id() != Some(server_id)
961 });
962 }
963
964 self.editor.diagnostics.retain(|_, diags| !diags.is_empty());
965
966 // Clear any diagnostics for documents with this server open.
967 for doc in self.editor.documents_mut() {
968 doc.clear_diagnostics_for_language_server(server_id);
969 }
970
971 helix_event::dispatch(helix_view::events::LanguageServerExited {
972 editor: &mut self.editor,
973 server_id,
974 });
975
976 // Remove the language server from the registry.
977 self.editor.language_servers.remove_by_id(server_id);
978 }
979 }
980 }
981 Call::MethodCall(helix_lsp::jsonrpc::MethodCall {
982 method, params, id, ..
983 }) => {
984 let reply = match MethodCall::parse(&method, params) {
985 Err(helix_lsp::Error::Unhandled) => {
986 error!(
987 "Language Server: Method {} not found in request {}",
988 method, id
989 );
990 Err(helix_lsp::jsonrpc::Error {
991 code: helix_lsp::jsonrpc::ErrorCode::MethodNotFound,
992 message: format!("Method not found: {}", method),
993 data: None,
994 })
995 }
996 Err(err) => {
997 log::error!(
998 "Language Server: Received malformed method call {} in request {}: {}",
999 method,
1000 id,
1001 err
1002 );
1003 Err(helix_lsp::jsonrpc::Error {
1004 code: helix_lsp::jsonrpc::ErrorCode::ParseError,
1005 message: format!("Malformed method call: {}", method),
1006 data: None,
1007 })
1008 }
1009 Ok(MethodCall::WorkDoneProgressCreate(params)) => {
1010 self.lsp_progress.create(server_id, params.token);
1011
1012 let editor_view = self
1013 .compositor
1014 .find::<ui::EditorView>()
1015 .expect("expected at least one EditorView");
1016 let spinner = editor_view.spinners_mut().get_or_create(server_id);
1017 if spinner.is_stopped() {
1018 spinner.start();
1019 }
1020
1021 Ok(serde_json::Value::Null)
1022 }
1023 Ok(MethodCall::ApplyWorkspaceEdit(params)) => {
1024 let language_server = language_server!();
1025 if language_server.is_initialized() {
1026 let offset_encoding = language_server.offset_encoding();
1027 let res = self
1028 .editor
1029 .apply_workspace_edit(offset_encoding, &params.edit);
1030
1031 Ok(json!(lsp::ApplyWorkspaceEditResponse {
1032 applied: res.is_ok(),
1033 failure_reason: res.as_ref().err().map(|err| err.kind.to_string()),
1034 failed_change: res
1035 .as_ref()
1036 .err()
1037 .map(|err| err.failed_change_idx as u32),
1038 }))
1039 } else {
1040 Err(helix_lsp::jsonrpc::Error {
1041 code: helix_lsp::jsonrpc::ErrorCode::InvalidRequest,
1042 message: "Server must be initialized to request workspace edits"
1043 .to_string(),
1044 data: None,
1045 })
1046 }
1047 }
1048 Ok(MethodCall::WorkspaceFolders) => {
1049 Ok(json!(&*language_server!().workspace_folders().await))
1050 }
1051 Ok(MethodCall::WorkspaceConfiguration(params)) => {
1052 let language_server = language_server!();
1053 let result: Vec<_> = params
1054 .items
1055 .iter()
1056 .map(|item| {
1057 let mut config = language_server.config()?;
1058 if let Some(section) = item.section.as_ref() {
1059 // for some reason some lsps send an empty string (observed in 'vscode-eslint-language-server')
1060 if !section.is_empty() {
1061 for part in section.split('.') {
1062 config = config.get(part)?;
1063 }
1064 }
1065 }
1066 Some(config)
1067 })
1068 .collect();
1069 Ok(json!(result))
1070 }
1071 Ok(MethodCall::RegisterCapability(params)) => {
1072 if let Some(client) = self.editor.language_servers.get_by_id(server_id) {
1073 for reg in params.registrations {
1074 match reg.method.as_str() {
1075 lsp::notification::DidChangeWatchedFiles::METHOD => {
1076 let Some(options) = reg.register_options else {
1077 continue;
1078 };
1079 let ops: lsp::DidChangeWatchedFilesRegistrationOptions =
1080 match serde_json::from_value(options) {
1081 Ok(ops) => ops,
1082 Err(err) => {
1083 log::warn!("Failed to deserialize DidChangeWatchedFilesRegistrationOptions: {err}");
1084 continue;
1085 }
1086 };
1087 self.editor.language_servers.file_event_handler.register(
1088 client.id(),
1089 Arc::downgrade(client),
1090 reg.id,
1091 ops,
1092 )
1093 }
1094 _ => {
1095 // Language Servers based on the `vscode-languageserver-node` library often send
1096 // client/registerCapability even though we do not enable dynamic registration
1097 // for most capabilities. We should send a MethodNotFound JSONRPC error in this
1098 // case but that rejects the registration promise in the server which causes an
1099 // exit. So we work around this by ignoring the request and sending back an OK
1100 // response.
1101 log::warn!("Ignoring a client/registerCapability request because dynamic capability registration is not enabled. Please report this upstream to the language server");
1102 }
1103 }
1104 }
1105 }
1106
1107 Ok(serde_json::Value::Null)
1108 }
1109 Ok(MethodCall::UnregisterCapability(params)) => {
1110 for unreg in params.unregisterations {
1111 match unreg.method.as_str() {
1112 lsp::notification::DidChangeWatchedFiles::METHOD => {
1113 self.editor
1114 .language_servers
1115 .file_event_handler
1116 .unregister(server_id, unreg.id);
1117 }
1118 _ => {
1119 log::warn!("Received unregistration request for unsupported method: {}", unreg.method);
1120 }
1121 }
1122 }
1123 Ok(serde_json::Value::Null)
1124 }
1125 Ok(MethodCall::ShowDocument(params)) => {
1126 let language_server = language_server!();
1127 let offset_encoding = language_server.offset_encoding();
1128
1129 let result = self.handle_show_document(params, offset_encoding);
1130 Ok(json!(result))
1131 }
1132 Ok(MethodCall::WorkspaceDiagnosticRefresh) => {
1133 let server_id = language_server!().id();
1134 handlers::diagnostics::request_all_document_diagnostics_for_language_server(
1135 &mut self.editor,
1136 server_id,
1137 );
1138
1139 Ok(serde_json::Value::Null)
1140 }
1141 Ok(MethodCall::ShowMessageRequest(params)) => {
1142 if let Some(actions) = params.actions.filter(|a| !a.is_empty()) {
1143 let id = id.clone();
1144 let select = ui::Select::new(
1145 params.message,
1146 actions,
1147 (),
1148 move |editor, action, event| {
1149 let reply = match event {
1150 ui::PromptEvent::Update => return,
1151 ui::PromptEvent::Validate => Some(action.clone()),
1152 ui::PromptEvent::Abort => None,
1153 };
1154 if let Some(language_server) =
1155 editor.language_server_by_id(server_id)
1156 {
1157 if let Err(err) =
1158 language_server.reply(id.clone(), Ok(json!(reply)))
1159 {
1160 log::error!(
1161 "Failed to send reply to server '{}' request {id}: {err}",
1162 language_server.name()
1163 );
1164 }
1165 }
1166 },
1167 );
1168 self.compositor
1169 .replace_or_push("lsp-show-message-request", select);
1170 // Avoid sending a reply. The `Select` callback above sends the reply.
1171 return;
1172 } else {
1173 self.handle_show_message(params.typ, params.message);
1174 Ok(serde_json::Value::Null)
1175 }
1176 }
1177 };
1178
1179 let language_server = language_server!();
1180 if let Err(err) = language_server.reply(id.clone(), reply) {
1181 log::error!(
1182 "Failed to send reply to server '{}' request {id}: {err}",
1183 language_server.name()
1184 );
1185 }
1186 }
1187 Call::Invalid { id } => log::error!("LSP invalid method call id={:?}", id),
1188 }
1189 }
1190
1191 fn handle_show_message(&mut self, message_type: lsp::MessageType, message: String) {
1192 if self.config.load().editor.lsp.display_messages {
1193 match message_type {
1194 lsp::MessageType::ERROR => self.editor.set_error(message),
1195 lsp::MessageType::WARNING => self.editor.set_warning(message),
1196 _ => self.editor.set_status(message),
1197 }
1198 }
1199 }
1200
1201 fn handle_show_document(
1202 &mut self,
1203 params: lsp::ShowDocumentParams,
1204 offset_encoding: helix_lsp::OffsetEncoding,
1205 ) -> lsp::ShowDocumentResult {
1206 if let lsp::ShowDocumentParams {
1207 external: Some(true),
1208 uri,
1209 ..
1210 } = params
1211 {
1212 self.jobs.callback(crate::open_external_url_callback(uri));
1213 return lsp::ShowDocumentResult { success: true };
1214 };
1215
1216 let lsp::ShowDocumentParams {
1217 uri,
1218 selection,
1219 take_focus,
1220 ..
1221 } = params;
1222
1223 let uri = match helix_core::Uri::try_from(uri) {
1224 Ok(uri) => uri,
1225 Err(err) => {
1226 log::error!("{err}");
1227 return lsp::ShowDocumentResult { success: false };
1228 }
1229 };
1230 // If `Uri` gets another variant other than `Path` this may not be valid.
1231 let path = uri.as_path().expect("URIs are valid paths");
1232
1233 // Determine the focus strategy based on the current UI state and LSP request:
1234 // 1. If there is no pop-up overlay, jump directly (Replace).
1235 // 2. If there is a pop-up overlay, unless the LSP forces take_focus, only load in the background (Load) to prevent interruption of input.
1236 // Note: We assume layer_count() == 1 means only the EditorView is present (no popups/overlays).
1237 let action = if self.compositor.layer_count() == 1 {
1238 helix_view::editor::Action::Replace
1239 } else {
1240 match take_focus {
1241 Some(true) => helix_view::editor::Action::Replace,
1242 _ => helix_view::editor::Action::Load,
1243 }
1244 };
1245
1246 let doc_id = match self.editor.open(path, action) {
1247 Ok(id) => id,
1248 Err(err) => {
1249 log::error!("failed to open path: {:?}: {:?}", uri, err);
1250 return lsp::ShowDocumentResult { success: false };
1251 }
1252 };
1253
1254 let doc = doc_mut!(self.editor, &doc_id);
1255 if let Some(range) = selection {
1256 // TODO: convert inside server
1257 if let Some(new_range) = lsp_range_to_range(doc.text(), range, offset_encoding) {
1258 let view = view_mut!(self.editor);
1259
1260 // we flip the range so that the cursor sits on the start of the symbol
1261 // (for example start of the function).
1262 doc.set_selection(view.id, Selection::single(new_range.head, new_range.anchor));
1263 if action.align_view(view, doc.id()) {
1264 align_view(doc, view, Align::Center);
1265 }
1266 } else {
1267 log::warn!("lsp position out of bounds - {:?}", range);
1268 };
1269 };
1270 lsp::ShowDocumentResult { success: true }
1271 }
1272
1273 fn restore_term(&mut self) -> std::io::Result<()> {
1274 use helix_view::graphics::CursorKind;
1275 self.terminal
1276 .backend_mut()
1277 .show_cursor(CursorKind::Block)
1278 .ok();
1279 self.terminal.restore()
1280 }
1281
1282 #[cfg(all(not(feature = "integration"), not(windows)))]
1283 pub fn event_stream(&self) -> impl Stream<Item = std::io::Result<TerminalEvent>> + Unpin {
1284 use termina::{escape::csi, Terminal as _};
1285 let reader = self.terminal.backend().terminal().event_reader();
1286 termina::EventStream::new(reader, |event| {
1287 // Accept either non-escape sequences or theme mode updates.
1288 !event.is_escape()
1289 || matches!(
1290 event,
1291 termina::Event::Csi(csi::Csi::Mode(csi::Mode::ReportTheme(_)))
1292 )
1293 })
1294 }
1295
1296 #[cfg(all(not(feature = "integration"), windows))]
1297 pub fn event_stream(&self) -> impl Stream<Item = std::io::Result<TerminalEvent>> + Unpin {
1298 crossterm::event::EventStream::new()
1299 }
1300
1301 #[cfg(feature = "integration")]
1302 pub fn event_stream(&self) -> impl Stream<Item = std::io::Result<TerminalEvent>> + Unpin {
1303 use std::{
1304 pin::Pin,
1305 task::{Context, Poll},
1306 };
1307
1308 /// A dummy stream that never polls as ready.
1309 pub struct DummyEventStream;
1310
1311 impl Stream for DummyEventStream {
1312 type Item = std::io::Result<TerminalEvent>;
1313
1314 fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1315 Poll::Pending
1316 }
1317 }
1318
1319 DummyEventStream
1320 }
1321
1322 pub async fn run<S>(&mut self, input_stream: &mut S) -> Result<i32, Error>
1323 where
1324 S: Stream<Item = std::io::Result<TerminalEvent>> + Unpin,
1325 {
1326 self.terminal.claim()?;
1327
1328 self.event_loop(input_stream).await;
1329
1330 let close_errs = self.close().await;
1331
1332 self.restore_term()?;
1333
1334 for err in close_errs {
1335 self.editor.exit_code = 1;
1336 eprintln!("Error: {}", err);
1337 }
1338
1339 Ok(self.editor.exit_code)
1340 }
1341
1342 pub async fn close(&mut self) -> Vec<anyhow::Error> {
1343 // [NOTE] we intentionally do not return early for errors because we
1344 // want to try to run as much cleanup as we can, regardless of
1345 // errors along the way
1346 let mut errs = Vec::new();
1347
1348 if let Err(err) = self
1349 .jobs
1350 .finish(&mut self.editor, Some(&mut self.compositor))
1351 .await
1352 {
1353 log::error!("Error executing job: {}", err);
1354 errs.push(err);
1355 };
1356
1357 if let Err(err) = self.editor.flush_writes().await {
1358 log::error!("Error writing: {}", err);
1359 errs.push(err);
1360 }
1361
1362 self.editor.close_language_servers(None).await;
1363
1364 errs
1365 }
1366 }
1367
1368 impl ui::menu::Item for lsp::MessageActionItem {
1369 type Data = ();
1370 fn format(&self, _data: &Self::Data) -> tui::widgets::Row<'_> {
1371 self.title.as_str().into()
1372 }
1373 }