1pub mod mappings;
2
3pub use alacritty_terminal;
4
5mod pty_info;
6pub mod terminal_settings;
7
8use alacritty_terminal::{
9 event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
10 event_loop::{EventLoop, Msg, Notifier},
11 grid::{Dimensions, Scroll as AlacScroll},
12 index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
13 selection::{Selection, SelectionRange, SelectionType},
14 sync::FairMutex,
15 term::{
16 cell::Cell,
17 search::{Match, RegexIter, RegexSearch},
18 Config, RenderableCursor, TermMode,
19 },
20 tty::{self},
21 vi_mode::{ViModeCursor, ViMotion},
22 vte::ansi::{
23 ClearMode, CursorStyle as AlacCursorStyle, Handler, NamedPrivateMode, PrivateMode,
24 },
25 Term,
26};
27use anyhow::{bail, Result};
28
29use futures::{
30 channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
31 FutureExt,
32};
33
34use mappings::mouse::{
35 alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
36 scroll_report,
37};
38
39use collections::{HashMap, VecDeque};
40use futures::StreamExt;
41use pty_info::PtyProcessInfo;
42use serde::{Deserialize, Serialize};
43use settings::Settings;
44use smol::channel::{Receiver, Sender};
45use task::{HideStrategy, Shell, TaskId};
46use terminal_settings::{AlternateScroll, CursorShape, TerminalSettings};
47use theme::{ActiveTheme, Theme};
48use util::truncate_and_trailoff;
49
50use std::{
51 cmp::{self, min},
52 fmt::Display,
53 ops::{Deref, Index, RangeInclusive},
54 path::PathBuf,
55 sync::Arc,
56 time::Duration,
57};
58use thiserror::Error;
59
60use gpui::{
61 actions, black, px, AnyWindowHandle, AppContext, Bounds, ClipboardItem, EventEmitter, Hsla,
62 Keystroke, ModelContext, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
63 Pixels, Point, Rgba, ScrollWheelEvent, Size, Task, TouchPhase,
64};
65
66use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
67
68actions!(
69 terminal,
70 [
71 Clear,
72 Copy,
73 Paste,
74 ShowCharacterPalette,
75 SearchTest,
76 ScrollLineUp,
77 ScrollLineDown,
78 ScrollPageUp,
79 ScrollPageDown,
80 ScrollToTop,
81 ScrollToBottom,
82 ToggleViMode,
83 ]
84);
85
86///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
87///Scroll multiplier that is set to 3 by default. This will be removed when I
88///Implement scroll bars.
89#[cfg(target_os = "macos")]
90const SCROLL_MULTIPLIER: f32 = 4.;
91#[cfg(not(target_os = "macos"))]
92const SCROLL_MULTIPLIER: f32 = 1.;
93const MAX_SEARCH_LINES: usize = 100;
94const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
95const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
96const DEBUG_CELL_WIDTH: Pixels = px(5.);
97const DEBUG_LINE_HEIGHT: Pixels = px(5.);
98
99///Upward flowing events, for changing the title and such
100#[derive(Clone, Debug)]
101pub enum Event {
102 TitleChanged,
103 BreadcrumbsChanged,
104 CloseTerminal,
105 Bell,
106 Wakeup,
107 BlinkChanged(bool),
108 SelectionsChanged,
109 NewNavigationTarget(Option<MaybeNavigationTarget>),
110 Open(MaybeNavigationTarget),
111}
112
113#[derive(Clone, Debug)]
114pub struct PathLikeTarget {
115 /// File system path, absolute or relative, existing or not.
116 /// Might have line and column number(s) attached as `file.rs:1:23`
117 pub maybe_path: String,
118 /// Current working directory of the terminal
119 pub terminal_dir: Option<PathBuf>,
120}
121
122/// A string inside terminal, potentially useful as a URI that can be opened.
123#[derive(Clone, Debug)]
124pub enum MaybeNavigationTarget {
125 /// HTTP, git, etc. string determined by the [`URL_REGEX`] regex.
126 Url(String),
127 /// File system path, absolute or relative, existing or not.
128 /// Might have line and column number(s) attached as `file.rs:1:23`
129 PathLike(PathLikeTarget),
130}
131
132#[derive(Clone)]
133enum InternalEvent {
134 Resize(TerminalSize),
135 Clear,
136 // FocusNextMatch,
137 Scroll(AlacScroll),
138 ScrollToAlacPoint(AlacPoint),
139 SetSelection(Option<(Selection, AlacPoint)>),
140 UpdateSelection(Point<Pixels>),
141 // Adjusted mouse position, should open
142 FindHyperlink(Point<Pixels>, bool),
143 Copy,
144 // Vi mode events
145 ToggleViMode,
146 ViMotion(ViMotion),
147}
148
149///A translation struct for Alacritty to communicate with us from their event loop
150#[derive(Clone)]
151pub struct ZedListener(pub UnboundedSender<AlacTermEvent>);
152
153impl EventListener for ZedListener {
154 fn send_event(&self, event: AlacTermEvent) {
155 self.0.unbounded_send(event).ok();
156 }
157}
158
159pub fn init(cx: &mut AppContext) {
160 TerminalSettings::register(cx);
161}
162
163#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
164pub struct TerminalSize {
165 pub cell_width: Pixels,
166 pub line_height: Pixels,
167 pub size: Size<Pixels>,
168}
169
170impl TerminalSize {
171 pub fn new(line_height: Pixels, cell_width: Pixels, size: Size<Pixels>) -> Self {
172 TerminalSize {
173 cell_width,
174 line_height,
175 size,
176 }
177 }
178
179 pub fn num_lines(&self) -> usize {
180 (self.size.height / self.line_height).floor() as usize
181 }
182
183 pub fn num_columns(&self) -> usize {
184 (self.size.width / self.cell_width).floor() as usize
185 }
186
187 pub fn height(&self) -> Pixels {
188 self.size.height
189 }
190
191 pub fn width(&self) -> Pixels {
192 self.size.width
193 }
194
195 pub fn cell_width(&self) -> Pixels {
196 self.cell_width
197 }
198
199 pub fn line_height(&self) -> Pixels {
200 self.line_height
201 }
202}
203
204impl Default for TerminalSize {
205 fn default() -> Self {
206 TerminalSize::new(
207 DEBUG_LINE_HEIGHT,
208 DEBUG_CELL_WIDTH,
209 Size {
210 width: DEBUG_TERMINAL_WIDTH,
211 height: DEBUG_TERMINAL_HEIGHT,
212 },
213 )
214 }
215}
216
217impl From<TerminalSize> for WindowSize {
218 fn from(val: TerminalSize) -> Self {
219 WindowSize {
220 num_lines: val.num_lines() as u16,
221 num_cols: val.num_columns() as u16,
222 cell_width: f32::from(val.cell_width()) as u16,
223 cell_height: f32::from(val.line_height()) as u16,
224 }
225 }
226}
227
228impl Dimensions for TerminalSize {
229 /// Note: this is supposed to be for the back buffer's length,
230 /// but we exclusively use it to resize the terminal, which does not
231 /// use this method. We still have to implement it for the trait though,
232 /// hence, this comment.
233 fn total_lines(&self) -> usize {
234 self.screen_lines()
235 }
236
237 fn screen_lines(&self) -> usize {
238 self.num_lines()
239 }
240
241 fn columns(&self) -> usize {
242 self.num_columns()
243 }
244}
245
246#[derive(Error, Debug)]
247pub struct TerminalError {
248 pub directory: Option<PathBuf>,
249 pub shell: Shell,
250 pub source: std::io::Error,
251}
252
253impl TerminalError {
254 pub fn fmt_directory(&self) -> String {
255 self.directory
256 .clone()
257 .map(|path| {
258 match path
259 .into_os_string()
260 .into_string()
261 .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
262 {
263 Ok(s) => s,
264 Err(s) => s,
265 }
266 })
267 .unwrap_or_else(|| {
268 let default_dir =
269 dirs::home_dir().map(|buf| buf.into_os_string().to_string_lossy().to_string());
270 match default_dir {
271 Some(dir) => format!("<none specified, using home directory> {}", dir),
272 None => "<none specified, could not find home directory>".to_string(),
273 }
274 })
275 }
276
277 pub fn shell_to_string(&self) -> String {
278 match &self.shell {
279 Shell::System => "<system shell>".to_string(),
280 Shell::Program(p) => p.to_string(),
281 Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
282 }
283 }
284
285 pub fn fmt_shell(&self) -> String {
286 match &self.shell {
287 Shell::System => "<system defined shell>".to_string(),
288 Shell::Program(s) => s.to_string(),
289 Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
290 }
291 }
292}
293
294impl Display for TerminalError {
295 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296 let dir_string: String = self.fmt_directory();
297 let shell = self.fmt_shell();
298
299 write!(
300 f,
301 "Working directory: {} Shell command: `{}`, IOError: {}",
302 dir_string, shell, self.source
303 )
304 }
305}
306
307// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
308const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
309const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
310const URL_REGEX: &str = r#"(ipfs:|ipns:|magnet:|mailto:|gemini://|gopher://|https://|http://|news:|file://|git://|ssh:|ftp://)[^\u{0000}-\u{001F}\u{007F}-\u{009F}<>"\s{-}\^⟨⟩`]+"#;
311// Optional suffix matches MSBuild diagnostic suffixes for path parsing in PathLikeWithPosition
312// https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-diagnostic-format-for-tasks
313const WORD_REGEX: &str =
314 r#"[\$\+\w.\[\]:/\\@\-~()]+(?:\((?:\d+|\d+,\d+)\))|[\$\+\w.\[\]:/\\@\-~()]+"#;
315
316pub struct TerminalBuilder {
317 terminal: Terminal,
318 events_rx: UnboundedReceiver<AlacTermEvent>,
319}
320
321impl TerminalBuilder {
322 #[allow(clippy::too_many_arguments)]
323 pub fn new(
324 working_directory: Option<PathBuf>,
325 task: Option<TaskState>,
326 shell: Shell,
327 mut env: HashMap<String, String>,
328 cursor_shape: CursorShape,
329 alternate_scroll: AlternateScroll,
330 max_scroll_history_lines: Option<usize>,
331 window: AnyWindowHandle,
332 completion_tx: Sender<()>,
333 cx: &AppContext,
334 ) -> Result<TerminalBuilder> {
335 // TODO: Properly set the current locale,
336 env.entry("LC_ALL".to_string())
337 .or_insert_with(|| "en_US.UTF-8".to_string());
338
339 env.insert("ZED_TERM".to_string(), "true".to_string());
340 env.insert("TERM_PROGRAM".to_string(), "zed".to_string());
341 env.insert(
342 "TERM_PROGRAM_VERSION".to_string(),
343 release_channel::AppVersion::global(cx).to_string(),
344 );
345
346 let pty_options = {
347 let alac_shell = match shell.clone() {
348 Shell::System => None,
349 Shell::Program(program) => {
350 Some(alacritty_terminal::tty::Shell::new(program, Vec::new()))
351 }
352 Shell::WithArguments { program, args } => {
353 Some(alacritty_terminal::tty::Shell::new(program, args))
354 }
355 };
356
357 alacritty_terminal::tty::Options {
358 shell: alac_shell,
359 working_directory: working_directory.clone(),
360 hold: false,
361 env: env.into_iter().collect(),
362 }
363 };
364
365 // Setup Alacritty's env, which modifies the current process's environment
366 alacritty_terminal::tty::setup_env();
367
368 let default_cursor_style = AlacCursorStyle::from(cursor_shape);
369 let scrolling_history = if task.is_some() {
370 // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
371 // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
372 // cause excessive memory usage over time.
373 MAX_SCROLL_HISTORY_LINES
374 } else {
375 max_scroll_history_lines
376 .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
377 .min(MAX_SCROLL_HISTORY_LINES)
378 };
379 let config = Config {
380 scrolling_history,
381 default_cursor_style,
382 ..Config::default()
383 };
384
385 //Spawn a task so the Alacritty EventLoop can communicate with us in a view context
386 //TODO: Remove with a bounded sender which can be dispatched on &self
387 let (events_tx, events_rx) = unbounded();
388 //Set up the terminal...
389 let mut term = Term::new(
390 config.clone(),
391 &TerminalSize::default(),
392 ZedListener(events_tx.clone()),
393 );
394
395 //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
396 if let AlternateScroll::Off = alternate_scroll {
397 term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
398 }
399
400 let term = Arc::new(FairMutex::new(term));
401
402 //Setup the pty...
403 let pty = match tty::new(
404 &pty_options,
405 TerminalSize::default().into(),
406 window.window_id().as_u64(),
407 ) {
408 Ok(pty) => pty,
409 Err(error) => {
410 bail!(TerminalError {
411 directory: working_directory,
412 shell,
413 source: error,
414 });
415 }
416 };
417
418 let pty_info = PtyProcessInfo::new(&pty);
419
420 //And connect them together
421 let event_loop = EventLoop::new(
422 term.clone(),
423 ZedListener(events_tx.clone()),
424 pty,
425 pty_options.hold,
426 false,
427 )?;
428
429 //Kick things off
430 let pty_tx = event_loop.channel();
431 let _io_thread = event_loop.spawn(); // DANGER
432
433 let terminal = Terminal {
434 task,
435 pty_tx: Notifier(pty_tx),
436 completion_tx,
437 term,
438 term_config: config,
439 events: VecDeque::with_capacity(10), //Should never get this high.
440 last_content: Default::default(),
441 last_mouse: None,
442 matches: Vec::new(),
443 selection_head: None,
444 pty_info,
445 breadcrumb_text: String::new(),
446 scroll_px: px(0.),
447 last_mouse_position: None,
448 next_link_id: 0,
449 selection_phase: SelectionPhase::Ended,
450 secondary_pressed: false,
451 hovered_word: false,
452 url_regex: RegexSearch::new(URL_REGEX).unwrap(),
453 word_regex: RegexSearch::new(WORD_REGEX).unwrap(),
454 vi_mode_enabled: false,
455 };
456
457 Ok(TerminalBuilder {
458 terminal,
459 events_rx,
460 })
461 }
462
463 pub fn subscribe(mut self, cx: &ModelContext<Terminal>) -> Terminal {
464 //Event loop
465 cx.spawn(|terminal, mut cx| async move {
466 while let Some(event) = self.events_rx.next().await {
467 terminal.update(&mut cx, |terminal, cx| {
468 //Process the first event immediately for lowered latency
469 terminal.process_event(&event, cx);
470 })?;
471
472 'outer: loop {
473 let mut events = Vec::new();
474 let mut timer = cx
475 .background_executor()
476 .timer(Duration::from_millis(4))
477 .fuse();
478 let mut wakeup = false;
479 loop {
480 futures::select_biased! {
481 _ = timer => break,
482 event = self.events_rx.next() => {
483 if let Some(event) = event {
484 if matches!(event, AlacTermEvent::Wakeup) {
485 wakeup = true;
486 } else {
487 events.push(event);
488 }
489
490 if events.len() > 100 {
491 break;
492 }
493 } else {
494 break;
495 }
496 },
497 }
498 }
499
500 if events.is_empty() && !wakeup {
501 smol::future::yield_now().await;
502 break 'outer;
503 }
504
505 terminal.update(&mut cx, |this, cx| {
506 if wakeup {
507 this.process_event(&AlacTermEvent::Wakeup, cx);
508 }
509
510 for event in events {
511 this.process_event(&event, cx);
512 }
513 })?;
514 smol::future::yield_now().await;
515 }
516 }
517
518 anyhow::Ok(())
519 })
520 .detach();
521
522 self.terminal
523 }
524}
525
526#[derive(Debug, Clone, Deserialize, Serialize)]
527pub struct IndexedCell {
528 pub point: AlacPoint,
529 pub cell: Cell,
530}
531
532impl Deref for IndexedCell {
533 type Target = Cell;
534
535 #[inline]
536 fn deref(&self) -> &Cell {
537 &self.cell
538 }
539}
540
541// TODO: Un-pub
542#[derive(Clone)]
543pub struct TerminalContent {
544 pub cells: Vec<IndexedCell>,
545 pub mode: TermMode,
546 pub display_offset: usize,
547 pub selection_text: Option<String>,
548 pub selection: Option<SelectionRange>,
549 pub cursor: RenderableCursor,
550 pub cursor_char: char,
551 pub size: TerminalSize,
552 pub last_hovered_word: Option<HoveredWord>,
553}
554
555#[derive(Clone)]
556pub struct HoveredWord {
557 pub word: String,
558 pub word_match: RangeInclusive<AlacPoint>,
559 pub id: usize,
560}
561
562impl Default for TerminalContent {
563 fn default() -> Self {
564 TerminalContent {
565 cells: Default::default(),
566 mode: Default::default(),
567 display_offset: Default::default(),
568 selection_text: Default::default(),
569 selection: Default::default(),
570 cursor: RenderableCursor {
571 shape: alacritty_terminal::vte::ansi::CursorShape::Block,
572 point: AlacPoint::new(Line(0), Column(0)),
573 },
574 cursor_char: Default::default(),
575 size: Default::default(),
576 last_hovered_word: None,
577 }
578 }
579}
580
581#[derive(PartialEq, Eq)]
582pub enum SelectionPhase {
583 Selecting,
584 Ended,
585}
586
587pub struct Terminal {
588 pty_tx: Notifier,
589 completion_tx: Sender<()>,
590 term: Arc<FairMutex<Term<ZedListener>>>,
591 term_config: Config,
592 events: VecDeque<InternalEvent>,
593 /// This is only used for mouse mode cell change detection
594 last_mouse: Option<(AlacPoint, AlacDirection)>,
595 /// This is only used for terminal hovered word checking
596 last_mouse_position: Option<Point<Pixels>>,
597 pub matches: Vec<RangeInclusive<AlacPoint>>,
598 pub last_content: TerminalContent,
599 pub selection_head: Option<AlacPoint>,
600 pub breadcrumb_text: String,
601 pub pty_info: PtyProcessInfo,
602 scroll_px: Pixels,
603 next_link_id: usize,
604 selection_phase: SelectionPhase,
605 secondary_pressed: bool,
606 hovered_word: bool,
607 url_regex: RegexSearch,
608 word_regex: RegexSearch,
609 task: Option<TaskState>,
610 vi_mode_enabled: bool,
611}
612
613pub struct TaskState {
614 pub id: TaskId,
615 pub full_label: String,
616 pub label: String,
617 pub command_label: String,
618 pub status: TaskStatus,
619 pub completion_rx: Receiver<()>,
620 pub hide: HideStrategy,
621}
622
623/// A status of the current terminal tab's task.
624#[derive(Debug, Clone, Copy, PartialEq, Eq)]
625pub enum TaskStatus {
626 /// The task had been started, but got cancelled or somehow otherwise it did not
627 /// report its exit code before the terminal event loop was shut down.
628 Unknown,
629 /// The task is started and running currently.
630 Running,
631 /// After the start, the task stopped running and reported its error code back.
632 Completed { success: bool },
633}
634
635impl TaskStatus {
636 fn register_terminal_exit(&mut self) {
637 if self == &Self::Running {
638 *self = Self::Unknown;
639 }
640 }
641
642 fn register_task_exit(&mut self, error_code: i32) {
643 *self = TaskStatus::Completed {
644 success: error_code == 0,
645 };
646 }
647}
648
649impl Terminal {
650 fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
651 match event {
652 AlacTermEvent::Title(title) => {
653 self.breadcrumb_text = title.to_string();
654 cx.emit(Event::BreadcrumbsChanged);
655 }
656 AlacTermEvent::ResetTitle => {
657 self.breadcrumb_text = String::new();
658 cx.emit(Event::BreadcrumbsChanged);
659 }
660 AlacTermEvent::ClipboardStore(_, data) => {
661 cx.write_to_clipboard(ClipboardItem::new_string(data.to_string()))
662 }
663 AlacTermEvent::ClipboardLoad(_, format) => {
664 self.write_to_pty(
665 match &cx.read_from_clipboard().and_then(|item| item.text()) {
666 // The terminal only supports pasting strings, not images.
667 Some(text) => format(text),
668 _ => format(""),
669 },
670 )
671 }
672 AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
673 AlacTermEvent::TextAreaSizeRequest(format) => {
674 self.write_to_pty(format(self.last_content.size.into()))
675 }
676 AlacTermEvent::CursorBlinkingChange => {
677 let terminal = self.term.lock();
678 let blinking = terminal.cursor_style().blinking;
679 cx.emit(Event::BlinkChanged(blinking));
680 }
681 AlacTermEvent::Bell => {
682 cx.emit(Event::Bell);
683 }
684 AlacTermEvent::Exit => self.register_task_finished(None, cx),
685 AlacTermEvent::MouseCursorDirty => {
686 //NOOP, Handled in render
687 }
688 AlacTermEvent::Wakeup => {
689 cx.emit(Event::Wakeup);
690
691 if self.pty_info.has_changed() {
692 cx.emit(Event::TitleChanged);
693 }
694 }
695 AlacTermEvent::ColorRequest(index, format) => {
696 // It's important that the color request is processed here to retain relative order
697 // with other PTY writes. Otherwise applications might witness out-of-order
698 // responses to requests. For example: An application sending `OSC 11 ; ? ST`
699 // (color request) followed by `CSI c` (request device attributes) would receive
700 // the response to `CSI c` first.
701 // Instead of locking, we could store the colors in `self.last_content`. But then
702 // we might respond with out of date value if a "set color" sequence is immediately
703 // followed by a color request sequence.
704 let color = self.term.lock().colors()[*index].unwrap_or_else(|| {
705 to_alac_rgb(get_color_at_index(*index, cx.theme().as_ref()))
706 });
707 self.write_to_pty(format(color));
708 }
709 AlacTermEvent::ChildExit(error_code) => {
710 self.register_task_finished(Some(*error_code), cx);
711 }
712 }
713 }
714
715 pub fn selection_started(&self) -> bool {
716 self.selection_phase == SelectionPhase::Selecting
717 }
718
719 pub fn get_cwd(&self) -> Option<PathBuf> {
720 self.pty_info.current.as_ref().map(|info| info.cwd.clone())
721 }
722
723 ///Takes events from Alacritty and translates them to behavior on this view
724 fn process_terminal_event(
725 &mut self,
726 event: &InternalEvent,
727 term: &mut Term<ZedListener>,
728 cx: &mut ModelContext<Self>,
729 ) {
730 match event {
731 InternalEvent::Resize(mut new_size) => {
732 new_size.size.height = cmp::max(new_size.line_height, new_size.height());
733 new_size.size.width = cmp::max(new_size.cell_width, new_size.width());
734
735 self.last_content.size = new_size;
736
737 self.pty_tx.0.send(Msg::Resize(new_size.into())).ok();
738
739 term.resize(new_size);
740 }
741 InternalEvent::Clear => {
742 // Clear back buffer
743 term.clear_screen(ClearMode::Saved);
744
745 let cursor = term.grid().cursor.point;
746
747 // Clear the lines above
748 term.grid_mut().reset_region(..cursor.line);
749
750 // Copy the current line up
751 let line = term.grid()[cursor.line][..Column(term.grid().columns())]
752 .iter()
753 .cloned()
754 .enumerate()
755 .collect::<Vec<(usize, Cell)>>();
756
757 for (i, cell) in line {
758 term.grid_mut()[Line(0)][Column(i)] = cell;
759 }
760
761 // Reset the cursor
762 term.grid_mut().cursor.point =
763 AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
764 let new_cursor = term.grid().cursor.point;
765
766 // Clear the lines below the new cursor
767 if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
768 term.grid_mut().reset_region((new_cursor.line + 1)..);
769 }
770
771 cx.emit(Event::Wakeup);
772 }
773 InternalEvent::Scroll(scroll) => {
774 term.scroll_display(*scroll);
775 self.refresh_hovered_word();
776
777 if self.vi_mode_enabled {
778 match *scroll {
779 AlacScroll::Delta(delta) => {
780 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, delta);
781 }
782 AlacScroll::PageUp => {
783 let lines = term.screen_lines() as i32;
784 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
785 }
786 AlacScroll::PageDown => {
787 let lines = -(term.screen_lines() as i32);
788 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
789 }
790 AlacScroll::Top => {
791 let point = AlacPoint::new(term.topmost_line(), Column(0));
792 term.vi_mode_cursor = ViModeCursor::new(point);
793 }
794 AlacScroll::Bottom => {
795 let point = AlacPoint::new(term.bottommost_line(), Column(0));
796 term.vi_mode_cursor = ViModeCursor::new(point);
797 }
798 }
799 if let Some(mut selection) = term.selection.take() {
800 let point = term.vi_mode_cursor.point;
801 selection.update(point, AlacDirection::Right);
802 term.selection = Some(selection);
803
804 #[cfg(target_os = "linux")]
805 if let Some(selection_text) = term.selection_to_string() {
806 cx.write_to_primary(ClipboardItem::new_string(selection_text));
807 }
808
809 self.selection_head = Some(point);
810 cx.emit(Event::SelectionsChanged)
811 }
812 }
813 }
814 InternalEvent::SetSelection(selection) => {
815 term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
816
817 #[cfg(target_os = "linux")]
818 if let Some(selection_text) = term.selection_to_string() {
819 cx.write_to_primary(ClipboardItem::new_string(selection_text));
820 }
821
822 if let Some((_, head)) = selection {
823 self.selection_head = Some(*head);
824 }
825 cx.emit(Event::SelectionsChanged)
826 }
827 InternalEvent::UpdateSelection(position) => {
828 if let Some(mut selection) = term.selection.take() {
829 let (point, side) = grid_point_and_side(
830 *position,
831 self.last_content.size,
832 term.grid().display_offset(),
833 );
834
835 selection.update(point, side);
836 term.selection = Some(selection);
837
838 #[cfg(target_os = "linux")]
839 if let Some(selection_text) = term.selection_to_string() {
840 cx.write_to_primary(ClipboardItem::new_string(selection_text));
841 }
842
843 self.selection_head = Some(point);
844 cx.emit(Event::SelectionsChanged)
845 }
846 }
847
848 InternalEvent::Copy => {
849 if let Some(txt) = term.selection_to_string() {
850 cx.write_to_clipboard(ClipboardItem::new_string(txt))
851 }
852 }
853 InternalEvent::ScrollToAlacPoint(point) => {
854 term.scroll_to_point(*point);
855 self.refresh_hovered_word();
856 }
857 InternalEvent::ToggleViMode => {
858 self.vi_mode_enabled = !self.vi_mode_enabled;
859 term.toggle_vi_mode();
860 }
861 InternalEvent::ViMotion(motion) => {
862 term.vi_motion(*motion);
863 }
864 InternalEvent::FindHyperlink(position, open) => {
865 let prev_hovered_word = self.last_content.last_hovered_word.take();
866
867 let point = grid_point(
868 *position,
869 self.last_content.size,
870 term.grid().display_offset(),
871 )
872 .grid_clamp(term, Boundary::Grid);
873
874 let link = term.grid().index(point).hyperlink();
875 let found_word = if link.is_some() {
876 let mut min_index = point;
877 loop {
878 let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
879 if new_min_index == min_index
880 || term.grid().index(new_min_index).hyperlink() != link
881 {
882 break;
883 } else {
884 min_index = new_min_index
885 }
886 }
887
888 let mut max_index = point;
889 loop {
890 let new_max_index = max_index.add(term, Boundary::Cursor, 1);
891 if new_max_index == max_index
892 || term.grid().index(new_max_index).hyperlink() != link
893 {
894 break;
895 } else {
896 max_index = new_max_index
897 }
898 }
899
900 let url = link.unwrap().uri().to_owned();
901 let url_match = min_index..=max_index;
902
903 Some((url, true, url_match))
904 } else if let Some(url_match) = regex_match_at(term, point, &mut self.url_regex) {
905 let url = term.bounds_to_string(*url_match.start(), *url_match.end());
906 Some((url, true, url_match))
907 } else if let Some(word_match) = regex_match_at(term, point, &mut self.word_regex) {
908 let file_path = term.bounds_to_string(*word_match.start(), *word_match.end());
909
910 let (sanitized_match, sanitized_word) =
911 if file_path.starts_with('[') && file_path.ends_with(']') {
912 (
913 Match::new(
914 word_match.start().add(term, Boundary::Cursor, 1),
915 word_match.end().sub(term, Boundary::Cursor, 1),
916 ),
917 file_path[1..file_path.len() - 1].to_owned(),
918 )
919 } else {
920 (word_match, file_path)
921 };
922
923 Some((sanitized_word, false, sanitized_match))
924 } else {
925 None
926 };
927
928 match found_word {
929 Some((maybe_url_or_path, is_url, url_match)) => {
930 if *open {
931 let target = if is_url {
932 MaybeNavigationTarget::Url(maybe_url_or_path)
933 } else {
934 MaybeNavigationTarget::PathLike(PathLikeTarget {
935 maybe_path: maybe_url_or_path,
936 terminal_dir: self.get_cwd(),
937 })
938 };
939 cx.emit(Event::Open(target));
940 } else {
941 self.update_selected_word(
942 prev_hovered_word,
943 url_match,
944 maybe_url_or_path,
945 is_url,
946 cx,
947 );
948 }
949 self.hovered_word = true;
950 }
951 None => {
952 if self.hovered_word {
953 cx.emit(Event::NewNavigationTarget(None));
954 }
955 self.hovered_word = false;
956 }
957 }
958 }
959 }
960 }
961
962 fn update_selected_word(
963 &mut self,
964 prev_word: Option<HoveredWord>,
965 word_match: RangeInclusive<AlacPoint>,
966 word: String,
967 is_url: bool,
968 cx: &mut ModelContext<Self>,
969 ) {
970 if let Some(prev_word) = prev_word {
971 if prev_word.word == word && prev_word.word_match == word_match {
972 self.last_content.last_hovered_word = Some(HoveredWord {
973 word,
974 word_match,
975 id: prev_word.id,
976 });
977 return;
978 }
979 }
980
981 self.last_content.last_hovered_word = Some(HoveredWord {
982 word: word.clone(),
983 word_match,
984 id: self.next_link_id(),
985 });
986 let navigation_target = if is_url {
987 MaybeNavigationTarget::Url(word)
988 } else {
989 MaybeNavigationTarget::PathLike(PathLikeTarget {
990 maybe_path: word,
991 terminal_dir: self.get_cwd(),
992 })
993 };
994 cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
995 }
996
997 fn next_link_id(&mut self) -> usize {
998 let res = self.next_link_id;
999 self.next_link_id = self.next_link_id.wrapping_add(1);
1000 res
1001 }
1002
1003 pub fn last_content(&self) -> &TerminalContent {
1004 &self.last_content
1005 }
1006
1007 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
1008 self.term_config.default_cursor_style = cursor_shape.into();
1009 self.term.lock().set_options(self.term_config.clone());
1010 }
1011
1012 pub fn total_lines(&self) -> usize {
1013 let term = self.term.clone();
1014 let terminal = term.lock_unfair();
1015 terminal.total_lines()
1016 }
1017
1018 pub fn viewport_lines(&self) -> usize {
1019 let term = self.term.clone();
1020 let terminal = term.lock_unfair();
1021 terminal.screen_lines()
1022 }
1023
1024 //To test:
1025 //- Activate match on terminal (scrolling and selection)
1026 //- Editor search snapping behavior
1027
1028 pub fn activate_match(&mut self, index: usize) {
1029 if let Some(search_match) = self.matches.get(index).cloned() {
1030 self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1031
1032 self.events
1033 .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1034 }
1035 }
1036
1037 pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1038 let matches_to_select = self
1039 .matches
1040 .iter()
1041 .filter(|self_match| matches.contains(self_match))
1042 .cloned()
1043 .collect::<Vec<_>>();
1044 for match_to_select in matches_to_select {
1045 self.set_selection(Some((
1046 make_selection(&match_to_select),
1047 *match_to_select.end(),
1048 )));
1049 }
1050 }
1051
1052 pub fn select_all(&mut self) {
1053 let term = self.term.lock();
1054 let start = AlacPoint::new(term.topmost_line(), Column(0));
1055 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1056 drop(term);
1057 self.set_selection(Some((make_selection(&(start..=end)), end)));
1058 }
1059
1060 fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1061 self.events
1062 .push_back(InternalEvent::SetSelection(selection));
1063 }
1064
1065 pub fn copy(&mut self) {
1066 self.events.push_back(InternalEvent::Copy);
1067 }
1068
1069 pub fn clear(&mut self) {
1070 self.events.push_back(InternalEvent::Clear)
1071 }
1072
1073 pub fn scroll_line_up(&mut self) {
1074 self.events
1075 .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1076 }
1077
1078 pub fn scroll_up_by(&mut self, lines: usize) {
1079 self.events
1080 .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1081 }
1082
1083 pub fn scroll_line_down(&mut self) {
1084 self.events
1085 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1086 }
1087
1088 pub fn scroll_down_by(&mut self, lines: usize) {
1089 self.events
1090 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1091 }
1092
1093 pub fn scroll_page_up(&mut self) {
1094 self.events
1095 .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1096 }
1097
1098 pub fn scroll_page_down(&mut self) {
1099 self.events
1100 .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1101 }
1102
1103 pub fn scroll_to_top(&mut self) {
1104 self.events
1105 .push_back(InternalEvent::Scroll(AlacScroll::Top));
1106 }
1107
1108 pub fn scroll_to_bottom(&mut self) {
1109 self.events
1110 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1111 }
1112
1113 ///Resize the terminal and the PTY.
1114 pub fn set_size(&mut self, new_size: TerminalSize) {
1115 if self.last_content.size != new_size {
1116 self.events.push_back(InternalEvent::Resize(new_size))
1117 }
1118 }
1119
1120 ///Write the Input payload to the tty.
1121 fn write_to_pty(&self, input: String) {
1122 self.pty_tx.notify(input.into_bytes());
1123 }
1124
1125 fn write_bytes_to_pty(&self, input: Vec<u8>) {
1126 self.pty_tx.notify(input);
1127 }
1128
1129 pub fn input(&mut self, input: String) {
1130 self.events
1131 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1132 self.events.push_back(InternalEvent::SetSelection(None));
1133
1134 self.write_to_pty(input);
1135 }
1136
1137 pub fn input_bytes(&mut self, input: Vec<u8>) {
1138 self.events
1139 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1140 self.events.push_back(InternalEvent::SetSelection(None));
1141
1142 self.write_bytes_to_pty(input);
1143 }
1144
1145 pub fn toggle_vi_mode(&mut self) {
1146 self.events.push_back(InternalEvent::ToggleViMode);
1147 }
1148
1149 pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1150 if !self.vi_mode_enabled {
1151 return;
1152 }
1153
1154 let mut key = keystroke.key.clone();
1155 if keystroke.modifiers.shift {
1156 key = key.to_uppercase();
1157 }
1158
1159 let motion: Option<ViMotion> = match key.as_str() {
1160 "h" => Some(ViMotion::Left),
1161 "j" => Some(ViMotion::Down),
1162 "k" => Some(ViMotion::Up),
1163 "l" => Some(ViMotion::Right),
1164 "w" => Some(ViMotion::WordRight),
1165 "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1166 "e" => Some(ViMotion::WordRightEnd),
1167 "%" => Some(ViMotion::Bracket),
1168 "$" => Some(ViMotion::Last),
1169 "0" => Some(ViMotion::First),
1170 "^" => Some(ViMotion::FirstOccupied),
1171 "H" => Some(ViMotion::High),
1172 "M" => Some(ViMotion::Middle),
1173 "L" => Some(ViMotion::Low),
1174 _ => None,
1175 };
1176
1177 if let Some(motion) = motion {
1178 let cursor = self.last_content.cursor.point;
1179 let cursor_pos = Point {
1180 x: cursor.column.0 as f32 * self.last_content.size.cell_width,
1181 y: cursor.line.0 as f32 * self.last_content.size.line_height,
1182 };
1183 self.events
1184 .push_back(InternalEvent::UpdateSelection(cursor_pos));
1185 self.events.push_back(InternalEvent::ViMotion(motion));
1186 return;
1187 }
1188
1189 let scroll_motion = match key.as_str() {
1190 "g" => Some(AlacScroll::Top),
1191 "G" => Some(AlacScroll::Bottom),
1192 "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1193 "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1194 "d" if keystroke.modifiers.control => {
1195 let amount = self.last_content.size.line_height().to_f64() as i32 / 2;
1196 Some(AlacScroll::Delta(-amount))
1197 }
1198 "u" if keystroke.modifiers.control => {
1199 let amount = self.last_content.size.line_height().to_f64() as i32 / 2;
1200 Some(AlacScroll::Delta(amount))
1201 }
1202 _ => None,
1203 };
1204
1205 if let Some(scroll_motion) = scroll_motion {
1206 self.events.push_back(InternalEvent::Scroll(scroll_motion));
1207 return;
1208 }
1209
1210 match key.as_str() {
1211 "v" => {
1212 let point = self.last_content.cursor.point;
1213 let selection_type = SelectionType::Simple;
1214 let side = AlacDirection::Right;
1215 let selection = Selection::new(selection_type, point, side);
1216 self.events
1217 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1218 return;
1219 }
1220
1221 "escape" => {
1222 self.events.push_back(InternalEvent::SetSelection(None));
1223 return;
1224 }
1225
1226 "y" => {
1227 self.events.push_back(InternalEvent::Copy);
1228 self.events.push_back(InternalEvent::SetSelection(None));
1229 return;
1230 }
1231
1232 "i" => {
1233 self.scroll_to_bottom();
1234 self.toggle_vi_mode();
1235 return;
1236 }
1237 _ => {}
1238 }
1239 }
1240
1241 pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1242 if self.vi_mode_enabled {
1243 self.vi_motion(keystroke);
1244 return true;
1245 }
1246
1247 // Keep default terminal behavior
1248 let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1249 if let Some(esc) = esc {
1250 self.input(esc);
1251 true
1252 } else {
1253 false
1254 }
1255 }
1256
1257 pub fn try_modifiers_change(&mut self, modifiers: &Modifiers) -> bool {
1258 let changed = self.secondary_pressed != modifiers.secondary();
1259 if !self.secondary_pressed && modifiers.secondary() {
1260 self.refresh_hovered_word();
1261 }
1262 self.secondary_pressed = modifiers.secondary();
1263 changed
1264 }
1265
1266 ///Paste text into the terminal
1267 pub fn paste(&mut self, text: &str) {
1268 let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1269 format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1270 } else {
1271 text.replace("\r\n", "\r").replace('\n', "\r")
1272 };
1273
1274 self.input(paste_text);
1275 }
1276
1277 pub fn sync(&mut self, cx: &mut ModelContext<Self>) {
1278 let term = self.term.clone();
1279 let mut terminal = term.lock_unfair();
1280 //Note that the ordering of events matters for event processing
1281 while let Some(e) = self.events.pop_front() {
1282 self.process_terminal_event(&e, &mut terminal, cx)
1283 }
1284
1285 self.last_content = Self::make_content(&terminal, &self.last_content);
1286 }
1287
1288 fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1289 let content = term.renderable_content();
1290 TerminalContent {
1291 cells: content
1292 .display_iter
1293 //TODO: Add this once there's a way to retain empty lines
1294 // .filter(|ic| {
1295 // !ic.flags.contains(Flags::HIDDEN)
1296 // && !(ic.bg == Named(NamedColor::Background)
1297 // && ic.c == ' '
1298 // && !ic.flags.contains(Flags::INVERSE))
1299 // })
1300 .map(|ic| IndexedCell {
1301 point: ic.point,
1302 cell: ic.cell.clone(),
1303 })
1304 .collect::<Vec<IndexedCell>>(),
1305 mode: content.mode,
1306 display_offset: content.display_offset,
1307 selection_text: term.selection_to_string(),
1308 selection: content.selection,
1309 cursor: content.cursor,
1310 cursor_char: term.grid()[content.cursor.point].c,
1311 size: last_content.size,
1312 last_hovered_word: last_content.last_hovered_word.clone(),
1313 }
1314 }
1315
1316 pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1317 let term = self.term.clone();
1318 let terminal = term.lock_unfair();
1319
1320 let mut lines = Vec::new();
1321 let mut current_line = terminal.bottommost_line();
1322 while lines.len() < n {
1323 let mut line_buffer = String::new();
1324 for cell in &terminal.grid()[current_line] {
1325 line_buffer.push(cell.c);
1326 }
1327 let line = line_buffer.trim_end();
1328 if !line.is_empty() {
1329 lines.push(line.to_string());
1330 }
1331
1332 if current_line == terminal.topmost_line() {
1333 break;
1334 }
1335 current_line = Line(current_line.0 - 1);
1336 }
1337 lines.reverse();
1338 lines
1339 }
1340
1341 pub fn focus_in(&self) {
1342 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1343 self.write_to_pty("\x1b[I".to_string());
1344 }
1345 }
1346
1347 pub fn focus_out(&mut self) {
1348 self.last_mouse_position = None;
1349 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1350 self.write_to_pty("\x1b[O".to_string());
1351 }
1352 }
1353
1354 pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1355 match self.last_mouse {
1356 Some((old_point, old_side)) => {
1357 if old_point == point && old_side == side {
1358 false
1359 } else {
1360 self.last_mouse = Some((point, side));
1361 true
1362 }
1363 }
1364 None => {
1365 self.last_mouse = Some((point, side));
1366 true
1367 }
1368 }
1369 }
1370
1371 pub fn mouse_mode(&self, shift: bool) -> bool {
1372 self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1373 }
1374
1375 pub fn mouse_move(&mut self, e: &MouseMoveEvent, origin: Point<Pixels>) {
1376 let position = e.position - origin;
1377 self.last_mouse_position = Some(position);
1378 if self.mouse_mode(e.modifiers.shift) {
1379 let (point, side) = grid_point_and_side(
1380 position,
1381 self.last_content.size,
1382 self.last_content.display_offset,
1383 );
1384
1385 if self.mouse_changed(point, side) {
1386 if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
1387 self.pty_tx.notify(bytes);
1388 }
1389 }
1390 } else if self.secondary_pressed {
1391 self.word_from_position(Some(position));
1392 }
1393 }
1394
1395 fn word_from_position(&mut self, position: Option<Point<Pixels>>) {
1396 if self.selection_phase == SelectionPhase::Selecting {
1397 self.last_content.last_hovered_word = None;
1398 } else if let Some(position) = position {
1399 self.events
1400 .push_back(InternalEvent::FindHyperlink(position, false));
1401 }
1402 }
1403
1404 pub fn mouse_drag(
1405 &mut self,
1406 e: &MouseMoveEvent,
1407 origin: Point<Pixels>,
1408 region: Bounds<Pixels>,
1409 ) {
1410 let position = e.position - origin;
1411 self.last_mouse_position = Some(position);
1412
1413 if !self.mouse_mode(e.modifiers.shift) {
1414 self.selection_phase = SelectionPhase::Selecting;
1415 // Alacritty has the same ordering, of first updating the selection
1416 // then scrolling 15ms later
1417 self.events
1418 .push_back(InternalEvent::UpdateSelection(position));
1419
1420 // Doesn't make sense to scroll the alt screen
1421 if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1422 let scroll_delta = match self.drag_line_delta(e, region) {
1423 Some(value) => value,
1424 None => return,
1425 };
1426
1427 let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
1428
1429 self.events
1430 .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1431 }
1432 }
1433 }
1434
1435 fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<Pixels> {
1436 //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1437 let top = region.origin.y + (self.last_content.size.line_height * 2.);
1438 let bottom = region.lower_left().y - (self.last_content.size.line_height * 2.);
1439 let scroll_delta = if e.position.y < top {
1440 (top - e.position.y).pow(1.1)
1441 } else if e.position.y > bottom {
1442 -((e.position.y - bottom).pow(1.1))
1443 } else {
1444 return None; //Nothing to do
1445 };
1446 Some(scroll_delta)
1447 }
1448
1449 pub fn mouse_down(
1450 &mut self,
1451 e: &MouseDownEvent,
1452 origin: Point<Pixels>,
1453 _cx: &mut ModelContext<Self>,
1454 ) {
1455 let position = e.position - origin;
1456 let point = grid_point(
1457 position,
1458 self.last_content.size,
1459 self.last_content.display_offset,
1460 );
1461
1462 if self.mouse_mode(e.modifiers.shift) {
1463 if let Some(bytes) =
1464 mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1465 {
1466 self.pty_tx.notify(bytes);
1467 }
1468 } else {
1469 match e.button {
1470 MouseButton::Left => {
1471 let position = e.position - origin;
1472 let (point, side) = grid_point_and_side(
1473 position,
1474 self.last_content.size,
1475 self.last_content.display_offset,
1476 );
1477
1478 let selection_type = match e.click_count {
1479 0 => return, //This is a release
1480 1 => Some(SelectionType::Simple),
1481 2 => Some(SelectionType::Semantic),
1482 3 => Some(SelectionType::Lines),
1483 _ => None,
1484 };
1485
1486 let selection = selection_type
1487 .map(|selection_type| Selection::new(selection_type, point, side));
1488
1489 if let Some(sel) = selection {
1490 self.events
1491 .push_back(InternalEvent::SetSelection(Some((sel, point))));
1492 }
1493 }
1494 #[cfg(target_os = "linux")]
1495 MouseButton::Middle => {
1496 if let Some(item) = _cx.read_from_primary() {
1497 let text = item.text().unwrap_or_default().to_string();
1498 self.input(text);
1499 }
1500 }
1501 _ => {}
1502 }
1503 }
1504 }
1505
1506 pub fn mouse_up(&mut self, e: &MouseUpEvent, origin: Point<Pixels>, cx: &ModelContext<Self>) {
1507 let setting = TerminalSettings::get_global(cx);
1508
1509 let position = e.position - origin;
1510 if self.mouse_mode(e.modifiers.shift) {
1511 let point = grid_point(
1512 position,
1513 self.last_content.size,
1514 self.last_content.display_offset,
1515 );
1516
1517 if let Some(bytes) =
1518 mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1519 {
1520 self.pty_tx.notify(bytes);
1521 }
1522 } else {
1523 if e.button == MouseButton::Left && setting.copy_on_select {
1524 self.copy();
1525 }
1526
1527 //Hyperlinks
1528 if self.selection_phase == SelectionPhase::Ended {
1529 let mouse_cell_index = content_index_for_mouse(position, &self.last_content.size);
1530 if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1531 cx.open_url(link.uri());
1532 } else if self.secondary_pressed {
1533 self.events
1534 .push_back(InternalEvent::FindHyperlink(position, true));
1535 }
1536 }
1537 }
1538
1539 self.selection_phase = SelectionPhase::Ended;
1540 self.last_mouse = None;
1541 }
1542
1543 ///Scroll the terminal
1544 pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent, origin: Point<Pixels>) {
1545 let mouse_mode = self.mouse_mode(e.shift);
1546
1547 if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1548 if mouse_mode {
1549 let point = grid_point(
1550 e.position - origin,
1551 self.last_content.size,
1552 self.last_content.display_offset,
1553 );
1554
1555 if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1556 {
1557 for scroll in scrolls {
1558 self.pty_tx.notify(scroll);
1559 }
1560 };
1561 } else if self
1562 .last_content
1563 .mode
1564 .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1565 && !e.shift
1566 {
1567 self.pty_tx.notify(alt_scroll(scroll_lines))
1568 } else if scroll_lines != 0 {
1569 let scroll = AlacScroll::Delta(scroll_lines);
1570
1571 self.events.push_back(InternalEvent::Scroll(scroll));
1572 }
1573 }
1574 }
1575
1576 fn refresh_hovered_word(&mut self) {
1577 self.word_from_position(self.last_mouse_position);
1578 }
1579
1580 fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1581 let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1582 let line_height = self.last_content.size.line_height;
1583 match e.touch_phase {
1584 /* Reset scroll state on started */
1585 TouchPhase::Started => {
1586 self.scroll_px = px(0.);
1587 None
1588 }
1589 /* Calculate the appropriate scroll lines */
1590 TouchPhase::Moved => {
1591 let old_offset = (self.scroll_px / line_height) as i32;
1592
1593 self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1594
1595 let new_offset = (self.scroll_px / line_height) as i32;
1596
1597 // Whenever we hit the edges, reset our stored scroll to 0
1598 // so we can respond to changes in direction quickly
1599 self.scroll_px %= self.last_content.size.height();
1600
1601 Some(new_offset - old_offset)
1602 }
1603 TouchPhase::Ended => None,
1604 }
1605 }
1606
1607 pub fn find_matches(
1608 &self,
1609 mut searcher: RegexSearch,
1610 cx: &ModelContext<Self>,
1611 ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1612 let term = self.term.clone();
1613 cx.background_executor().spawn(async move {
1614 let term = term.lock();
1615
1616 all_search_matches(&term, &mut searcher).collect()
1617 })
1618 }
1619
1620 pub fn working_directory(&self) -> Option<PathBuf> {
1621 self.pty_info
1622 .current
1623 .as_ref()
1624 .map(|process| process.cwd.clone())
1625 }
1626
1627 pub fn title(&self, truncate: bool) -> String {
1628 const MAX_CHARS: usize = 25;
1629 match &self.task {
1630 Some(task_state) => {
1631 if truncate {
1632 truncate_and_trailoff(&task_state.label, MAX_CHARS)
1633 } else {
1634 task_state.full_label.clone()
1635 }
1636 }
1637 None => self
1638 .pty_info
1639 .current
1640 .as_ref()
1641 .map(|fpi| {
1642 let process_file = fpi
1643 .cwd
1644 .file_name()
1645 .map(|name| name.to_string_lossy().to_string())
1646 .unwrap_or_default();
1647
1648 let argv = fpi.argv.clone();
1649 let process_name = format!(
1650 "{}{}",
1651 fpi.name,
1652 if !argv.is_empty() {
1653 format!(" {}", (argv[1..]).join(" "))
1654 } else {
1655 "".to_string()
1656 }
1657 );
1658 let (process_file, process_name) = if truncate {
1659 (
1660 truncate_and_trailoff(&process_file, MAX_CHARS),
1661 truncate_and_trailoff(&process_name, MAX_CHARS),
1662 )
1663 } else {
1664 (process_file, process_name)
1665 };
1666 format!("{process_file} — {process_name}")
1667 })
1668 .unwrap_or_else(|| "Terminal".to_string()),
1669 }
1670 }
1671
1672 pub fn can_navigate_to_selected_word(&self) -> bool {
1673 self.secondary_pressed && self.hovered_word
1674 }
1675
1676 pub fn task(&self) -> Option<&TaskState> {
1677 self.task.as_ref()
1678 }
1679
1680 pub fn wait_for_completed_task(&self, cx: &AppContext) -> Task<()> {
1681 if let Some(task) = self.task() {
1682 if task.status == TaskStatus::Running {
1683 let mut completion_receiver = task.completion_rx.clone();
1684 return cx.spawn(|_| async move {
1685 completion_receiver.next().await;
1686 });
1687 }
1688 }
1689 Task::ready(())
1690 }
1691
1692 fn register_task_finished(
1693 &mut self,
1694 error_code: Option<i32>,
1695 cx: &mut ModelContext<'_, Terminal>,
1696 ) {
1697 self.completion_tx.try_send(()).ok();
1698 let task = match &mut self.task {
1699 Some(task) => task,
1700 None => {
1701 if error_code.is_none() {
1702 cx.emit(Event::CloseTerminal);
1703 }
1704 return;
1705 }
1706 };
1707 if task.status != TaskStatus::Running {
1708 return;
1709 }
1710 match error_code {
1711 Some(error_code) => {
1712 task.status.register_task_exit(error_code);
1713 }
1714 None => {
1715 task.status.register_terminal_exit();
1716 }
1717 };
1718
1719 let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1720 // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1721 // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1722 // when Zed task finishes and no more output is made.
1723 // After the task summary is output once, no more text is appended to the terminal.
1724 unsafe { append_text_to_term(&mut self.term.lock(), &[&task_line, &command_line]) };
1725 match task.hide {
1726 HideStrategy::Never => {}
1727 HideStrategy::Always => {
1728 cx.emit(Event::CloseTerminal);
1729 }
1730 HideStrategy::OnSuccess => {
1731 if finished_successfully {
1732 cx.emit(Event::CloseTerminal);
1733 }
1734 }
1735 }
1736 }
1737}
1738
1739const TASK_DELIMITER: &str = "⏵ ";
1740fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1741 let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1742 let (success, task_line) = match error_code {
1743 Some(0) => {
1744 (true, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"))
1745 }
1746 Some(error_code) => {
1747 (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"))
1748 }
1749 None => {
1750 (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"))
1751 }
1752 };
1753 let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1754 let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1755 (success, task_line, command_line)
1756}
1757
1758/// Appends a stringified task summary to the terminal, after its output.
1759///
1760/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1761/// New text being added to the terminal here, uses "less public" APIs,
1762/// which are not maintaining the entire terminal state intact.
1763///
1764///
1765/// The library
1766///
1767/// * does not increment inner grid cursor's _lines_ on `input` calls
1768/// (but displaying the lines correctly and incrementing cursor's columns)
1769///
1770/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1771///
1772/// * does not alter grid state after `newline` call
1773/// so its `bottommost_line` is always the same additions, and
1774/// the cursor's `point` is not updated to the new line and column values
1775///
1776/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1777/// Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1778///
1779/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1780/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1781/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1782/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1783unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1784 term.newline();
1785 term.grid_mut().cursor.point.column = Column(0);
1786 for line in text_lines {
1787 for c in line.chars() {
1788 term.input(c);
1789 }
1790 term.newline();
1791 term.grid_mut().cursor.point.column = Column(0);
1792 }
1793}
1794
1795impl Drop for Terminal {
1796 fn drop(&mut self) {
1797 self.pty_tx.0.send(Msg::Shutdown).ok();
1798 }
1799}
1800
1801impl EventEmitter<Event> for Terminal {}
1802
1803/// Based on alacritty/src/display/hint.rs > regex_match_at
1804/// Retrieve the match, if the specified point is inside the content matching the regex.
1805fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &mut RegexSearch) -> Option<Match> {
1806 visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1807}
1808
1809/// Copied from alacritty/src/display/hint.rs:
1810/// Iterate over all visible regex matches.
1811pub fn visible_regex_match_iter<'a, T>(
1812 term: &'a Term<T>,
1813 regex: &'a mut RegexSearch,
1814) -> impl Iterator<Item = Match> + 'a {
1815 let viewport_start = Line(-(term.grid().display_offset() as i32));
1816 let viewport_end = viewport_start + term.bottommost_line();
1817 let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1818 let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1819 start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1820 end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1821
1822 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1823 .skip_while(move |rm| rm.end().line < viewport_start)
1824 .take_while(move |rm| rm.start().line <= viewport_end)
1825}
1826
1827fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1828 let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1829 selection.update(*range.end(), AlacDirection::Right);
1830 selection
1831}
1832
1833fn all_search_matches<'a, T>(
1834 term: &'a Term<T>,
1835 regex: &'a mut RegexSearch,
1836) -> impl Iterator<Item = Match> + 'a {
1837 let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1838 let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1839 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1840}
1841
1842fn content_index_for_mouse(pos: Point<Pixels>, size: &TerminalSize) -> usize {
1843 let col = (pos.x / size.cell_width()).round() as usize;
1844 let clamped_col = min(col, size.columns() - 1);
1845 let row = (pos.y / size.line_height()).round() as usize;
1846 let clamped_row = min(row, size.screen_lines() - 1);
1847 clamped_row * size.columns() + clamped_col
1848}
1849
1850/// Converts an 8 bit ANSI color to its GPUI equivalent.
1851/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1852/// Other than that use case, should only be called with values in the [0,255] range
1853pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1854 let colors = theme.colors();
1855
1856 match index {
1857 // 0-15 are the same as the named colors above
1858 0 => colors.terminal_ansi_black,
1859 1 => colors.terminal_ansi_red,
1860 2 => colors.terminal_ansi_green,
1861 3 => colors.terminal_ansi_yellow,
1862 4 => colors.terminal_ansi_blue,
1863 5 => colors.terminal_ansi_magenta,
1864 6 => colors.terminal_ansi_cyan,
1865 7 => colors.terminal_ansi_white,
1866 8 => colors.terminal_ansi_bright_black,
1867 9 => colors.terminal_ansi_bright_red,
1868 10 => colors.terminal_ansi_bright_green,
1869 11 => colors.terminal_ansi_bright_yellow,
1870 12 => colors.terminal_ansi_bright_blue,
1871 13 => colors.terminal_ansi_bright_magenta,
1872 14 => colors.terminal_ansi_bright_cyan,
1873 15 => colors.terminal_ansi_bright_white,
1874 // 16-231 are mapped to their RGB colors on a 0-5 range per channel
1875 16..=231 => {
1876 let (r, g, b) = rgb_for_index(index as u8); // Split the index into its ANSI-RGB components
1877 let step = (u8::MAX as f32 / 5.).floor() as u8; // Split the RGB range into 5 chunks, with floor so no overflow
1878 rgba_color(r * step, g * step, b * step) // Map the ANSI-RGB components to an RGB color
1879 }
1880 // 232-255 are a 24 step grayscale from black to white
1881 232..=255 => {
1882 let i = index as u8 - 232; // Align index to 0..24
1883 let step = (u8::MAX as f32 / 24.).floor() as u8; // Split the RGB grayscale values into 24 chunks
1884 rgba_color(i * step, i * step, i * step) // Map the ANSI-grayscale components to the RGB-grayscale
1885 }
1886 // For compatibility with the alacritty::Colors interface
1887 256 => colors.text,
1888 257 => colors.background,
1889 258 => theme.players().local().cursor,
1890 259 => colors.terminal_ansi_dim_black,
1891 260 => colors.terminal_ansi_dim_red,
1892 261 => colors.terminal_ansi_dim_green,
1893 262 => colors.terminal_ansi_dim_yellow,
1894 263 => colors.terminal_ansi_dim_blue,
1895 264 => colors.terminal_ansi_dim_magenta,
1896 265 => colors.terminal_ansi_dim_cyan,
1897 266 => colors.terminal_ansi_dim_white,
1898 267 => colors.terminal_bright_foreground,
1899 268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
1900
1901 _ => black(),
1902 }
1903}
1904
1905/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
1906/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1907///
1908/// Wikipedia gives a formula for calculating the index for a given color:
1909///
1910/// ```
1911/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1912/// ```
1913///
1914/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
1915fn rgb_for_index(i: u8) -> (u8, u8, u8) {
1916 debug_assert!((16..=231).contains(&i));
1917 let i = i - 16;
1918 let r = (i - (i % 36)) / 36;
1919 let g = ((i % 36) - (i % 6)) / 6;
1920 let b = (i % 36) % 6;
1921 (r, g, b)
1922}
1923
1924pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1925 Rgba {
1926 r: (r as f32 / 255.),
1927 g: (g as f32 / 255.),
1928 b: (b as f32 / 255.),
1929 a: 1.,
1930 }
1931 .into()
1932}
1933
1934#[cfg(test)]
1935mod tests {
1936 use alacritty_terminal::{
1937 index::{Column, Line, Point as AlacPoint},
1938 term::cell::Cell,
1939 };
1940 use gpui::{point, size, Pixels};
1941 use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
1942
1943 use crate::{
1944 content_index_for_mouse, rgb_for_index, IndexedCell, TerminalContent, TerminalSize,
1945 };
1946
1947 #[test]
1948 fn test_rgb_for_index() {
1949 // Test every possible value in the color cube.
1950 for i in 16..=231 {
1951 let (r, g, b) = rgb_for_index(i);
1952 assert_eq!(i, 16 + 36 * r + 6 * g + b);
1953 }
1954 }
1955
1956 #[test]
1957 fn test_mouse_to_cell_test() {
1958 let mut rng = thread_rng();
1959 const ITERATIONS: usize = 10;
1960 const PRECISION: usize = 1000;
1961
1962 for _ in 0..ITERATIONS {
1963 let viewport_cells = rng.gen_range(15..20);
1964 let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
1965
1966 let size = crate::TerminalSize {
1967 cell_width: Pixels::from(cell_size),
1968 line_height: Pixels::from(cell_size),
1969 size: size(
1970 Pixels::from(cell_size * (viewport_cells as f32)),
1971 Pixels::from(cell_size * (viewport_cells as f32)),
1972 ),
1973 };
1974
1975 let cells = get_cells(size, &mut rng);
1976 let content = convert_cells_to_content(size, &cells);
1977
1978 for row in 0..(viewport_cells - 1) {
1979 let row = row as usize;
1980 for col in 0..(viewport_cells - 1) {
1981 let col = col as usize;
1982
1983 let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1984 let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1985
1986 let mouse_pos = point(
1987 Pixels::from(col as f32 * cell_size + col_offset),
1988 Pixels::from(row as f32 * cell_size + row_offset),
1989 );
1990
1991 let content_index = content_index_for_mouse(mouse_pos, &content.size);
1992 let mouse_cell = content.cells[content_index].c;
1993 let real_cell = cells[row][col];
1994
1995 assert_eq!(mouse_cell, real_cell);
1996 }
1997 }
1998 }
1999 }
2000
2001 #[test]
2002 fn test_mouse_to_cell_clamp() {
2003 let mut rng = thread_rng();
2004
2005 let size = crate::TerminalSize {
2006 cell_width: Pixels::from(10.),
2007 line_height: Pixels::from(10.),
2008 size: size(Pixels::from(100.), Pixels::from(100.)),
2009 };
2010
2011 let cells = get_cells(size, &mut rng);
2012 let content = convert_cells_to_content(size, &cells);
2013
2014 assert_eq!(
2015 content.cells[content_index_for_mouse(
2016 point(Pixels::from(-10.), Pixels::from(-10.)),
2017 &content.size,
2018 )]
2019 .c,
2020 cells[0][0]
2021 );
2022 assert_eq!(
2023 content.cells[content_index_for_mouse(
2024 point(Pixels::from(1000.), Pixels::from(1000.)),
2025 &content.size,
2026 )]
2027 .c,
2028 cells[9][9]
2029 );
2030 }
2031
2032 fn get_cells(size: TerminalSize, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2033 let mut cells = Vec::new();
2034
2035 for _ in 0..((size.height() / size.line_height()) as usize) {
2036 let mut row_vec = Vec::new();
2037 for _ in 0..((size.width() / size.cell_width()) as usize) {
2038 let cell_char = rng.sample(Alphanumeric) as char;
2039 row_vec.push(cell_char)
2040 }
2041 cells.push(row_vec)
2042 }
2043
2044 cells
2045 }
2046
2047 fn convert_cells_to_content(size: TerminalSize, cells: &[Vec<char>]) -> TerminalContent {
2048 let mut ic = Vec::new();
2049
2050 for (index, row) in cells.iter().enumerate() {
2051 for (cell_index, cell_char) in row.iter().enumerate() {
2052 ic.push(IndexedCell {
2053 point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2054 cell: Cell {
2055 c: *cell_char,
2056 ..Default::default()
2057 },
2058 });
2059 }
2060 }
2061
2062 TerminalContent {
2063 cells: ic,
2064 size,
2065 ..Default::default()
2066 }
2067 }
2068
2069 fn re_test(re: &str, hay: &str, expected: Vec<&str>) {
2070 let results: Vec<_> = regex::Regex::new(re)
2071 .unwrap()
2072 .find_iter(hay)
2073 .map(|m| m.as_str())
2074 .collect();
2075 assert_eq!(results, expected);
2076 }
2077 #[test]
2078 fn test_url_regex() {
2079 re_test(
2080 crate::URL_REGEX,
2081 "test http://example.com test mailto:bob@example.com train",
2082 vec!["http://example.com", "mailto:bob@example.com"],
2083 );
2084 }
2085 #[test]
2086 fn test_word_regex() {
2087 re_test(
2088 crate::WORD_REGEX,
2089 "hello, world! \"What\" is this?",
2090 vec!["hello", "world", "What", "is", "this"],
2091 );
2092 }
2093 #[test]
2094 fn test_word_regex_with_linenum() {
2095 // filename(line) and filename(line,col) as used in MSBuild output
2096 // should be considered a single "word", even though comma is
2097 // usually a word separator
2098 re_test(
2099 crate::WORD_REGEX,
2100 "a Main.cs(20) b",
2101 vec!["a", "Main.cs(20)", "b"],
2102 );
2103 re_test(
2104 crate::WORD_REGEX,
2105 "Main.cs(20,5) Error desc",
2106 vec!["Main.cs(20,5)", "Error", "desc"],
2107 );
2108 // filename:line:col is a popular format for unix tools
2109 re_test(
2110 crate::WORD_REGEX,
2111 "a Main.cs:20:5 b",
2112 vec!["a", "Main.cs:20:5", "b"],
2113 );
2114 // Some tools output "filename:line:col:message", which currently isn't
2115 // handled correctly, but might be in the future
2116 re_test(
2117 crate::WORD_REGEX,
2118 "Main.cs:20:5:Error desc",
2119 vec!["Main.cs:20:5:Error", "desc"],
2120 );
2121 }
2122}