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