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