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