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(target_os = "linux")]
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(target_os = "linux")]
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(target_os = "linux")]
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) =
928 if file_path.starts_with('[') && file_path.ends_with(']') {
929 (
930 Match::new(
931 word_match.start().add(term, Boundary::Cursor, 1),
932 word_match.end().sub(term, Boundary::Cursor, 1),
933 ),
934 file_path[1..file_path.len() - 1].to_owned(),
935 )
936 } else {
937 (word_match, file_path)
938 };
939
940 Some((sanitized_word, false, sanitized_match))
941 } else {
942 None
943 };
944
945 match found_word {
946 Some((maybe_url_or_path, is_url, url_match)) => {
947 if *open {
948 let target = if is_url {
949 MaybeNavigationTarget::Url(maybe_url_or_path)
950 } else {
951 MaybeNavigationTarget::PathLike(PathLikeTarget {
952 maybe_path: maybe_url_or_path,
953 terminal_dir: self.working_directory(),
954 })
955 };
956 cx.emit(Event::Open(target));
957 } else {
958 self.update_selected_word(
959 prev_hovered_word,
960 url_match,
961 maybe_url_or_path,
962 is_url,
963 cx,
964 );
965 }
966 self.hovered_word = true;
967 }
968 None => {
969 if self.hovered_word {
970 cx.emit(Event::NewNavigationTarget(None));
971 }
972 self.hovered_word = false;
973 }
974 }
975 }
976 }
977 }
978
979 fn update_selected_word(
980 &mut self,
981 prev_word: Option<HoveredWord>,
982 word_match: RangeInclusive<AlacPoint>,
983 word: String,
984 is_url: bool,
985 cx: &mut ModelContext<Self>,
986 ) {
987 if let Some(prev_word) = prev_word {
988 if prev_word.word == word && prev_word.word_match == word_match {
989 self.last_content.last_hovered_word = Some(HoveredWord {
990 word,
991 word_match,
992 id: prev_word.id,
993 });
994 return;
995 }
996 }
997
998 self.last_content.last_hovered_word = Some(HoveredWord {
999 word: word.clone(),
1000 word_match,
1001 id: self.next_link_id(),
1002 });
1003 let navigation_target = if is_url {
1004 MaybeNavigationTarget::Url(word)
1005 } else {
1006 MaybeNavigationTarget::PathLike(PathLikeTarget {
1007 maybe_path: word,
1008 terminal_dir: self.working_directory(),
1009 })
1010 };
1011 cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
1012 }
1013
1014 fn next_link_id(&mut self) -> usize {
1015 let res = self.next_link_id;
1016 self.next_link_id = self.next_link_id.wrapping_add(1);
1017 res
1018 }
1019
1020 pub fn last_content(&self) -> &TerminalContent {
1021 &self.last_content
1022 }
1023
1024 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
1025 self.term_config.default_cursor_style = cursor_shape.into();
1026 self.term.lock().set_options(self.term_config.clone());
1027 }
1028
1029 pub fn total_lines(&self) -> usize {
1030 let term = self.term.clone();
1031 let terminal = term.lock_unfair();
1032 terminal.total_lines()
1033 }
1034
1035 pub fn viewport_lines(&self) -> usize {
1036 let term = self.term.clone();
1037 let terminal = term.lock_unfair();
1038 terminal.screen_lines()
1039 }
1040
1041 //To test:
1042 //- Activate match on terminal (scrolling and selection)
1043 //- Editor search snapping behavior
1044
1045 pub fn activate_match(&mut self, index: usize) {
1046 if let Some(search_match) = self.matches.get(index).cloned() {
1047 self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1048
1049 self.events
1050 .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1051 }
1052 }
1053
1054 pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1055 let matches_to_select = self
1056 .matches
1057 .iter()
1058 .filter(|self_match| matches.contains(self_match))
1059 .cloned()
1060 .collect::<Vec<_>>();
1061 for match_to_select in matches_to_select {
1062 self.set_selection(Some((
1063 make_selection(&match_to_select),
1064 *match_to_select.end(),
1065 )));
1066 }
1067 }
1068
1069 pub fn select_all(&mut self) {
1070 let term = self.term.lock();
1071 let start = AlacPoint::new(term.topmost_line(), Column(0));
1072 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1073 drop(term);
1074 self.set_selection(Some((make_selection(&(start..=end)), end)));
1075 }
1076
1077 fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1078 self.events
1079 .push_back(InternalEvent::SetSelection(selection));
1080 }
1081
1082 pub fn copy(&mut self) {
1083 self.events.push_back(InternalEvent::Copy);
1084 }
1085
1086 pub fn clear(&mut self) {
1087 self.events.push_back(InternalEvent::Clear)
1088 }
1089
1090 pub fn scroll_line_up(&mut self) {
1091 self.events
1092 .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1093 }
1094
1095 pub fn scroll_up_by(&mut self, lines: usize) {
1096 self.events
1097 .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1098 }
1099
1100 pub fn scroll_line_down(&mut self) {
1101 self.events
1102 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1103 }
1104
1105 pub fn scroll_down_by(&mut self, lines: usize) {
1106 self.events
1107 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1108 }
1109
1110 pub fn scroll_page_up(&mut self) {
1111 self.events
1112 .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1113 }
1114
1115 pub fn scroll_page_down(&mut self) {
1116 self.events
1117 .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1118 }
1119
1120 pub fn scroll_to_top(&mut self) {
1121 self.events
1122 .push_back(InternalEvent::Scroll(AlacScroll::Top));
1123 }
1124
1125 pub fn scroll_to_bottom(&mut self) {
1126 self.events
1127 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1128 }
1129
1130 ///Resize the terminal and the PTY.
1131 pub fn set_size(&mut self, new_size: TerminalSize) {
1132 if self.last_content.size != new_size {
1133 self.events.push_back(InternalEvent::Resize(new_size))
1134 }
1135 }
1136
1137 ///Write the Input payload to the tty.
1138 fn write_to_pty(&self, input: String) {
1139 self.pty_tx.notify(input.into_bytes());
1140 }
1141
1142 fn write_bytes_to_pty(&self, input: Vec<u8>) {
1143 self.pty_tx.notify(input);
1144 }
1145
1146 pub fn input(&mut self, input: String) {
1147 self.events
1148 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1149 self.events.push_back(InternalEvent::SetSelection(None));
1150
1151 self.write_to_pty(input);
1152 }
1153
1154 pub fn input_bytes(&mut self, input: Vec<u8>) {
1155 self.events
1156 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1157 self.events.push_back(InternalEvent::SetSelection(None));
1158
1159 self.write_bytes_to_pty(input);
1160 }
1161
1162 pub fn toggle_vi_mode(&mut self) {
1163 self.events.push_back(InternalEvent::ToggleViMode);
1164 }
1165
1166 pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1167 if !self.vi_mode_enabled {
1168 return;
1169 }
1170
1171 let mut key = keystroke.key.clone();
1172 if keystroke.modifiers.shift {
1173 key = key.to_uppercase();
1174 }
1175
1176 let motion: Option<ViMotion> = match key.as_str() {
1177 "h" => Some(ViMotion::Left),
1178 "j" => Some(ViMotion::Down),
1179 "k" => Some(ViMotion::Up),
1180 "l" => Some(ViMotion::Right),
1181 "w" => Some(ViMotion::WordRight),
1182 "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1183 "e" => Some(ViMotion::WordRightEnd),
1184 "%" => Some(ViMotion::Bracket),
1185 "$" => Some(ViMotion::Last),
1186 "0" => Some(ViMotion::First),
1187 "^" => Some(ViMotion::FirstOccupied),
1188 "H" => Some(ViMotion::High),
1189 "M" => Some(ViMotion::Middle),
1190 "L" => Some(ViMotion::Low),
1191 _ => None,
1192 };
1193
1194 if let Some(motion) = motion {
1195 let cursor = self.last_content.cursor.point;
1196 let cursor_pos = Point {
1197 x: cursor.column.0 as f32 * self.last_content.size.cell_width,
1198 y: cursor.line.0 as f32 * self.last_content.size.line_height,
1199 };
1200 self.events
1201 .push_back(InternalEvent::UpdateSelection(cursor_pos));
1202 self.events.push_back(InternalEvent::ViMotion(motion));
1203 return;
1204 }
1205
1206 let scroll_motion = match key.as_str() {
1207 "g" => Some(AlacScroll::Top),
1208 "G" => Some(AlacScroll::Bottom),
1209 "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1210 "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1211 "d" if keystroke.modifiers.control => {
1212 let amount = self.last_content.size.line_height().to_f64() as i32 / 2;
1213 Some(AlacScroll::Delta(-amount))
1214 }
1215 "u" 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 _ => None,
1220 };
1221
1222 if let Some(scroll_motion) = scroll_motion {
1223 self.events.push_back(InternalEvent::Scroll(scroll_motion));
1224 return;
1225 }
1226
1227 match key.as_str() {
1228 "v" => {
1229 let point = self.last_content.cursor.point;
1230 let selection_type = SelectionType::Simple;
1231 let side = AlacDirection::Right;
1232 let selection = Selection::new(selection_type, point, side);
1233 self.events
1234 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1235 return;
1236 }
1237
1238 "escape" => {
1239 self.events.push_back(InternalEvent::SetSelection(None));
1240 return;
1241 }
1242
1243 "y" => {
1244 self.events.push_back(InternalEvent::Copy);
1245 self.events.push_back(InternalEvent::SetSelection(None));
1246 return;
1247 }
1248
1249 "i" => {
1250 self.scroll_to_bottom();
1251 self.toggle_vi_mode();
1252 return;
1253 }
1254 _ => {}
1255 }
1256 }
1257
1258 pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1259 if self.vi_mode_enabled {
1260 self.vi_motion(keystroke);
1261 return true;
1262 }
1263
1264 // Keep default terminal behavior
1265 let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1266 if let Some(esc) = esc {
1267 self.input(esc);
1268 true
1269 } else {
1270 false
1271 }
1272 }
1273
1274 pub fn try_modifiers_change(&mut self, modifiers: &Modifiers) -> bool {
1275 let changed = self.secondary_pressed != modifiers.secondary();
1276 if !self.secondary_pressed && modifiers.secondary() {
1277 self.refresh_hovered_word();
1278 }
1279 self.secondary_pressed = modifiers.secondary();
1280 changed
1281 }
1282
1283 ///Paste text into the terminal
1284 pub fn paste(&mut self, text: &str) {
1285 let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1286 format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1287 } else {
1288 text.replace("\r\n", "\r").replace('\n', "\r")
1289 };
1290
1291 self.input(paste_text);
1292 }
1293
1294 pub fn sync(&mut self, cx: &mut ModelContext<Self>) {
1295 let term = self.term.clone();
1296 let mut terminal = term.lock_unfair();
1297 //Note that the ordering of events matters for event processing
1298 while let Some(e) = self.events.pop_front() {
1299 self.process_terminal_event(&e, &mut terminal, cx)
1300 }
1301
1302 self.last_content = Self::make_content(&terminal, &self.last_content);
1303 }
1304
1305 fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1306 let content = term.renderable_content();
1307 TerminalContent {
1308 cells: content
1309 .display_iter
1310 //TODO: Add this once there's a way to retain empty lines
1311 // .filter(|ic| {
1312 // !ic.flags.contains(Flags::HIDDEN)
1313 // && !(ic.bg == Named(NamedColor::Background)
1314 // && ic.c == ' '
1315 // && !ic.flags.contains(Flags::INVERSE))
1316 // })
1317 .map(|ic| IndexedCell {
1318 point: ic.point,
1319 cell: ic.cell.clone(),
1320 })
1321 .collect::<Vec<IndexedCell>>(),
1322 mode: content.mode,
1323 display_offset: content.display_offset,
1324 selection_text: term.selection_to_string(),
1325 selection: content.selection,
1326 cursor: content.cursor,
1327 cursor_char: term.grid()[content.cursor.point].c,
1328 size: last_content.size,
1329 last_hovered_word: last_content.last_hovered_word.clone(),
1330 }
1331 }
1332
1333 pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1334 let term = self.term.clone();
1335 let terminal = term.lock_unfair();
1336
1337 let mut lines = Vec::new();
1338 let mut current_line = terminal.bottommost_line();
1339 while lines.len() < n {
1340 let mut line_buffer = String::new();
1341 for cell in &terminal.grid()[current_line] {
1342 line_buffer.push(cell.c);
1343 }
1344 let line = line_buffer.trim_end();
1345 if !line.is_empty() {
1346 lines.push(line.to_string());
1347 }
1348
1349 if current_line == terminal.topmost_line() {
1350 break;
1351 }
1352 current_line = Line(current_line.0 - 1);
1353 }
1354 lines.reverse();
1355 lines
1356 }
1357
1358 pub fn focus_in(&self) {
1359 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1360 self.write_to_pty("\x1b[I".to_string());
1361 }
1362 }
1363
1364 pub fn focus_out(&mut self) {
1365 self.last_mouse_position = None;
1366 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1367 self.write_to_pty("\x1b[O".to_string());
1368 }
1369 }
1370
1371 pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1372 match self.last_mouse {
1373 Some((old_point, old_side)) => {
1374 if old_point == point && old_side == side {
1375 false
1376 } else {
1377 self.last_mouse = Some((point, side));
1378 true
1379 }
1380 }
1381 None => {
1382 self.last_mouse = Some((point, side));
1383 true
1384 }
1385 }
1386 }
1387
1388 pub fn mouse_mode(&self, shift: bool) -> bool {
1389 self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1390 }
1391
1392 pub fn mouse_move(&mut self, e: &MouseMoveEvent, origin: Point<Pixels>) {
1393 let position = e.position - origin;
1394 self.last_mouse_position = Some(position);
1395 if self.mouse_mode(e.modifiers.shift) {
1396 let (point, side) = grid_point_and_side(
1397 position,
1398 self.last_content.size,
1399 self.last_content.display_offset,
1400 );
1401
1402 if self.mouse_changed(point, side) {
1403 if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
1404 self.pty_tx.notify(bytes);
1405 }
1406 }
1407 } else if self.secondary_pressed {
1408 self.word_from_position(Some(position));
1409 }
1410 }
1411
1412 fn word_from_position(&mut self, position: Option<Point<Pixels>>) {
1413 if self.selection_phase == SelectionPhase::Selecting {
1414 self.last_content.last_hovered_word = None;
1415 } else if let Some(position) = position {
1416 self.events
1417 .push_back(InternalEvent::FindHyperlink(position, false));
1418 }
1419 }
1420
1421 pub fn mouse_drag(
1422 &mut self,
1423 e: &MouseMoveEvent,
1424 origin: Point<Pixels>,
1425 region: Bounds<Pixels>,
1426 ) {
1427 let position = e.position - origin;
1428 self.last_mouse_position = Some(position);
1429
1430 if !self.mouse_mode(e.modifiers.shift) {
1431 self.selection_phase = SelectionPhase::Selecting;
1432 // Alacritty has the same ordering, of first updating the selection
1433 // then scrolling 15ms later
1434 self.events
1435 .push_back(InternalEvent::UpdateSelection(position));
1436
1437 // Doesn't make sense to scroll the alt screen
1438 if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1439 let scroll_delta = match self.drag_line_delta(e, region) {
1440 Some(value) => value,
1441 None => return,
1442 };
1443
1444 let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
1445
1446 self.events
1447 .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1448 }
1449 }
1450 }
1451
1452 fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<Pixels> {
1453 //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1454 let top = region.origin.y + (self.last_content.size.line_height * 2.);
1455 let bottom = region.lower_left().y - (self.last_content.size.line_height * 2.);
1456 let scroll_delta = if e.position.y < top {
1457 (top - e.position.y).pow(1.1)
1458 } else if e.position.y > bottom {
1459 -((e.position.y - bottom).pow(1.1))
1460 } else {
1461 return None; //Nothing to do
1462 };
1463 Some(scroll_delta)
1464 }
1465
1466 pub fn mouse_down(
1467 &mut self,
1468 e: &MouseDownEvent,
1469 origin: Point<Pixels>,
1470 _cx: &mut ModelContext<Self>,
1471 ) {
1472 let position = e.position - origin;
1473 let point = grid_point(
1474 position,
1475 self.last_content.size,
1476 self.last_content.display_offset,
1477 );
1478
1479 if self.mouse_mode(e.modifiers.shift) {
1480 if let Some(bytes) =
1481 mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1482 {
1483 self.pty_tx.notify(bytes);
1484 }
1485 } else {
1486 match e.button {
1487 MouseButton::Left => {
1488 let position = e.position - origin;
1489 let (point, side) = grid_point_and_side(
1490 position,
1491 self.last_content.size,
1492 self.last_content.display_offset,
1493 );
1494
1495 let selection_type = match e.click_count {
1496 0 => return, //This is a release
1497 1 => Some(SelectionType::Simple),
1498 2 => Some(SelectionType::Semantic),
1499 3 => Some(SelectionType::Lines),
1500 _ => None,
1501 };
1502
1503 let selection = selection_type
1504 .map(|selection_type| Selection::new(selection_type, point, side));
1505
1506 if let Some(sel) = selection {
1507 self.events
1508 .push_back(InternalEvent::SetSelection(Some((sel, point))));
1509 }
1510 }
1511 #[cfg(target_os = "linux")]
1512 MouseButton::Middle => {
1513 if let Some(item) = _cx.read_from_primary() {
1514 let text = item.text().unwrap_or_default().to_string();
1515 self.input(text);
1516 }
1517 }
1518 _ => {}
1519 }
1520 }
1521 }
1522
1523 pub fn mouse_up(&mut self, e: &MouseUpEvent, origin: Point<Pixels>, cx: &ModelContext<Self>) {
1524 let setting = TerminalSettings::get_global(cx);
1525
1526 let position = e.position - origin;
1527 if self.mouse_mode(e.modifiers.shift) {
1528 let point = grid_point(
1529 position,
1530 self.last_content.size,
1531 self.last_content.display_offset,
1532 );
1533
1534 if let Some(bytes) =
1535 mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1536 {
1537 self.pty_tx.notify(bytes);
1538 }
1539 } else {
1540 if e.button == MouseButton::Left && setting.copy_on_select {
1541 self.copy();
1542 }
1543
1544 //Hyperlinks
1545 if self.selection_phase == SelectionPhase::Ended {
1546 let mouse_cell_index = content_index_for_mouse(position, &self.last_content.size);
1547 if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1548 cx.open_url(link.uri());
1549 } else if self.secondary_pressed {
1550 self.events
1551 .push_back(InternalEvent::FindHyperlink(position, true));
1552 }
1553 }
1554 }
1555
1556 self.selection_phase = SelectionPhase::Ended;
1557 self.last_mouse = None;
1558 }
1559
1560 ///Scroll the terminal
1561 pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent, origin: Point<Pixels>) {
1562 let mouse_mode = self.mouse_mode(e.shift);
1563
1564 if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1565 if mouse_mode {
1566 let point = grid_point(
1567 e.position - origin,
1568 self.last_content.size,
1569 self.last_content.display_offset,
1570 );
1571
1572 if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1573 {
1574 for scroll in scrolls {
1575 self.pty_tx.notify(scroll);
1576 }
1577 };
1578 } else if self
1579 .last_content
1580 .mode
1581 .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1582 && !e.shift
1583 {
1584 self.pty_tx.notify(alt_scroll(scroll_lines))
1585 } else if scroll_lines != 0 {
1586 let scroll = AlacScroll::Delta(scroll_lines);
1587
1588 self.events.push_back(InternalEvent::Scroll(scroll));
1589 }
1590 }
1591 }
1592
1593 fn refresh_hovered_word(&mut self) {
1594 self.word_from_position(self.last_mouse_position);
1595 }
1596
1597 fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1598 let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1599 let line_height = self.last_content.size.line_height;
1600 match e.touch_phase {
1601 /* Reset scroll state on started */
1602 TouchPhase::Started => {
1603 self.scroll_px = px(0.);
1604 None
1605 }
1606 /* Calculate the appropriate scroll lines */
1607 TouchPhase::Moved => {
1608 let old_offset = (self.scroll_px / line_height) as i32;
1609
1610 self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1611
1612 let new_offset = (self.scroll_px / line_height) as i32;
1613
1614 // Whenever we hit the edges, reset our stored scroll to 0
1615 // so we can respond to changes in direction quickly
1616 self.scroll_px %= self.last_content.size.height();
1617
1618 Some(new_offset - old_offset)
1619 }
1620 TouchPhase::Ended => None,
1621 }
1622 }
1623
1624 pub fn find_matches(
1625 &self,
1626 mut searcher: RegexSearch,
1627 cx: &ModelContext<Self>,
1628 ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1629 let term = self.term.clone();
1630 cx.background_executor().spawn(async move {
1631 let term = term.lock();
1632
1633 all_search_matches(&term, &mut searcher).collect()
1634 })
1635 }
1636
1637 pub fn working_directory(&self) -> Option<PathBuf> {
1638 if self.is_ssh_terminal {
1639 // We can't yet reliably detect the working directory of a shell on the
1640 // SSH host. Until we can do that, it doesn't make sense to display
1641 // the working directory on the client and persist that.
1642 None
1643 } else {
1644 self.client_side_working_directory()
1645 }
1646 }
1647
1648 /// Returns the working directory of the process that's connected to the PTY.
1649 /// That means it returns the working directory of the local shell or program
1650 /// that's running inside the terminal.
1651 ///
1652 /// This does *not* return the working directory of the shell that runs on the
1653 /// remote host, in case Zed is connected to a remote host.
1654 fn client_side_working_directory(&self) -> Option<PathBuf> {
1655 self.pty_info
1656 .current
1657 .as_ref()
1658 .map(|process| process.cwd.clone())
1659 }
1660
1661 pub fn title(&self, truncate: bool) -> String {
1662 const MAX_CHARS: usize = 25;
1663 match &self.task {
1664 Some(task_state) => {
1665 if truncate {
1666 truncate_and_trailoff(&task_state.label, MAX_CHARS)
1667 } else {
1668 task_state.full_label.clone()
1669 }
1670 }
1671 None => self
1672 .title_override
1673 .as_ref()
1674 .map(|title_override| title_override.to_string())
1675 .unwrap_or_else(|| {
1676 self.pty_info
1677 .current
1678 .as_ref()
1679 .map(|fpi| {
1680 let process_file = fpi
1681 .cwd
1682 .file_name()
1683 .map(|name| name.to_string_lossy().to_string())
1684 .unwrap_or_default();
1685
1686 let argv = fpi.argv.clone();
1687 let process_name = format!(
1688 "{}{}",
1689 fpi.name,
1690 if !argv.is_empty() {
1691 format!(" {}", (argv[1..]).join(" "))
1692 } else {
1693 "".to_string()
1694 }
1695 );
1696 let (process_file, process_name) = if truncate {
1697 (
1698 truncate_and_trailoff(&process_file, MAX_CHARS),
1699 truncate_and_trailoff(&process_name, MAX_CHARS),
1700 )
1701 } else {
1702 (process_file, process_name)
1703 };
1704 format!("{process_file} — {process_name}")
1705 })
1706 .unwrap_or_else(|| "Terminal".to_string())
1707 }),
1708 }
1709 }
1710
1711 pub fn can_navigate_to_selected_word(&self) -> bool {
1712 self.secondary_pressed && self.hovered_word
1713 }
1714
1715 pub fn task(&self) -> Option<&TaskState> {
1716 self.task.as_ref()
1717 }
1718
1719 pub fn wait_for_completed_task(&self, cx: &AppContext) -> Task<()> {
1720 if let Some(task) = self.task() {
1721 if task.status == TaskStatus::Running {
1722 let mut completion_receiver = task.completion_rx.clone();
1723 return cx.spawn(|_| async move {
1724 completion_receiver.next().await;
1725 });
1726 }
1727 }
1728 Task::ready(())
1729 }
1730
1731 fn register_task_finished(
1732 &mut self,
1733 error_code: Option<i32>,
1734 cx: &mut ModelContext<'_, Terminal>,
1735 ) {
1736 self.completion_tx.try_send(()).ok();
1737 let task = match &mut self.task {
1738 Some(task) => task,
1739 None => {
1740 if error_code.is_none() {
1741 cx.emit(Event::CloseTerminal);
1742 }
1743 return;
1744 }
1745 };
1746 if task.status != TaskStatus::Running {
1747 return;
1748 }
1749 match error_code {
1750 Some(error_code) => {
1751 task.status.register_task_exit(error_code);
1752 }
1753 None => {
1754 task.status.register_terminal_exit();
1755 }
1756 };
1757
1758 let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1759 // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1760 // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1761 // when Zed task finishes and no more output is made.
1762 // After the task summary is output once, no more text is appended to the terminal.
1763 unsafe { append_text_to_term(&mut self.term.lock(), &[&task_line, &command_line]) };
1764 match task.hide {
1765 HideStrategy::Never => {}
1766 HideStrategy::Always => {
1767 cx.emit(Event::CloseTerminal);
1768 }
1769 HideStrategy::OnSuccess => {
1770 if finished_successfully {
1771 cx.emit(Event::CloseTerminal);
1772 }
1773 }
1774 }
1775 }
1776}
1777
1778const TASK_DELIMITER: &str = "⏵ ";
1779fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1780 let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1781 let (success, task_line) = match error_code {
1782 Some(0) => {
1783 (true, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"))
1784 }
1785 Some(error_code) => {
1786 (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"))
1787 }
1788 None => {
1789 (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"))
1790 }
1791 };
1792 let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1793 let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1794 (success, task_line, command_line)
1795}
1796
1797/// Appends a stringified task summary to the terminal, after its output.
1798///
1799/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1800/// New text being added to the terminal here, uses "less public" APIs,
1801/// which are not maintaining the entire terminal state intact.
1802///
1803///
1804/// The library
1805///
1806/// * does not increment inner grid cursor's _lines_ on `input` calls
1807/// (but displaying the lines correctly and incrementing cursor's columns)
1808///
1809/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1810///
1811/// * does not alter grid state after `newline` call
1812/// so its `bottommost_line` is always the same additions, and
1813/// the cursor's `point` is not updated to the new line and column values
1814///
1815/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1816/// Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1817///
1818/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1819/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1820/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1821/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1822unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1823 term.newline();
1824 term.grid_mut().cursor.point.column = Column(0);
1825 for line in text_lines {
1826 for c in line.chars() {
1827 term.input(c);
1828 }
1829 term.newline();
1830 term.grid_mut().cursor.point.column = Column(0);
1831 }
1832}
1833
1834impl Drop for Terminal {
1835 fn drop(&mut self) {
1836 self.pty_tx.0.send(Msg::Shutdown).ok();
1837 }
1838}
1839
1840impl EventEmitter<Event> for Terminal {}
1841
1842/// Based on alacritty/src/display/hint.rs > regex_match_at
1843/// Retrieve the match, if the specified point is inside the content matching the regex.
1844fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &mut RegexSearch) -> Option<Match> {
1845 visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1846}
1847
1848/// Copied from alacritty/src/display/hint.rs:
1849/// Iterate over all visible regex matches.
1850pub fn visible_regex_match_iter<'a, T>(
1851 term: &'a Term<T>,
1852 regex: &'a mut RegexSearch,
1853) -> impl Iterator<Item = Match> + 'a {
1854 let viewport_start = Line(-(term.grid().display_offset() as i32));
1855 let viewport_end = viewport_start + term.bottommost_line();
1856 let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1857 let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1858 start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1859 end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1860
1861 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1862 .skip_while(move |rm| rm.end().line < viewport_start)
1863 .take_while(move |rm| rm.start().line <= viewport_end)
1864}
1865
1866fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1867 let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1868 selection.update(*range.end(), AlacDirection::Right);
1869 selection
1870}
1871
1872fn all_search_matches<'a, T>(
1873 term: &'a Term<T>,
1874 regex: &'a mut RegexSearch,
1875) -> impl Iterator<Item = Match> + 'a {
1876 let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1877 let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1878 RegexIter::new(start, end, AlacDirection::Right, term, regex)
1879}
1880
1881fn content_index_for_mouse(pos: Point<Pixels>, size: &TerminalSize) -> usize {
1882 let col = (pos.x / size.cell_width()).round() as usize;
1883 let clamped_col = min(col, size.columns() - 1);
1884 let row = (pos.y / size.line_height()).round() as usize;
1885 let clamped_row = min(row, size.screen_lines() - 1);
1886 clamped_row * size.columns() + clamped_col
1887}
1888
1889/// Converts an 8 bit ANSI color to its GPUI equivalent.
1890/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1891/// Other than that use case, should only be called with values in the [0,255] range
1892pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1893 let colors = theme.colors();
1894
1895 match index {
1896 // 0-15 are the same as the named colors above
1897 0 => colors.terminal_ansi_black,
1898 1 => colors.terminal_ansi_red,
1899 2 => colors.terminal_ansi_green,
1900 3 => colors.terminal_ansi_yellow,
1901 4 => colors.terminal_ansi_blue,
1902 5 => colors.terminal_ansi_magenta,
1903 6 => colors.terminal_ansi_cyan,
1904 7 => colors.terminal_ansi_white,
1905 8 => colors.terminal_ansi_bright_black,
1906 9 => colors.terminal_ansi_bright_red,
1907 10 => colors.terminal_ansi_bright_green,
1908 11 => colors.terminal_ansi_bright_yellow,
1909 12 => colors.terminal_ansi_bright_blue,
1910 13 => colors.terminal_ansi_bright_magenta,
1911 14 => colors.terminal_ansi_bright_cyan,
1912 15 => colors.terminal_ansi_bright_white,
1913 // 16-231 are mapped to their RGB colors on a 0-5 range per channel
1914 16..=231 => {
1915 let (r, g, b) = rgb_for_index(index as u8); // Split the index into its ANSI-RGB components
1916 let step = (u8::MAX as f32 / 5.).floor() as u8; // Split the RGB range into 5 chunks, with floor so no overflow
1917 rgba_color(r * step, g * step, b * step) // Map the ANSI-RGB components to an RGB color
1918 }
1919 // 232-255 are a 24 step grayscale from black to white
1920 232..=255 => {
1921 let i = index as u8 - 232; // Align index to 0..24
1922 let step = (u8::MAX as f32 / 24.).floor() as u8; // Split the RGB grayscale values into 24 chunks
1923 rgba_color(i * step, i * step, i * step) // Map the ANSI-grayscale components to the RGB-grayscale
1924 }
1925 // For compatibility with the alacritty::Colors interface
1926 256 => colors.text,
1927 257 => colors.background,
1928 258 => theme.players().local().cursor,
1929 259 => colors.terminal_ansi_dim_black,
1930 260 => colors.terminal_ansi_dim_red,
1931 261 => colors.terminal_ansi_dim_green,
1932 262 => colors.terminal_ansi_dim_yellow,
1933 263 => colors.terminal_ansi_dim_blue,
1934 264 => colors.terminal_ansi_dim_magenta,
1935 265 => colors.terminal_ansi_dim_cyan,
1936 266 => colors.terminal_ansi_dim_white,
1937 267 => colors.terminal_bright_foreground,
1938 268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
1939
1940 _ => black(),
1941 }
1942}
1943
1944/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
1945/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1946///
1947/// Wikipedia gives a formula for calculating the index for a given color:
1948///
1949/// ```
1950/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1951/// ```
1952///
1953/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
1954fn rgb_for_index(i: u8) -> (u8, u8, u8) {
1955 debug_assert!((16..=231).contains(&i));
1956 let i = i - 16;
1957 let r = (i - (i % 36)) / 36;
1958 let g = ((i % 36) - (i % 6)) / 6;
1959 let b = (i % 36) % 6;
1960 (r, g, b)
1961}
1962
1963pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1964 Rgba {
1965 r: (r as f32 / 255.),
1966 g: (g as f32 / 255.),
1967 b: (b as f32 / 255.),
1968 a: 1.,
1969 }
1970 .into()
1971}
1972
1973#[cfg(test)]
1974mod tests {
1975 use alacritty_terminal::{
1976 index::{Column, Line, Point as AlacPoint},
1977 term::cell::Cell,
1978 };
1979 use gpui::{point, size, Pixels};
1980 use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
1981
1982 use crate::{
1983 content_index_for_mouse, rgb_for_index, IndexedCell, TerminalContent, TerminalSize,
1984 };
1985
1986 #[test]
1987 fn test_rgb_for_index() {
1988 // Test every possible value in the color cube.
1989 for i in 16..=231 {
1990 let (r, g, b) = rgb_for_index(i);
1991 assert_eq!(i, 16 + 36 * r + 6 * g + b);
1992 }
1993 }
1994
1995 #[test]
1996 fn test_mouse_to_cell_test() {
1997 let mut rng = thread_rng();
1998 const ITERATIONS: usize = 10;
1999 const PRECISION: usize = 1000;
2000
2001 for _ in 0..ITERATIONS {
2002 let viewport_cells = rng.gen_range(15..20);
2003 let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2004
2005 let size = crate::TerminalSize {
2006 cell_width: Pixels::from(cell_size),
2007 line_height: Pixels::from(cell_size),
2008 size: size(
2009 Pixels::from(cell_size * (viewport_cells as f32)),
2010 Pixels::from(cell_size * (viewport_cells as f32)),
2011 ),
2012 };
2013
2014 let cells = get_cells(size, &mut rng);
2015 let content = convert_cells_to_content(size, &cells);
2016
2017 for row in 0..(viewport_cells - 1) {
2018 let row = row as usize;
2019 for col in 0..(viewport_cells - 1) {
2020 let col = col as usize;
2021
2022 let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2023 let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2024
2025 let mouse_pos = point(
2026 Pixels::from(col as f32 * cell_size + col_offset),
2027 Pixels::from(row as f32 * cell_size + row_offset),
2028 );
2029
2030 let content_index = content_index_for_mouse(mouse_pos, &content.size);
2031 let mouse_cell = content.cells[content_index].c;
2032 let real_cell = cells[row][col];
2033
2034 assert_eq!(mouse_cell, real_cell);
2035 }
2036 }
2037 }
2038 }
2039
2040 #[test]
2041 fn test_mouse_to_cell_clamp() {
2042 let mut rng = thread_rng();
2043
2044 let size = crate::TerminalSize {
2045 cell_width: Pixels::from(10.),
2046 line_height: Pixels::from(10.),
2047 size: size(Pixels::from(100.), Pixels::from(100.)),
2048 };
2049
2050 let cells = get_cells(size, &mut rng);
2051 let content = convert_cells_to_content(size, &cells);
2052
2053 assert_eq!(
2054 content.cells[content_index_for_mouse(
2055 point(Pixels::from(-10.), Pixels::from(-10.)),
2056 &content.size,
2057 )]
2058 .c,
2059 cells[0][0]
2060 );
2061 assert_eq!(
2062 content.cells[content_index_for_mouse(
2063 point(Pixels::from(1000.), Pixels::from(1000.)),
2064 &content.size,
2065 )]
2066 .c,
2067 cells[9][9]
2068 );
2069 }
2070
2071 fn get_cells(size: TerminalSize, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2072 let mut cells = Vec::new();
2073
2074 for _ in 0..((size.height() / size.line_height()) as usize) {
2075 let mut row_vec = Vec::new();
2076 for _ in 0..((size.width() / size.cell_width()) as usize) {
2077 let cell_char = rng.sample(Alphanumeric) as char;
2078 row_vec.push(cell_char)
2079 }
2080 cells.push(row_vec)
2081 }
2082
2083 cells
2084 }
2085
2086 fn convert_cells_to_content(size: TerminalSize, cells: &[Vec<char>]) -> TerminalContent {
2087 let mut ic = Vec::new();
2088
2089 for (index, row) in cells.iter().enumerate() {
2090 for (cell_index, cell_char) in row.iter().enumerate() {
2091 ic.push(IndexedCell {
2092 point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2093 cell: Cell {
2094 c: *cell_char,
2095 ..Default::default()
2096 },
2097 });
2098 }
2099 }
2100
2101 TerminalContent {
2102 cells: ic,
2103 size,
2104 ..Default::default()
2105 }
2106 }
2107
2108 fn re_test(re: &str, hay: &str, expected: Vec<&str>) {
2109 let results: Vec<_> = regex::Regex::new(re)
2110 .unwrap()
2111 .find_iter(hay)
2112 .map(|m| m.as_str())
2113 .collect();
2114 assert_eq!(results, expected);
2115 }
2116 #[test]
2117 fn test_url_regex() {
2118 re_test(
2119 crate::URL_REGEX,
2120 "test http://example.com test mailto:bob@example.com train",
2121 vec!["http://example.com", "mailto:bob@example.com"],
2122 );
2123 }
2124 #[test]
2125 fn test_word_regex() {
2126 re_test(
2127 crate::WORD_REGEX,
2128 "hello, world! \"What\" is this?",
2129 vec!["hello", "world", "What", "is", "this"],
2130 );
2131 }
2132 #[test]
2133 fn test_word_regex_with_linenum() {
2134 // filename(line) and filename(line,col) as used in MSBuild output
2135 // should be considered a single "word", even though comma is
2136 // usually a word separator
2137 re_test(
2138 crate::WORD_REGEX,
2139 "a Main.cs(20) b",
2140 vec!["a", "Main.cs(20)", "b"],
2141 );
2142 re_test(
2143 crate::WORD_REGEX,
2144 "Main.cs(20,5) Error desc",
2145 vec!["Main.cs(20,5)", "Error", "desc"],
2146 );
2147 // filename:line:col is a popular format for unix tools
2148 re_test(
2149 crate::WORD_REGEX,
2150 "a Main.cs:20:5 b",
2151 vec!["a", "Main.cs:20:5", "b"],
2152 );
2153 // Some tools output "filename:line:col:message", which currently isn't
2154 // handled correctly, but might be in the future
2155 re_test(
2156 crate::WORD_REGEX,
2157 "Main.cs:20:5:Error desc",
2158 vec!["Main.cs:20:5:Error", "desc"],
2159 );
2160 }
2161}