1pub mod mappings;
2
3pub use alacritty_terminal;
4
5mod pty_info;
6mod terminal_hyperlinks;
7pub mod terminal_settings;
8
9use alacritty_terminal::{
10 Term,
11 event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
12 event_loop::{EventLoop, Msg, Notifier},
13 grid::{Dimensions, Grid, Row, Scroll as AlacScroll},
14 index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
15 selection::{Selection, SelectionRange, SelectionType},
16 sync::FairMutex,
17 term::{
18 Config, RenderableCursor, TermMode,
19 cell::{Cell, Flags},
20 search::{Match, RegexIter, RegexSearch},
21 },
22 tty::{self},
23 vi_mode::{ViModeCursor, ViMotion},
24 vte::ansi::{
25 ClearMode, CursorStyle as AlacCursorStyle, Handler, NamedPrivateMode, PrivateMode,
26 },
27};
28use anyhow::{Context as _, Result, bail};
29use log::trace;
30
31use futures::{
32 FutureExt,
33 channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded},
34};
35
36use itertools::Itertools as _;
37use mappings::mouse::{
38 alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
39 scroll_report,
40};
41
42use collections::{HashMap, VecDeque};
43use futures::StreamExt;
44use pty_info::{ProcessIdGetter, PtyProcessInfo};
45use serde::{Deserialize, Serialize};
46use settings::Settings;
47use smol::channel::{Receiver, Sender};
48use task::{HideStrategy, Shell, SpawnInTerminal};
49use terminal_hyperlinks::RegexSearches;
50use terminal_settings::{AlternateScroll, CursorShape, TerminalSettings};
51use theme::{ActiveTheme, Theme};
52use urlencoding;
53use util::truncate_and_trailoff;
54
55use std::{
56 borrow::Cow,
57 cmp::{self, min},
58 fmt::Display,
59 ops::{Deref, RangeInclusive},
60 path::PathBuf,
61 process::ExitStatus,
62 sync::Arc,
63 time::Instant,
64};
65use thiserror::Error;
66
67use gpui::{
68 App, AppContext as _, Bounds, ClipboardItem, Context, EventEmitter, Hsla, Keystroke, Modifiers,
69 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, Rgba,
70 ScrollWheelEvent, SharedString, Size, Task, TouchPhase, Window, actions, black, px,
71};
72
73use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
74
75actions!(
76 terminal,
77 [
78 /// Clears the terminal screen.
79 Clear,
80 /// Copies selected text to the clipboard.
81 Copy,
82 /// Pastes from the clipboard.
83 Paste,
84 /// Shows the character palette for special characters.
85 ShowCharacterPalette,
86 /// Searches for text in the terminal.
87 SearchTest,
88 /// Scrolls up by one line.
89 ScrollLineUp,
90 /// Scrolls down by one line.
91 ScrollLineDown,
92 /// Scrolls up by one page.
93 ScrollPageUp,
94 /// Scrolls down by one page.
95 ScrollPageDown,
96 /// Scrolls up by half a page.
97 ScrollHalfPageUp,
98 /// Scrolls down by half a page.
99 ScrollHalfPageDown,
100 /// Scrolls to the top of the terminal buffer.
101 ScrollToTop,
102 /// Scrolls to the bottom of the terminal buffer.
103 ScrollToBottom,
104 /// Toggles vi mode in the terminal.
105 ToggleViMode,
106 /// Selects all text in the terminal.
107 SelectAll,
108 ]
109);
110
111///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
112///Scroll multiplier that is set to 3 by default. This will be removed when I
113///Implement scroll bars.
114#[cfg(target_os = "macos")]
115const SCROLL_MULTIPLIER: f32 = 4.;
116#[cfg(not(target_os = "macos"))]
117const SCROLL_MULTIPLIER: f32 = 1.;
118const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
119const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
120const DEBUG_CELL_WIDTH: Pixels = px(5.);
121const DEBUG_LINE_HEIGHT: Pixels = px(5.);
122
123///Upward flowing events, for changing the title and such
124#[derive(Clone, Debug, PartialEq, Eq)]
125pub enum Event {
126 TitleChanged,
127 BreadcrumbsChanged,
128 CloseTerminal,
129 Bell,
130 Wakeup,
131 BlinkChanged(bool),
132 SelectionsChanged,
133 NewNavigationTarget(Option<MaybeNavigationTarget>),
134 Open(MaybeNavigationTarget),
135}
136
137#[derive(Clone, Debug, PartialEq, Eq)]
138pub struct PathLikeTarget {
139 /// File system path, absolute or relative, existing or not.
140 /// Might have line and column number(s) attached as `file.rs:1:23`
141 pub maybe_path: String,
142 /// Current working directory of the terminal
143 pub terminal_dir: Option<PathBuf>,
144}
145
146/// A string inside terminal, potentially useful as a URI that can be opened.
147#[derive(Clone, Debug, PartialEq, Eq)]
148pub enum MaybeNavigationTarget {
149 /// HTTP, git, etc. string determined by the `URL_REGEX` regex.
150 Url(String),
151 /// File system path, absolute or relative, existing or not.
152 /// Might have line and column number(s) attached as `file.rs:1:23`
153 PathLike(PathLikeTarget),
154}
155
156#[derive(Clone)]
157enum InternalEvent {
158 Resize(TerminalBounds),
159 Clear,
160 // FocusNextMatch,
161 Scroll(AlacScroll),
162 ScrollToAlacPoint(AlacPoint),
163 SetSelection(Option<(Selection, AlacPoint)>),
164 UpdateSelection(Point<Pixels>),
165 // Adjusted mouse position, should open
166 FindHyperlink(Point<Pixels>, bool),
167 // Whether keep selection when copy
168 Copy(Option<bool>),
169 // Vi mode events
170 ToggleViMode,
171 ViMotion(ViMotion),
172 MoveViCursorToAlacPoint(AlacPoint),
173}
174
175///A translation struct for Alacritty to communicate with us from their event loop
176#[derive(Clone)]
177pub struct ZedListener(pub UnboundedSender<AlacTermEvent>);
178
179impl EventListener for ZedListener {
180 fn send_event(&self, event: AlacTermEvent) {
181 self.0.unbounded_send(event).ok();
182 }
183}
184
185pub fn init(cx: &mut App) {
186 TerminalSettings::register(cx);
187}
188
189#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
190pub struct TerminalBounds {
191 pub cell_width: Pixels,
192 pub line_height: Pixels,
193 pub bounds: Bounds<Pixels>,
194}
195
196impl TerminalBounds {
197 pub fn new(line_height: Pixels, cell_width: Pixels, bounds: Bounds<Pixels>) -> Self {
198 TerminalBounds {
199 cell_width,
200 line_height,
201 bounds,
202 }
203 }
204
205 pub fn num_lines(&self) -> usize {
206 (self.bounds.size.height / self.line_height).floor() as usize
207 }
208
209 pub fn num_columns(&self) -> usize {
210 (self.bounds.size.width / self.cell_width).floor() as usize
211 }
212
213 pub fn height(&self) -> Pixels {
214 self.bounds.size.height
215 }
216
217 pub fn width(&self) -> Pixels {
218 self.bounds.size.width
219 }
220
221 pub fn cell_width(&self) -> Pixels {
222 self.cell_width
223 }
224
225 pub fn line_height(&self) -> Pixels {
226 self.line_height
227 }
228}
229
230impl Default for TerminalBounds {
231 fn default() -> Self {
232 TerminalBounds::new(
233 DEBUG_LINE_HEIGHT,
234 DEBUG_CELL_WIDTH,
235 Bounds {
236 origin: Point::default(),
237 size: Size {
238 width: DEBUG_TERMINAL_WIDTH,
239 height: DEBUG_TERMINAL_HEIGHT,
240 },
241 },
242 )
243 }
244}
245
246impl From<TerminalBounds> for WindowSize {
247 fn from(val: TerminalBounds) -> Self {
248 WindowSize {
249 num_lines: val.num_lines() as u16,
250 num_cols: val.num_columns() as u16,
251 cell_width: f32::from(val.cell_width()) as u16,
252 cell_height: f32::from(val.line_height()) as u16,
253 }
254 }
255}
256
257impl Dimensions for TerminalBounds {
258 /// Note: this is supposed to be for the back buffer's length,
259 /// but we exclusively use it to resize the terminal, which does not
260 /// use this method. We still have to implement it for the trait though,
261 /// hence, this comment.
262 fn total_lines(&self) -> usize {
263 self.screen_lines()
264 }
265
266 fn screen_lines(&self) -> usize {
267 self.num_lines()
268 }
269
270 fn columns(&self) -> usize {
271 self.num_columns()
272 }
273}
274
275#[derive(Error, Debug)]
276pub struct TerminalError {
277 pub directory: Option<PathBuf>,
278 pub program: Option<String>,
279 pub args: Option<Vec<String>>,
280 pub title_override: Option<SharedString>,
281 pub source: std::io::Error,
282}
283
284impl TerminalError {
285 pub fn fmt_directory(&self) -> String {
286 self.directory
287 .clone()
288 .map(|path| {
289 match path
290 .into_os_string()
291 .into_string()
292 .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
293 {
294 Ok(s) => s,
295 Err(s) => s,
296 }
297 })
298 .unwrap_or_else(|| "<none specified>".to_string())
299 }
300
301 pub fn fmt_shell(&self) -> String {
302 if let Some(title_override) = &self.title_override {
303 format!(
304 "{} {} ({})",
305 self.program.as_deref().unwrap_or("<system defined shell>"),
306 self.args.as_ref().into_iter().flatten().format(" "),
307 title_override
308 )
309 } else {
310 format!(
311 "{} {}",
312 self.program.as_deref().unwrap_or("<system defined shell>"),
313 self.args.as_ref().into_iter().flatten().format(" ")
314 )
315 }
316 }
317}
318
319impl Display for TerminalError {
320 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
321 let dir_string: String = self.fmt_directory();
322 let shell = self.fmt_shell();
323
324 write!(
325 f,
326 "Working directory: {} Shell command: `{}`, IOError: {}",
327 dir_string, shell, self.source
328 )
329 }
330}
331
332// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
333const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
334pub const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
335
336pub struct TerminalBuilder {
337 terminal: Terminal,
338 events_rx: UnboundedReceiver<AlacTermEvent>,
339}
340
341impl TerminalBuilder {
342 pub fn new_display_only(
343 cursor_shape: CursorShape,
344 alternate_scroll: AlternateScroll,
345 max_scroll_history_lines: Option<usize>,
346 window_id: u64,
347 ) -> Result<TerminalBuilder> {
348 // Create a display-only terminal (no actual PTY).
349 let default_cursor_style = AlacCursorStyle::from(cursor_shape);
350 let scrolling_history = max_scroll_history_lines
351 .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
352 .min(MAX_SCROLL_HISTORY_LINES);
353 let config = Config {
354 scrolling_history,
355 default_cursor_style,
356 ..Config::default()
357 };
358
359 let (events_tx, events_rx) = unbounded();
360 let mut term = Term::new(
361 config.clone(),
362 &TerminalBounds::default(),
363 ZedListener(events_tx),
364 );
365
366 if let AlternateScroll::Off = alternate_scroll {
367 term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
368 }
369
370 let term = Arc::new(FairMutex::new(term));
371
372 let terminal = Terminal {
373 task: None,
374 terminal_type: TerminalType::DisplayOnly,
375 completion_tx: None,
376 term,
377 term_config: config,
378 title_override: None,
379 events: VecDeque::with_capacity(10),
380 last_content: Default::default(),
381 last_mouse: None,
382 matches: Vec::new(),
383 selection_head: None,
384 breadcrumb_text: String::new(),
385 scroll_px: px(0.),
386 next_link_id: 0,
387 selection_phase: SelectionPhase::Ended,
388 hyperlink_regex_searches: RegexSearches::new(),
389 vi_mode_enabled: false,
390 is_ssh_terminal: false,
391 last_mouse_move_time: Instant::now(),
392 last_hyperlink_search_position: None,
393 #[cfg(windows)]
394 shell_program: None,
395 activation_script: Vec::new(),
396 template: CopyTemplate {
397 shell: Shell::System,
398 env: HashMap::default(),
399 cursor_shape,
400 alternate_scroll,
401 max_scroll_history_lines,
402 window_id,
403 },
404 child_exited: None,
405 };
406
407 Ok(TerminalBuilder {
408 terminal,
409 events_rx,
410 })
411 }
412 pub fn new(
413 working_directory: Option<PathBuf>,
414 task: Option<TaskState>,
415 shell: Shell,
416 mut env: HashMap<String, String>,
417 cursor_shape: CursorShape,
418 alternate_scroll: AlternateScroll,
419 max_scroll_history_lines: Option<usize>,
420 is_ssh_terminal: bool,
421 window_id: u64,
422 completion_tx: Option<Sender<Option<ExitStatus>>>,
423 cx: &App,
424 activation_script: Vec<String>,
425 ) -> Result<TerminalBuilder> {
426 // If the parent environment doesn't have a locale set
427 // (As is the case when launched from a .app on MacOS),
428 // and the Project doesn't have a locale set, then
429 // set a fallback for our child environment to use.
430 if std::env::var("LANG").is_err() {
431 env.entry("LANG".to_string())
432 .or_insert_with(|| "en_US.UTF-8".to_string());
433 }
434
435 env.insert("ZED_TERM".to_string(), "true".to_string());
436 env.insert("TERM_PROGRAM".to_string(), "zed".to_string());
437 env.insert("TERM".to_string(), "xterm-256color".to_string());
438 env.insert("COLORTERM".to_string(), "truecolor".to_string());
439 env.insert(
440 "TERM_PROGRAM_VERSION".to_string(),
441 release_channel::AppVersion::global(cx).to_string(),
442 );
443
444 #[derive(Default)]
445 struct ShellParams {
446 program: String,
447 args: Option<Vec<String>>,
448 title_override: Option<SharedString>,
449 }
450
451 impl ShellParams {
452 fn new(
453 program: String,
454 args: Option<Vec<String>>,
455 title_override: Option<SharedString>,
456 ) -> Self {
457 log::info!("Using {program} as shell");
458 Self {
459 program,
460 args,
461 title_override,
462 }
463 }
464 }
465
466 let shell_params = match shell.clone() {
467 Shell::System => {
468 #[cfg(target_os = "windows")]
469 {
470 Some(ShellParams::new(
471 util::shell::get_windows_system_shell(),
472 None,
473 None,
474 ))
475 }
476 #[cfg(not(target_os = "windows"))]
477 None
478 }
479 Shell::Program(program) => Some(ShellParams::new(program, None, None)),
480 Shell::WithArguments {
481 program,
482 args,
483 title_override,
484 } => Some(ShellParams::new(program, Some(args), title_override)),
485 };
486 let terminal_title_override = shell_params.as_ref().and_then(|e| e.title_override.clone());
487
488 #[cfg(windows)]
489 let shell_program = shell_params.as_ref().map(|params| {
490 use util::ResultExt;
491
492 Self::resolve_path(¶ms.program)
493 .log_err()
494 .unwrap_or(params.program.clone())
495 });
496
497 let pty_options = {
498 let alac_shell = shell_params.as_ref().map(|params| {
499 alacritty_terminal::tty::Shell::new(
500 params.program.clone(),
501 params.args.clone().unwrap_or_default(),
502 )
503 });
504
505 alacritty_terminal::tty::Options {
506 shell: alac_shell,
507 working_directory: working_directory.clone(),
508 drain_on_exit: true,
509 env: env.clone().into_iter().collect(),
510 #[cfg(windows)]
511 escape_args: true,
512 }
513 };
514
515 let default_cursor_style = AlacCursorStyle::from(cursor_shape);
516 let scrolling_history = if task.is_some() {
517 // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
518 // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
519 // cause excessive memory usage over time.
520 MAX_SCROLL_HISTORY_LINES
521 } else {
522 max_scroll_history_lines
523 .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
524 .min(MAX_SCROLL_HISTORY_LINES)
525 };
526 let config = Config {
527 scrolling_history,
528 default_cursor_style,
529 ..Config::default()
530 };
531
532 //Spawn a task so the Alacritty EventLoop can communicate with us
533 //TODO: Remove with a bounded sender which can be dispatched on &self
534 let (events_tx, events_rx) = unbounded();
535 //Set up the terminal...
536 let mut term = Term::new(
537 config.clone(),
538 &TerminalBounds::default(),
539 ZedListener(events_tx.clone()),
540 );
541
542 //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
543 if let AlternateScroll::Off = alternate_scroll {
544 term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
545 }
546
547 let term = Arc::new(FairMutex::new(term));
548
549 //Setup the pty...
550 let pty = match tty::new(&pty_options, TerminalBounds::default().into(), window_id) {
551 Ok(pty) => pty,
552 Err(error) => {
553 bail!(TerminalError {
554 directory: working_directory,
555 program: shell_params.as_ref().map(|params| params.program.clone()),
556 args: shell_params.as_ref().and_then(|params| params.args.clone()),
557 title_override: terminal_title_override,
558 source: error,
559 });
560 }
561 };
562
563 let pty_info = PtyProcessInfo::new(&pty);
564
565 //And connect them together
566 let event_loop = EventLoop::new(
567 term.clone(),
568 ZedListener(events_tx),
569 pty,
570 pty_options.drain_on_exit,
571 false,
572 )
573 .context("failed to create event loop")?;
574
575 //Kick things off
576 let pty_tx = event_loop.channel();
577 let _io_thread = event_loop.spawn(); // DANGER
578
579 let no_task = task.is_none();
580
581 let mut terminal = Terminal {
582 task,
583 terminal_type: TerminalType::Pty {
584 pty_tx: Notifier(pty_tx),
585 info: pty_info,
586 },
587 completion_tx,
588 term,
589 term_config: config,
590 title_override: terminal_title_override,
591 events: VecDeque::with_capacity(10), //Should never get this high.
592 last_content: Default::default(),
593 last_mouse: None,
594 matches: Vec::new(),
595 selection_head: None,
596 breadcrumb_text: String::new(),
597 scroll_px: px(0.),
598 next_link_id: 0,
599 selection_phase: SelectionPhase::Ended,
600 hyperlink_regex_searches: RegexSearches::new(),
601 vi_mode_enabled: false,
602 is_ssh_terminal,
603 last_mouse_move_time: Instant::now(),
604 last_hyperlink_search_position: None,
605 #[cfg(windows)]
606 shell_program,
607 activation_script: activation_script.clone(),
608 template: CopyTemplate {
609 shell,
610 env,
611 cursor_shape,
612 alternate_scroll,
613 max_scroll_history_lines,
614 window_id,
615 },
616 child_exited: None,
617 };
618
619 if !activation_script.is_empty() && no_task {
620 for activation_script in activation_script {
621 terminal.input(activation_script.into_bytes());
622 terminal.write_to_pty(if cfg!(windows) {
623 b"\r\n" as &[_]
624 } else {
625 b"\n"
626 });
627 }
628 terminal.clear();
629 }
630
631 Ok(TerminalBuilder {
632 terminal,
633 events_rx,
634 })
635 }
636
637 pub fn subscribe(mut self, cx: &Context<Terminal>) -> Terminal {
638 //Event loop
639 cx.spawn(async move |terminal, cx| {
640 while let Some(event) = self.events_rx.next().await {
641 terminal.update(cx, |terminal, cx| {
642 //Process the first event immediately for lowered latency
643 terminal.process_event(event, cx);
644 })?;
645
646 'outer: loop {
647 let mut events = Vec::new();
648
649 #[cfg(any(test, feature = "test-support"))]
650 let mut timer = cx.background_executor().simulate_random_delay().fuse();
651 #[cfg(not(any(test, feature = "test-support")))]
652 let mut timer = cx
653 .background_executor()
654 .timer(std::time::Duration::from_millis(4))
655 .fuse();
656
657 let mut wakeup = false;
658 loop {
659 futures::select_biased! {
660 _ = timer => break,
661 event = self.events_rx.next() => {
662 if let Some(event) = event {
663 if matches!(event, AlacTermEvent::Wakeup) {
664 wakeup = true;
665 } else {
666 events.push(event);
667 }
668
669 if events.len() > 100 {
670 break;
671 }
672 } else {
673 break;
674 }
675 },
676 }
677 }
678
679 if events.is_empty() && !wakeup {
680 smol::future::yield_now().await;
681 break 'outer;
682 }
683
684 terminal.update(cx, |this, cx| {
685 if wakeup {
686 this.process_event(AlacTermEvent::Wakeup, cx);
687 }
688
689 for event in events {
690 this.process_event(event, cx);
691 }
692 })?;
693 smol::future::yield_now().await;
694 }
695 }
696
697 anyhow::Ok(())
698 })
699 .detach();
700
701 self.terminal
702 }
703
704 #[cfg(windows)]
705 fn resolve_path(path: &str) -> Result<String> {
706 use windows::Win32::Storage::FileSystem::SearchPathW;
707 use windows::core::HSTRING;
708
709 let path = if path.starts_with(r"\\?\") || !path.contains(&['/', '\\']) {
710 path.to_string()
711 } else {
712 r"\\?\".to_string() + path
713 };
714
715 let required_length = unsafe { SearchPathW(None, &HSTRING::from(&path), None, None, None) };
716 let mut buf = vec![0u16; required_length as usize];
717 let size = unsafe { SearchPathW(None, &HSTRING::from(&path), None, Some(&mut buf), None) };
718
719 Ok(String::from_utf16(&buf[..size as usize])?)
720 }
721}
722
723#[derive(Debug, Clone, Deserialize, Serialize)]
724pub struct IndexedCell {
725 pub point: AlacPoint,
726 pub cell: Cell,
727}
728
729impl Deref for IndexedCell {
730 type Target = Cell;
731
732 #[inline]
733 fn deref(&self) -> &Cell {
734 &self.cell
735 }
736}
737
738// TODO: Un-pub
739#[derive(Clone)]
740pub struct TerminalContent {
741 pub cells: Vec<IndexedCell>,
742 pub mode: TermMode,
743 pub display_offset: usize,
744 pub selection_text: Option<String>,
745 pub selection: Option<SelectionRange>,
746 pub cursor: RenderableCursor,
747 pub cursor_char: char,
748 pub terminal_bounds: TerminalBounds,
749 pub last_hovered_word: Option<HoveredWord>,
750 pub scrolled_to_top: bool,
751 pub scrolled_to_bottom: bool,
752}
753
754#[derive(Debug, Clone, Eq, PartialEq)]
755pub struct HoveredWord {
756 pub word: String,
757 pub word_match: RangeInclusive<AlacPoint>,
758 pub id: usize,
759}
760
761impl Default for TerminalContent {
762 fn default() -> Self {
763 TerminalContent {
764 cells: Default::default(),
765 mode: Default::default(),
766 display_offset: Default::default(),
767 selection_text: Default::default(),
768 selection: Default::default(),
769 cursor: RenderableCursor {
770 shape: alacritty_terminal::vte::ansi::CursorShape::Block,
771 point: AlacPoint::new(Line(0), Column(0)),
772 },
773 cursor_char: Default::default(),
774 terminal_bounds: Default::default(),
775 last_hovered_word: None,
776 scrolled_to_top: false,
777 scrolled_to_bottom: false,
778 }
779 }
780}
781
782#[derive(PartialEq, Eq)]
783pub enum SelectionPhase {
784 Selecting,
785 Ended,
786}
787
788enum TerminalType {
789 Pty {
790 pty_tx: Notifier,
791 info: PtyProcessInfo,
792 },
793 DisplayOnly,
794}
795
796pub struct Terminal {
797 terminal_type: TerminalType,
798 completion_tx: Option<Sender<Option<ExitStatus>>>,
799 term: Arc<FairMutex<Term<ZedListener>>>,
800 term_config: Config,
801 events: VecDeque<InternalEvent>,
802 /// This is only used for mouse mode cell change detection
803 last_mouse: Option<(AlacPoint, AlacDirection)>,
804 pub matches: Vec<RangeInclusive<AlacPoint>>,
805 pub last_content: TerminalContent,
806 pub selection_head: Option<AlacPoint>,
807 pub breadcrumb_text: String,
808 title_override: Option<SharedString>,
809 scroll_px: Pixels,
810 next_link_id: usize,
811 selection_phase: SelectionPhase,
812 hyperlink_regex_searches: RegexSearches,
813 task: Option<TaskState>,
814 vi_mode_enabled: bool,
815 is_ssh_terminal: bool,
816 last_mouse_move_time: Instant,
817 last_hyperlink_search_position: Option<Point<Pixels>>,
818 #[cfg(windows)]
819 shell_program: Option<String>,
820 template: CopyTemplate,
821 activation_script: Vec<String>,
822 child_exited: Option<ExitStatus>,
823}
824
825struct CopyTemplate {
826 shell: Shell,
827 env: HashMap<String, String>,
828 cursor_shape: CursorShape,
829 alternate_scroll: AlternateScroll,
830 max_scroll_history_lines: Option<usize>,
831 window_id: u64,
832}
833
834#[derive(Debug)]
835pub struct TaskState {
836 pub status: TaskStatus,
837 pub completion_rx: Receiver<Option<ExitStatus>>,
838 pub spawned_task: SpawnInTerminal,
839}
840
841/// A status of the current terminal tab's task.
842#[derive(Debug, Clone, Copy, PartialEq, Eq)]
843pub enum TaskStatus {
844 /// The task had been started, but got cancelled or somehow otherwise it did not
845 /// report its exit code before the terminal event loop was shut down.
846 Unknown,
847 /// The task is started and running currently.
848 Running,
849 /// After the start, the task stopped running and reported its error code back.
850 Completed { success: bool },
851}
852
853impl TaskStatus {
854 fn register_terminal_exit(&mut self) {
855 if self == &Self::Running {
856 *self = Self::Unknown;
857 }
858 }
859
860 fn register_task_exit(&mut self, error_code: i32) {
861 *self = TaskStatus::Completed {
862 success: error_code == 0,
863 };
864 }
865}
866
867impl Terminal {
868 fn process_event(&mut self, event: AlacTermEvent, cx: &mut Context<Self>) {
869 match event {
870 AlacTermEvent::Title(title) => {
871 // ignore default shell program title change as windows always sends those events
872 // and it would end up showing the shell executable path in breadcrumbs
873 #[cfg(windows)]
874 {
875 if self
876 .shell_program
877 .as_ref()
878 .map(|e| *e == title)
879 .unwrap_or(false)
880 {
881 return;
882 }
883 }
884
885 self.breadcrumb_text = title;
886 cx.emit(Event::BreadcrumbsChanged);
887 }
888 AlacTermEvent::ResetTitle => {
889 self.breadcrumb_text = String::new();
890 cx.emit(Event::BreadcrumbsChanged);
891 }
892 AlacTermEvent::ClipboardStore(_, data) => {
893 cx.write_to_clipboard(ClipboardItem::new_string(data))
894 }
895 AlacTermEvent::ClipboardLoad(_, format) => {
896 self.write_to_pty(
897 match &cx.read_from_clipboard().and_then(|item| item.text()) {
898 // The terminal only supports pasting strings, not images.
899 Some(text) => format(text),
900 _ => format(""),
901 }
902 .into_bytes(),
903 )
904 }
905 AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.into_bytes()),
906 AlacTermEvent::TextAreaSizeRequest(format) => {
907 self.write_to_pty(format(self.last_content.terminal_bounds.into()).into_bytes())
908 }
909 AlacTermEvent::CursorBlinkingChange => {
910 let terminal = self.term.lock();
911 let blinking = terminal.cursor_style().blinking;
912 cx.emit(Event::BlinkChanged(blinking));
913 }
914 AlacTermEvent::Bell => {
915 cx.emit(Event::Bell);
916 }
917 AlacTermEvent::Exit => self.register_task_finished(None, cx),
918 AlacTermEvent::MouseCursorDirty => {
919 //NOOP, Handled in render
920 }
921 AlacTermEvent::Wakeup => {
922 cx.emit(Event::Wakeup);
923
924 if let TerminalType::Pty { info, .. } = &mut self.terminal_type {
925 if info.has_changed() {
926 cx.emit(Event::TitleChanged);
927 }
928 }
929 }
930 AlacTermEvent::ColorRequest(index, format) => {
931 // It's important that the color request is processed here to retain relative order
932 // with other PTY writes. Otherwise applications might witness out-of-order
933 // responses to requests. For example: An application sending `OSC 11 ; ? ST`
934 // (color request) followed by `CSI c` (request device attributes) would receive
935 // the response to `CSI c` first.
936 // Instead of locking, we could store the colors in `self.last_content`. But then
937 // we might respond with out of date value if a "set color" sequence is immediately
938 // followed by a color request sequence.
939 let color = self.term.lock().colors()[index]
940 .unwrap_or_else(|| to_alac_rgb(get_color_at_index(index, cx.theme().as_ref())));
941 self.write_to_pty(format(color).into_bytes());
942 }
943 AlacTermEvent::ChildExit(error_code) => {
944 self.register_task_finished(Some(error_code), cx);
945 }
946 }
947 }
948
949 pub fn selection_started(&self) -> bool {
950 self.selection_phase == SelectionPhase::Selecting
951 }
952
953 fn process_terminal_event(
954 &mut self,
955 event: &InternalEvent,
956 term: &mut Term<ZedListener>,
957 window: &mut Window,
958 cx: &mut Context<Self>,
959 ) {
960 match event {
961 &InternalEvent::Resize(mut new_bounds) => {
962 trace!("Resizing: new_bounds={new_bounds:?}");
963 new_bounds.bounds.size.height =
964 cmp::max(new_bounds.line_height, new_bounds.height());
965 new_bounds.bounds.size.width = cmp::max(new_bounds.cell_width, new_bounds.width());
966
967 self.last_content.terminal_bounds = new_bounds;
968
969 if let TerminalType::Pty { pty_tx, .. } = &self.terminal_type {
970 pty_tx.0.send(Msg::Resize(new_bounds.into())).ok();
971 }
972
973 term.resize(new_bounds);
974 }
975 InternalEvent::Clear => {
976 trace!("Clearing");
977 // Clear back buffer
978 term.clear_screen(ClearMode::Saved);
979
980 let cursor = term.grid().cursor.point;
981
982 // Clear the lines above
983 term.grid_mut().reset_region(..cursor.line);
984
985 // Copy the current line up
986 let line = term.grid()[cursor.line][..Column(term.grid().columns())]
987 .iter()
988 .cloned()
989 .enumerate()
990 .collect::<Vec<(usize, Cell)>>();
991
992 for (i, cell) in line {
993 term.grid_mut()[Line(0)][Column(i)] = cell;
994 }
995
996 // Reset the cursor
997 term.grid_mut().cursor.point =
998 AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
999 let new_cursor = term.grid().cursor.point;
1000
1001 // Clear the lines below the new cursor
1002 if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
1003 term.grid_mut().reset_region((new_cursor.line + 1)..);
1004 }
1005
1006 cx.emit(Event::Wakeup);
1007 }
1008 InternalEvent::Scroll(scroll) => {
1009 trace!("Scrolling: scroll={scroll:?}");
1010 term.scroll_display(*scroll);
1011 self.refresh_hovered_word(window);
1012
1013 if self.vi_mode_enabled {
1014 match *scroll {
1015 AlacScroll::Delta(delta) => {
1016 term.vi_mode_cursor = term.vi_mode_cursor.scroll(term, delta);
1017 }
1018 AlacScroll::PageUp => {
1019 let lines = term.screen_lines() as i32;
1020 term.vi_mode_cursor = term.vi_mode_cursor.scroll(term, lines);
1021 }
1022 AlacScroll::PageDown => {
1023 let lines = -(term.screen_lines() as i32);
1024 term.vi_mode_cursor = term.vi_mode_cursor.scroll(term, lines);
1025 }
1026 AlacScroll::Top => {
1027 let point = AlacPoint::new(term.topmost_line(), Column(0));
1028 term.vi_mode_cursor = ViModeCursor::new(point);
1029 }
1030 AlacScroll::Bottom => {
1031 let point = AlacPoint::new(term.bottommost_line(), Column(0));
1032 term.vi_mode_cursor = ViModeCursor::new(point);
1033 }
1034 }
1035 if let Some(mut selection) = term.selection.take() {
1036 let point = term.vi_mode_cursor.point;
1037 selection.update(point, AlacDirection::Right);
1038 term.selection = Some(selection);
1039
1040 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1041 if let Some(selection_text) = term.selection_to_string() {
1042 cx.write_to_primary(ClipboardItem::new_string(selection_text));
1043 }
1044
1045 self.selection_head = Some(point);
1046 cx.emit(Event::SelectionsChanged)
1047 }
1048 }
1049 }
1050 InternalEvent::SetSelection(selection) => {
1051 trace!("Setting selection: selection={selection:?}");
1052 term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
1053
1054 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1055 if let Some(selection_text) = term.selection_to_string() {
1056 cx.write_to_primary(ClipboardItem::new_string(selection_text));
1057 }
1058
1059 if let Some((_, head)) = selection {
1060 self.selection_head = Some(*head);
1061 }
1062 cx.emit(Event::SelectionsChanged)
1063 }
1064 InternalEvent::UpdateSelection(position) => {
1065 trace!("Updating selection: position={position:?}");
1066 if let Some(mut selection) = term.selection.take() {
1067 let (point, side) = grid_point_and_side(
1068 *position,
1069 self.last_content.terminal_bounds,
1070 term.grid().display_offset(),
1071 );
1072
1073 selection.update(point, side);
1074 term.selection = Some(selection);
1075
1076 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1077 if let Some(selection_text) = term.selection_to_string() {
1078 cx.write_to_primary(ClipboardItem::new_string(selection_text));
1079 }
1080
1081 self.selection_head = Some(point);
1082 cx.emit(Event::SelectionsChanged)
1083 }
1084 }
1085
1086 InternalEvent::Copy(keep_selection) => {
1087 trace!("Copying selection: keep_selection={keep_selection:?}");
1088 if let Some(txt) = term.selection_to_string() {
1089 cx.write_to_clipboard(ClipboardItem::new_string(txt));
1090 if !keep_selection.unwrap_or_else(|| {
1091 let settings = TerminalSettings::get_global(cx);
1092 settings.keep_selection_on_copy
1093 }) {
1094 self.events.push_back(InternalEvent::SetSelection(None));
1095 }
1096 }
1097 }
1098 InternalEvent::ScrollToAlacPoint(point) => {
1099 trace!("Scrolling to point: point={point:?}");
1100 term.scroll_to_point(*point);
1101 self.refresh_hovered_word(window);
1102 }
1103 InternalEvent::MoveViCursorToAlacPoint(point) => {
1104 trace!("Move vi cursor to point: point={point:?}");
1105 term.vi_goto_point(*point);
1106 self.refresh_hovered_word(window);
1107 }
1108 InternalEvent::ToggleViMode => {
1109 trace!("Toggling vi mode");
1110 self.vi_mode_enabled = !self.vi_mode_enabled;
1111 term.toggle_vi_mode();
1112 }
1113 InternalEvent::ViMotion(motion) => {
1114 trace!("Performing vi motion: motion={motion:?}");
1115 term.vi_motion(*motion);
1116 }
1117 InternalEvent::FindHyperlink(position, open) => {
1118 trace!("Finding hyperlink at position: position={position:?}, open={open:?}");
1119 let prev_hovered_word = self.last_content.last_hovered_word.take();
1120
1121 let point = grid_point(
1122 *position,
1123 self.last_content.terminal_bounds,
1124 term.grid().display_offset(),
1125 )
1126 .grid_clamp(term, Boundary::Grid);
1127
1128 match terminal_hyperlinks::find_from_grid_point(
1129 term,
1130 point,
1131 &mut self.hyperlink_regex_searches,
1132 ) {
1133 Some((maybe_url_or_path, is_url, url_match)) => {
1134 let target = if is_url {
1135 // Treat "file://" URLs like file paths to ensure
1136 // that line numbers at the end of the path are
1137 // handled correctly.
1138 // file://{path} should be urldecoded, returning a urldecoded {path}
1139 if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
1140 let decoded_path = urlencoding::decode(path)
1141 .map(|decoded| decoded.into_owned())
1142 .unwrap_or(path.to_owned());
1143
1144 MaybeNavigationTarget::PathLike(PathLikeTarget {
1145 maybe_path: decoded_path,
1146 terminal_dir: self.working_directory(),
1147 })
1148 } else {
1149 MaybeNavigationTarget::Url(maybe_url_or_path.clone())
1150 }
1151 } else {
1152 MaybeNavigationTarget::PathLike(PathLikeTarget {
1153 maybe_path: maybe_url_or_path.clone(),
1154 terminal_dir: self.working_directory(),
1155 })
1156 };
1157 if *open {
1158 cx.emit(Event::Open(target));
1159 } else {
1160 self.update_selected_word(
1161 prev_hovered_word,
1162 url_match,
1163 maybe_url_or_path,
1164 target,
1165 cx,
1166 );
1167 }
1168 }
1169 None => {
1170 cx.emit(Event::NewNavigationTarget(None));
1171 }
1172 }
1173 }
1174 }
1175 }
1176
1177 fn update_selected_word(
1178 &mut self,
1179 prev_word: Option<HoveredWord>,
1180 word_match: RangeInclusive<AlacPoint>,
1181 word: String,
1182 navigation_target: MaybeNavigationTarget,
1183 cx: &mut Context<Self>,
1184 ) {
1185 if let Some(prev_word) = prev_word
1186 && prev_word.word == word
1187 && prev_word.word_match == word_match
1188 {
1189 self.last_content.last_hovered_word = Some(HoveredWord {
1190 word,
1191 word_match,
1192 id: prev_word.id,
1193 });
1194 return;
1195 }
1196
1197 self.last_content.last_hovered_word = Some(HoveredWord {
1198 word,
1199 word_match,
1200 id: self.next_link_id(),
1201 });
1202 cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
1203 cx.notify()
1204 }
1205
1206 fn next_link_id(&mut self) -> usize {
1207 let res = self.next_link_id;
1208 self.next_link_id = self.next_link_id.wrapping_add(1);
1209 res
1210 }
1211
1212 pub fn last_content(&self) -> &TerminalContent {
1213 &self.last_content
1214 }
1215
1216 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
1217 self.term_config.default_cursor_style = cursor_shape.into();
1218 self.term.lock().set_options(self.term_config.clone());
1219 }
1220
1221 pub fn write_output(&mut self, bytes: &[u8], cx: &mut Context<Self>) {
1222 // Inject bytes directly into the terminal emulator and refresh the UI.
1223 // This bypasses the PTY/event loop for display-only terminals.
1224 //
1225 // We first convert LF to CRLF, to get the expected line wrapping in Alacritty.
1226 // When output comes from piped commands (not a PTY) such as codex-acp, and that
1227 // output only contains LF (\n) without a CR (\r) after it, such as the output
1228 // of the `ls` command when running outside a PTY, Alacritty moves the cursor
1229 // cursor down a line but does not move it back to the initial column. This makes
1230 // the rendered output look ridiculous. To prevent this, we insert a CR (\r) before
1231 // each LF that didn't already have one. (Alacritty doesn't have a setting for this.)
1232 let mut converted = Vec::with_capacity(bytes.len());
1233 let mut prev_byte = 0u8;
1234 for &byte in bytes {
1235 if byte == b'\n' && prev_byte != b'\r' {
1236 converted.push(b'\r');
1237 }
1238 converted.push(byte);
1239 prev_byte = byte;
1240 }
1241
1242 let mut processor = alacritty_terminal::vte::ansi::Processor::<
1243 alacritty_terminal::vte::ansi::StdSyncHandler,
1244 >::new();
1245 {
1246 let mut term = self.term.lock();
1247 processor.advance(&mut *term, &converted);
1248 }
1249 cx.emit(Event::Wakeup);
1250 }
1251
1252 pub fn total_lines(&self) -> usize {
1253 let term = self.term.clone();
1254 let terminal = term.lock_unfair();
1255 terminal.total_lines()
1256 }
1257
1258 pub fn viewport_lines(&self) -> usize {
1259 let term = self.term.clone();
1260 let terminal = term.lock_unfair();
1261 terminal.screen_lines()
1262 }
1263
1264 //To test:
1265 //- Activate match on terminal (scrolling and selection)
1266 //- Editor search snapping behavior
1267
1268 pub fn activate_match(&mut self, index: usize) {
1269 if let Some(search_match) = self.matches.get(index).cloned() {
1270 self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1271 if self.vi_mode_enabled {
1272 self.events
1273 .push_back(InternalEvent::MoveViCursorToAlacPoint(*search_match.end()));
1274 } else {
1275 self.events
1276 .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1277 }
1278 }
1279 }
1280
1281 pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1282 let matches_to_select = self
1283 .matches
1284 .iter()
1285 .filter(|self_match| matches.contains(self_match))
1286 .cloned()
1287 .collect::<Vec<_>>();
1288 for match_to_select in matches_to_select {
1289 self.set_selection(Some((
1290 make_selection(&match_to_select),
1291 *match_to_select.end(),
1292 )));
1293 }
1294 }
1295
1296 pub fn select_all(&mut self) {
1297 let term = self.term.lock();
1298 let start = AlacPoint::new(term.topmost_line(), Column(0));
1299 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1300 drop(term);
1301 self.set_selection(Some((make_selection(&(start..=end)), end)));
1302 }
1303
1304 fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1305 self.events
1306 .push_back(InternalEvent::SetSelection(selection));
1307 }
1308
1309 pub fn copy(&mut self, keep_selection: Option<bool>) {
1310 self.events.push_back(InternalEvent::Copy(keep_selection));
1311 }
1312
1313 pub fn clear(&mut self) {
1314 self.events.push_back(InternalEvent::Clear)
1315 }
1316
1317 pub fn scroll_line_up(&mut self) {
1318 self.events
1319 .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1320 }
1321
1322 pub fn scroll_up_by(&mut self, lines: usize) {
1323 self.events
1324 .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1325 }
1326
1327 pub fn scroll_line_down(&mut self) {
1328 self.events
1329 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1330 }
1331
1332 pub fn scroll_down_by(&mut self, lines: usize) {
1333 self.events
1334 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1335 }
1336
1337 pub fn scroll_page_up(&mut self) {
1338 self.events
1339 .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1340 }
1341
1342 pub fn scroll_page_down(&mut self) {
1343 self.events
1344 .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1345 }
1346
1347 pub fn scroll_to_top(&mut self) {
1348 self.events
1349 .push_back(InternalEvent::Scroll(AlacScroll::Top));
1350 }
1351
1352 pub fn scroll_to_bottom(&mut self) {
1353 self.events
1354 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1355 }
1356
1357 pub fn scrolled_to_top(&self) -> bool {
1358 self.last_content.scrolled_to_top
1359 }
1360
1361 pub fn scrolled_to_bottom(&self) -> bool {
1362 self.last_content.scrolled_to_bottom
1363 }
1364
1365 ///Resize the terminal and the PTY.
1366 pub fn set_size(&mut self, new_bounds: TerminalBounds) {
1367 if self.last_content.terminal_bounds != new_bounds {
1368 self.events.push_back(InternalEvent::Resize(new_bounds))
1369 }
1370 }
1371
1372 /// Write the Input payload to the PTY, if applicable.
1373 /// (This is a no-op for display-only terminals.)
1374 fn write_to_pty(&self, input: impl Into<Cow<'static, [u8]>>) {
1375 if let TerminalType::Pty { pty_tx, .. } = &self.terminal_type {
1376 pty_tx.notify(input.into());
1377 }
1378 }
1379
1380 pub fn input(&mut self, input: impl Into<Cow<'static, [u8]>>) {
1381 self.events
1382 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1383 self.events.push_back(InternalEvent::SetSelection(None));
1384
1385 self.write_to_pty(input);
1386 }
1387
1388 pub fn toggle_vi_mode(&mut self) {
1389 self.events.push_back(InternalEvent::ToggleViMode);
1390 }
1391
1392 pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1393 if !self.vi_mode_enabled {
1394 return;
1395 }
1396
1397 let key: Cow<'_, str> = if keystroke.modifiers.shift {
1398 Cow::Owned(keystroke.key.to_uppercase())
1399 } else {
1400 Cow::Borrowed(keystroke.key.as_str())
1401 };
1402
1403 let motion: Option<ViMotion> = match key.as_ref() {
1404 "h" | "left" => Some(ViMotion::Left),
1405 "j" | "down" => Some(ViMotion::Down),
1406 "k" | "up" => Some(ViMotion::Up),
1407 "l" | "right" => Some(ViMotion::Right),
1408 "w" => Some(ViMotion::WordRight),
1409 "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1410 "e" => Some(ViMotion::WordRightEnd),
1411 "%" => Some(ViMotion::Bracket),
1412 "$" => Some(ViMotion::Last),
1413 "0" => Some(ViMotion::First),
1414 "^" => Some(ViMotion::FirstOccupied),
1415 "H" => Some(ViMotion::High),
1416 "M" => Some(ViMotion::Middle),
1417 "L" => Some(ViMotion::Low),
1418 _ => None,
1419 };
1420
1421 if let Some(motion) = motion {
1422 let cursor = self.last_content.cursor.point;
1423 let cursor_pos = Point {
1424 x: cursor.column.0 as f32 * self.last_content.terminal_bounds.cell_width,
1425 y: cursor.line.0 as f32 * self.last_content.terminal_bounds.line_height,
1426 };
1427 self.events
1428 .push_back(InternalEvent::UpdateSelection(cursor_pos));
1429 self.events.push_back(InternalEvent::ViMotion(motion));
1430 return;
1431 }
1432
1433 let scroll_motion = match key.as_ref() {
1434 "g" => Some(AlacScroll::Top),
1435 "G" => Some(AlacScroll::Bottom),
1436 "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1437 "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1438 "d" if keystroke.modifiers.control => {
1439 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1440 Some(AlacScroll::Delta(-amount))
1441 }
1442 "u" if keystroke.modifiers.control => {
1443 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1444 Some(AlacScroll::Delta(amount))
1445 }
1446 _ => None,
1447 };
1448
1449 if let Some(scroll_motion) = scroll_motion {
1450 self.events.push_back(InternalEvent::Scroll(scroll_motion));
1451 return;
1452 }
1453
1454 match key.as_ref() {
1455 "v" => {
1456 let point = self.last_content.cursor.point;
1457 let selection_type = SelectionType::Simple;
1458 let side = AlacDirection::Right;
1459 let selection = Selection::new(selection_type, point, side);
1460 self.events
1461 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1462 }
1463
1464 "escape" => {
1465 self.events.push_back(InternalEvent::SetSelection(None));
1466 }
1467
1468 "y" => {
1469 self.copy(Some(false));
1470 }
1471
1472 "i" => {
1473 self.scroll_to_bottom();
1474 self.toggle_vi_mode();
1475 }
1476 _ => {}
1477 }
1478 }
1479
1480 pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1481 if self.vi_mode_enabled {
1482 self.vi_motion(keystroke);
1483 return true;
1484 }
1485
1486 // Keep default terminal behavior
1487 let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1488 if let Some(esc) = esc {
1489 match esc {
1490 Cow::Borrowed(string) => self.input(string.as_bytes()),
1491 Cow::Owned(string) => self.input(string.into_bytes()),
1492 };
1493 true
1494 } else {
1495 false
1496 }
1497 }
1498
1499 pub fn try_modifiers_change(
1500 &mut self,
1501 modifiers: &Modifiers,
1502 window: &Window,
1503 cx: &mut Context<Self>,
1504 ) {
1505 if self
1506 .last_content
1507 .terminal_bounds
1508 .bounds
1509 .contains(&window.mouse_position())
1510 && modifiers.secondary()
1511 {
1512 self.refresh_hovered_word(window);
1513 }
1514 cx.notify();
1515 }
1516
1517 ///Paste text into the terminal
1518 pub fn paste(&mut self, text: &str) {
1519 let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1520 format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1521 } else {
1522 text.replace("\r\n", "\r").replace('\n', "\r")
1523 };
1524
1525 self.input(paste_text.into_bytes());
1526 }
1527
1528 pub fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1529 let term = self.term.clone();
1530 let mut terminal = term.lock_unfair();
1531 //Note that the ordering of events matters for event processing
1532 while let Some(e) = self.events.pop_front() {
1533 self.process_terminal_event(&e, &mut terminal, window, cx)
1534 }
1535
1536 self.last_content = Self::make_content(&terminal, &self.last_content);
1537 }
1538
1539 fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1540 let content = term.renderable_content();
1541
1542 // Pre-allocate with estimated size to reduce reallocations
1543 let estimated_size = content.display_iter.size_hint().0;
1544 let mut cells = Vec::with_capacity(estimated_size);
1545
1546 cells.extend(content.display_iter.map(|ic| IndexedCell {
1547 point: ic.point,
1548 cell: ic.cell.clone(),
1549 }));
1550
1551 let selection_text = if content.selection.is_some() {
1552 term.selection_to_string()
1553 } else {
1554 None
1555 };
1556
1557 TerminalContent {
1558 cells,
1559 mode: content.mode,
1560 display_offset: content.display_offset,
1561 selection_text,
1562 selection: content.selection,
1563 cursor: content.cursor,
1564 cursor_char: term.grid()[content.cursor.point].c,
1565 terminal_bounds: last_content.terminal_bounds,
1566 last_hovered_word: last_content.last_hovered_word.clone(),
1567 scrolled_to_top: content.display_offset == term.history_size(),
1568 scrolled_to_bottom: content.display_offset == 0,
1569 }
1570 }
1571
1572 pub fn get_content(&self) -> String {
1573 let term = self.term.lock_unfair();
1574 let start = AlacPoint::new(term.topmost_line(), Column(0));
1575 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1576 term.bounds_to_string(start, end)
1577 }
1578
1579 pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1580 let term = self.term.clone();
1581 let terminal = term.lock_unfair();
1582 let grid = terminal.grid();
1583 let mut lines = Vec::new();
1584
1585 let mut current_line = grid.bottommost_line().0;
1586 let topmost_line = grid.topmost_line().0;
1587
1588 while current_line >= topmost_line && lines.len() < n {
1589 let logical_line_start = self.find_logical_line_start(grid, current_line, topmost_line);
1590 let logical_line = self.construct_logical_line(grid, logical_line_start, current_line);
1591
1592 if let Some(line) = self.process_line(logical_line) {
1593 lines.push(line);
1594 }
1595
1596 // Move to the line above the start of the current logical line
1597 current_line = logical_line_start - 1;
1598 }
1599
1600 lines.reverse();
1601 lines
1602 }
1603
1604 fn find_logical_line_start(&self, grid: &Grid<Cell>, current: i32, topmost: i32) -> i32 {
1605 let mut line_start = current;
1606 while line_start > topmost {
1607 let prev_line = Line(line_start - 1);
1608 let last_cell = &grid[prev_line][Column(grid.columns() - 1)];
1609 if !last_cell.flags.contains(Flags::WRAPLINE) {
1610 break;
1611 }
1612 line_start -= 1;
1613 }
1614 line_start
1615 }
1616
1617 fn construct_logical_line(&self, grid: &Grid<Cell>, start: i32, end: i32) -> String {
1618 let mut logical_line = String::new();
1619 for row in start..=end {
1620 let grid_row = &grid[Line(row)];
1621 logical_line.push_str(&row_to_string(grid_row));
1622 }
1623 logical_line
1624 }
1625
1626 fn process_line(&self, line: String) -> Option<String> {
1627 let trimmed = line.trim_end().to_string();
1628 if !trimmed.is_empty() {
1629 Some(trimmed)
1630 } else {
1631 None
1632 }
1633 }
1634
1635 pub fn focus_in(&self) {
1636 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1637 self.write_to_pty("\x1b[I".as_bytes());
1638 }
1639 }
1640
1641 pub fn focus_out(&mut self) {
1642 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1643 self.write_to_pty("\x1b[O".as_bytes());
1644 }
1645 }
1646
1647 pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1648 match self.last_mouse {
1649 Some((old_point, old_side)) => {
1650 if old_point == point && old_side == side {
1651 false
1652 } else {
1653 self.last_mouse = Some((point, side));
1654 true
1655 }
1656 }
1657 None => {
1658 self.last_mouse = Some((point, side));
1659 true
1660 }
1661 }
1662 }
1663
1664 pub fn mouse_mode(&self, shift: bool) -> bool {
1665 self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1666 }
1667
1668 pub fn mouse_move(&mut self, e: &MouseMoveEvent, cx: &mut Context<Self>) {
1669 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1670 if self.mouse_mode(e.modifiers.shift) {
1671 let (point, side) = grid_point_and_side(
1672 position,
1673 self.last_content.terminal_bounds,
1674 self.last_content.display_offset,
1675 );
1676
1677 if self.mouse_changed(point, side)
1678 && let Some(bytes) =
1679 mouse_moved_report(point, e.pressed_button, e.modifiers, self.last_content.mode)
1680 {
1681 self.write_to_pty(bytes);
1682 }
1683 } else if e.modifiers.secondary() {
1684 self.word_from_position(e.position);
1685 }
1686 cx.notify();
1687 }
1688
1689 fn word_from_position(&mut self, position: Point<Pixels>) {
1690 if self.selection_phase == SelectionPhase::Selecting {
1691 self.last_content.last_hovered_word = None;
1692 } else if self.last_content.terminal_bounds.bounds.contains(&position) {
1693 // Throttle hyperlink searches to avoid excessive processing
1694 let now = Instant::now();
1695 let should_search = if let Some(last_pos) = self.last_hyperlink_search_position {
1696 // Only search if mouse moved significantly or enough time passed
1697 let distance_moved =
1698 ((position.x - last_pos.x).abs() + (position.y - last_pos.y).abs()) > px(5.0);
1699 let time_elapsed = now.duration_since(self.last_mouse_move_time).as_millis() > 100;
1700 distance_moved || time_elapsed
1701 } else {
1702 true
1703 };
1704
1705 if should_search {
1706 self.last_mouse_move_time = now;
1707 self.last_hyperlink_search_position = Some(position);
1708 self.events.push_back(InternalEvent::FindHyperlink(
1709 position - self.last_content.terminal_bounds.bounds.origin,
1710 false,
1711 ));
1712 }
1713 } else {
1714 self.last_content.last_hovered_word = None;
1715 }
1716 }
1717
1718 pub fn select_word_at_event_position(&mut self, e: &MouseDownEvent) {
1719 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1720 let (point, side) = grid_point_and_side(
1721 position,
1722 self.last_content.terminal_bounds,
1723 self.last_content.display_offset,
1724 );
1725 let selection = Selection::new(SelectionType::Semantic, point, side);
1726 self.events
1727 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1728 }
1729
1730 pub fn mouse_drag(
1731 &mut self,
1732 e: &MouseMoveEvent,
1733 region: Bounds<Pixels>,
1734 cx: &mut Context<Self>,
1735 ) {
1736 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1737 if !self.mouse_mode(e.modifiers.shift) {
1738 self.selection_phase = SelectionPhase::Selecting;
1739 // Alacritty has the same ordering, of first updating the selection
1740 // then scrolling 15ms later
1741 self.events
1742 .push_back(InternalEvent::UpdateSelection(position));
1743
1744 // Doesn't make sense to scroll the alt screen
1745 if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1746 let scroll_lines = match self.drag_line_delta(e, region) {
1747 Some(value) => value,
1748 None => return,
1749 };
1750
1751 self.events
1752 .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1753 }
1754
1755 cx.notify();
1756 }
1757 }
1758
1759 fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<i32> {
1760 let top = region.origin.y;
1761 let bottom = region.bottom_left().y;
1762
1763 let scroll_lines = if e.position.y < top {
1764 let scroll_delta = (top - e.position.y).pow(1.1);
1765 (scroll_delta / self.last_content.terminal_bounds.line_height).ceil() as i32
1766 } else if e.position.y > bottom {
1767 let scroll_delta = -((e.position.y - bottom).pow(1.1));
1768 (scroll_delta / self.last_content.terminal_bounds.line_height).floor() as i32
1769 } else {
1770 return None;
1771 };
1772
1773 Some(scroll_lines.clamp(-3, 3))
1774 }
1775
1776 pub fn mouse_down(&mut self, e: &MouseDownEvent, _cx: &mut Context<Self>) {
1777 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1778 let point = grid_point(
1779 position,
1780 self.last_content.terminal_bounds,
1781 self.last_content.display_offset,
1782 );
1783
1784 if self.mouse_mode(e.modifiers.shift) {
1785 if let Some(bytes) =
1786 mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1787 {
1788 self.write_to_pty(bytes);
1789 }
1790 } else {
1791 match e.button {
1792 MouseButton::Left => {
1793 let (point, side) = grid_point_and_side(
1794 position,
1795 self.last_content.terminal_bounds,
1796 self.last_content.display_offset,
1797 );
1798
1799 let selection_type = match e.click_count {
1800 0 => return, //This is a release
1801 1 => Some(SelectionType::Simple),
1802 2 => Some(SelectionType::Semantic),
1803 3 => Some(SelectionType::Lines),
1804 _ => None,
1805 };
1806
1807 if selection_type == Some(SelectionType::Simple) && e.modifiers.shift {
1808 self.events
1809 .push_back(InternalEvent::UpdateSelection(position));
1810 return;
1811 }
1812
1813 let selection = selection_type
1814 .map(|selection_type| Selection::new(selection_type, point, side));
1815
1816 if let Some(sel) = selection {
1817 self.events
1818 .push_back(InternalEvent::SetSelection(Some((sel, point))));
1819 }
1820 }
1821 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1822 MouseButton::Middle => {
1823 if let Some(item) = _cx.read_from_primary() {
1824 let text = item.text().unwrap_or_default();
1825 self.input(text.into_bytes());
1826 }
1827 }
1828 _ => {}
1829 }
1830 }
1831 }
1832
1833 pub fn mouse_up(&mut self, e: &MouseUpEvent, cx: &Context<Self>) {
1834 let setting = TerminalSettings::get_global(cx);
1835
1836 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1837 if self.mouse_mode(e.modifiers.shift) {
1838 let point = grid_point(
1839 position,
1840 self.last_content.terminal_bounds,
1841 self.last_content.display_offset,
1842 );
1843
1844 if let Some(bytes) =
1845 mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1846 {
1847 self.write_to_pty(bytes);
1848 }
1849 } else {
1850 if e.button == MouseButton::Left && setting.copy_on_select {
1851 self.copy(Some(true));
1852 }
1853
1854 //Hyperlinks
1855 if self.selection_phase == SelectionPhase::Ended {
1856 let mouse_cell_index =
1857 content_index_for_mouse(position, &self.last_content.terminal_bounds);
1858 if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1859 cx.open_url(link.uri());
1860 } else if e.modifiers.secondary() {
1861 self.events
1862 .push_back(InternalEvent::FindHyperlink(position, true));
1863 }
1864 }
1865 }
1866
1867 self.selection_phase = SelectionPhase::Ended;
1868 self.last_mouse = None;
1869 }
1870
1871 ///Scroll the terminal
1872 pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent) {
1873 let mouse_mode = self.mouse_mode(e.shift);
1874
1875 if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1876 if mouse_mode {
1877 let point = grid_point(
1878 e.position - self.last_content.terminal_bounds.bounds.origin,
1879 self.last_content.terminal_bounds,
1880 self.last_content.display_offset,
1881 );
1882
1883 if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1884 {
1885 for scroll in scrolls {
1886 self.write_to_pty(scroll);
1887 }
1888 };
1889 } else if self
1890 .last_content
1891 .mode
1892 .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1893 && !e.shift
1894 {
1895 self.write_to_pty(alt_scroll(scroll_lines));
1896 } else if scroll_lines != 0 {
1897 let scroll = AlacScroll::Delta(scroll_lines);
1898
1899 self.events.push_back(InternalEvent::Scroll(scroll));
1900 }
1901 }
1902 }
1903
1904 fn refresh_hovered_word(&mut self, window: &Window) {
1905 self.word_from_position(window.mouse_position());
1906 }
1907
1908 fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1909 let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1910 let line_height = self.last_content.terminal_bounds.line_height;
1911 match e.touch_phase {
1912 /* Reset scroll state on started */
1913 TouchPhase::Started => {
1914 self.scroll_px = px(0.);
1915 None
1916 }
1917 /* Calculate the appropriate scroll lines */
1918 TouchPhase::Moved => {
1919 let old_offset = (self.scroll_px / line_height) as i32;
1920
1921 self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1922
1923 let new_offset = (self.scroll_px / line_height) as i32;
1924
1925 // Whenever we hit the edges, reset our stored scroll to 0
1926 // so we can respond to changes in direction quickly
1927 self.scroll_px %= self.last_content.terminal_bounds.height();
1928
1929 Some(new_offset - old_offset)
1930 }
1931 TouchPhase::Ended => None,
1932 }
1933 }
1934
1935 pub fn find_matches(
1936 &self,
1937 mut searcher: RegexSearch,
1938 cx: &Context<Self>,
1939 ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1940 let term = self.term.clone();
1941 cx.background_spawn(async move {
1942 let term = term.lock();
1943
1944 all_search_matches(&term, &mut searcher).collect()
1945 })
1946 }
1947
1948 pub fn working_directory(&self) -> Option<PathBuf> {
1949 if self.is_ssh_terminal {
1950 // We can't yet reliably detect the working directory of a shell on the
1951 // SSH host. Until we can do that, it doesn't make sense to display
1952 // the working directory on the client and persist that.
1953 None
1954 } else {
1955 self.client_side_working_directory()
1956 }
1957 }
1958
1959 /// Returns the working directory of the process that's connected to the PTY.
1960 /// That means it returns the working directory of the local shell or program
1961 /// that's running inside the terminal.
1962 ///
1963 /// This does *not* return the working directory of the shell that runs on the
1964 /// remote host, in case Zed is connected to a remote host.
1965 fn client_side_working_directory(&self) -> Option<PathBuf> {
1966 match &self.terminal_type {
1967 TerminalType::Pty { info, .. } => {
1968 info.current.as_ref().map(|process| process.cwd.clone())
1969 }
1970 TerminalType::DisplayOnly => None,
1971 }
1972 }
1973
1974 pub fn title(&self, truncate: bool) -> String {
1975 const MAX_CHARS: usize = 25;
1976 match &self.task {
1977 Some(task_state) => {
1978 if truncate {
1979 truncate_and_trailoff(&task_state.spawned_task.label, MAX_CHARS)
1980 } else {
1981 task_state.spawned_task.full_label.clone()
1982 }
1983 }
1984 None => self
1985 .title_override
1986 .as_ref()
1987 .map(|title_override| title_override.to_string())
1988 .unwrap_or_else(|| match &self.terminal_type {
1989 TerminalType::Pty { info, .. } => info
1990 .current
1991 .as_ref()
1992 .map(|fpi| {
1993 let process_file = fpi
1994 .cwd
1995 .file_name()
1996 .map(|name| name.to_string_lossy().into_owned())
1997 .unwrap_or_default();
1998
1999 let argv = fpi.argv.as_slice();
2000 let process_name = format!(
2001 "{}{}",
2002 fpi.name,
2003 if !argv.is_empty() {
2004 format!(" {}", (argv[1..]).join(" "))
2005 } else {
2006 "".to_string()
2007 }
2008 );
2009 let (process_file, process_name) = if truncate {
2010 (
2011 truncate_and_trailoff(&process_file, MAX_CHARS),
2012 truncate_and_trailoff(&process_name, MAX_CHARS),
2013 )
2014 } else {
2015 (process_file, process_name)
2016 };
2017 format!("{process_file} — {process_name}")
2018 })
2019 .unwrap_or_else(|| "Terminal".to_string()),
2020 TerminalType::DisplayOnly => "Terminal".to_string(),
2021 }),
2022 }
2023 }
2024
2025 pub fn kill_active_task(&mut self) {
2026 if let Some(task) = self.task()
2027 && task.status == TaskStatus::Running
2028 {
2029 if let TerminalType::Pty { info, .. } = &mut self.terminal_type {
2030 info.kill_current_process();
2031 }
2032 }
2033 }
2034
2035 pub fn pid(&self) -> Option<sysinfo::Pid> {
2036 match &self.terminal_type {
2037 TerminalType::Pty { info, .. } => info.pid(),
2038 TerminalType::DisplayOnly => None,
2039 }
2040 }
2041
2042 pub fn pid_getter(&self) -> Option<&ProcessIdGetter> {
2043 match &self.terminal_type {
2044 TerminalType::Pty { info, .. } => Some(info.pid_getter()),
2045 TerminalType::DisplayOnly => None,
2046 }
2047 }
2048
2049 pub fn task(&self) -> Option<&TaskState> {
2050 self.task.as_ref()
2051 }
2052
2053 pub fn wait_for_completed_task(&self, cx: &App) -> Task<Option<ExitStatus>> {
2054 if let Some(task) = self.task() {
2055 if task.status == TaskStatus::Running {
2056 let completion_receiver = task.completion_rx.clone();
2057 return cx.spawn(async move |_| completion_receiver.recv().await.ok().flatten());
2058 } else if let Ok(status) = task.completion_rx.try_recv() {
2059 return Task::ready(status);
2060 }
2061 }
2062 Task::ready(None)
2063 }
2064
2065 fn register_task_finished(&mut self, error_code: Option<i32>, cx: &mut Context<Terminal>) {
2066 let e: Option<ExitStatus> = error_code.map(|code| {
2067 #[cfg(unix)]
2068 {
2069 std::os::unix::process::ExitStatusExt::from_raw(code)
2070 }
2071 #[cfg(windows)]
2072 {
2073 std::os::windows::process::ExitStatusExt::from_raw(code as u32)
2074 }
2075 });
2076
2077 if let Some(tx) = &self.completion_tx {
2078 tx.try_send(e).ok();
2079 }
2080 if let Some(e) = e {
2081 self.child_exited = Some(e);
2082 }
2083 let task = match &mut self.task {
2084 Some(task) => task,
2085 None => {
2086 if self.child_exited.is_none_or(|e| e.code() == Some(0)) {
2087 cx.emit(Event::CloseTerminal);
2088 }
2089 return;
2090 }
2091 };
2092 if task.status != TaskStatus::Running {
2093 return;
2094 }
2095 match error_code {
2096 Some(error_code) => {
2097 task.status.register_task_exit(error_code);
2098 }
2099 None => {
2100 task.status.register_terminal_exit();
2101 }
2102 };
2103
2104 let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
2105 let mut lines_to_show = Vec::new();
2106 if task.spawned_task.show_summary {
2107 lines_to_show.push(task_line.as_str());
2108 }
2109 if task.spawned_task.show_command {
2110 lines_to_show.push(command_line.as_str());
2111 }
2112
2113 if !lines_to_show.is_empty() {
2114 // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
2115 // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
2116 // when Zed task finishes and no more output is made.
2117 // After the task summary is output once, no more text is appended to the terminal.
2118 unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
2119 }
2120
2121 match task.spawned_task.hide {
2122 HideStrategy::Never => {}
2123 HideStrategy::Always => {
2124 cx.emit(Event::CloseTerminal);
2125 }
2126 HideStrategy::OnSuccess => {
2127 if finished_successfully {
2128 cx.emit(Event::CloseTerminal);
2129 }
2130 }
2131 }
2132 }
2133
2134 pub fn vi_mode_enabled(&self) -> bool {
2135 self.vi_mode_enabled
2136 }
2137
2138 pub fn clone_builder(
2139 &self,
2140 cx: &App,
2141 cwd: impl FnOnce() -> Option<PathBuf>,
2142 ) -> Result<TerminalBuilder> {
2143 let working_directory = self.working_directory().or_else(cwd);
2144 TerminalBuilder::new(
2145 working_directory,
2146 None,
2147 self.template.shell.clone(),
2148 self.template.env.clone(),
2149 self.template.cursor_shape,
2150 self.template.alternate_scroll,
2151 self.template.max_scroll_history_lines,
2152 self.is_ssh_terminal,
2153 self.template.window_id,
2154 None,
2155 cx,
2156 self.activation_script.clone(),
2157 )
2158 }
2159}
2160
2161// Helper function to convert a grid row to a string
2162pub fn row_to_string(row: &Row<Cell>) -> String {
2163 row[..Column(row.len())]
2164 .iter()
2165 .map(|cell| cell.c)
2166 .collect::<String>()
2167}
2168
2169const TASK_DELIMITER: &str = "⏵ ";
2170fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
2171 let escaped_full_label = task
2172 .spawned_task
2173 .full_label
2174 .replace("\r\n", "\r")
2175 .replace('\n', "\r");
2176 let (success, task_line) = match error_code {
2177 Some(0) => (
2178 true,
2179 format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"),
2180 ),
2181 Some(error_code) => (
2182 false,
2183 format!(
2184 "{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"
2185 ),
2186 ),
2187 None => (
2188 false,
2189 format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"),
2190 ),
2191 };
2192 let escaped_command_label = task
2193 .spawned_task
2194 .command_label
2195 .replace("\r\n", "\r")
2196 .replace('\n', "\r");
2197 let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
2198 (success, task_line, command_line)
2199}
2200
2201/// Appends a stringified task summary to the terminal, after its output.
2202///
2203/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
2204/// New text being added to the terminal here, uses "less public" APIs,
2205/// which are not maintaining the entire terminal state intact.
2206///
2207///
2208/// The library
2209///
2210/// * does not increment inner grid cursor's _lines_ on `input` calls
2211/// (but displaying the lines correctly and incrementing cursor's columns)
2212///
2213/// * ignores `\n` and \r` character input, requiring the `newline` call instead
2214///
2215/// * does not alter grid state after `newline` call
2216/// so its `bottommost_line` is always the same additions, and
2217/// the cursor's `point` is not updated to the new line and column values
2218///
2219/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
2220/// Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
2221///
2222/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
2223/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
2224/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
2225/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
2226unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
2227 term.newline();
2228 term.grid_mut().cursor.point.column = Column(0);
2229 for line in text_lines {
2230 for c in line.chars() {
2231 term.input(c);
2232 }
2233 term.newline();
2234 term.grid_mut().cursor.point.column = Column(0);
2235 }
2236}
2237
2238impl Drop for Terminal {
2239 fn drop(&mut self) {
2240 if let TerminalType::Pty { pty_tx, .. } = &self.terminal_type {
2241 pty_tx.0.send(Msg::Shutdown).ok();
2242 }
2243 }
2244}
2245
2246impl EventEmitter<Event> for Terminal {}
2247
2248fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
2249 let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
2250 selection.update(*range.end(), AlacDirection::Right);
2251 selection
2252}
2253
2254fn all_search_matches<'a, T>(
2255 term: &'a Term<T>,
2256 regex: &'a mut RegexSearch,
2257) -> impl Iterator<Item = Match> + 'a {
2258 let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
2259 let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
2260 RegexIter::new(start, end, AlacDirection::Right, term, regex)
2261}
2262
2263fn content_index_for_mouse(pos: Point<Pixels>, terminal_bounds: &TerminalBounds) -> usize {
2264 let col = (pos.x / terminal_bounds.cell_width()).round() as usize;
2265 let clamped_col = min(col, terminal_bounds.columns() - 1);
2266 let row = (pos.y / terminal_bounds.line_height()).round() as usize;
2267 let clamped_row = min(row, terminal_bounds.screen_lines() - 1);
2268 clamped_row * terminal_bounds.columns() + clamped_col
2269}
2270
2271/// Converts an 8 bit ANSI color to its GPUI equivalent.
2272/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
2273/// Other than that use case, should only be called with values in the `[0,255]` range
2274pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
2275 let colors = theme.colors();
2276
2277 match index {
2278 // 0-15 are the same as the named colors above
2279 0 => colors.terminal_ansi_black,
2280 1 => colors.terminal_ansi_red,
2281 2 => colors.terminal_ansi_green,
2282 3 => colors.terminal_ansi_yellow,
2283 4 => colors.terminal_ansi_blue,
2284 5 => colors.terminal_ansi_magenta,
2285 6 => colors.terminal_ansi_cyan,
2286 7 => colors.terminal_ansi_white,
2287 8 => colors.terminal_ansi_bright_black,
2288 9 => colors.terminal_ansi_bright_red,
2289 10 => colors.terminal_ansi_bright_green,
2290 11 => colors.terminal_ansi_bright_yellow,
2291 12 => colors.terminal_ansi_bright_blue,
2292 13 => colors.terminal_ansi_bright_magenta,
2293 14 => colors.terminal_ansi_bright_cyan,
2294 15 => colors.terminal_ansi_bright_white,
2295 // 16-231 are a 6x6x6 RGB color cube, mapped to 0-255 using steps defined by XTerm.
2296 // See: https://github.com/xterm-x11/xterm-snapshots/blob/master/256colres.pl
2297 16..=231 => {
2298 let (r, g, b) = rgb_for_index(index as u8);
2299 rgba_color(
2300 if r == 0 { 0 } else { r * 40 + 55 },
2301 if g == 0 { 0 } else { g * 40 + 55 },
2302 if b == 0 { 0 } else { b * 40 + 55 },
2303 )
2304 }
2305 // 232-255 are a 24-step grayscale ramp from (8, 8, 8) to (238, 238, 238).
2306 232..=255 => {
2307 let i = index as u8 - 232; // Align index to 0..24
2308 let value = i * 10 + 8;
2309 rgba_color(value, value, value)
2310 }
2311 // For compatibility with the alacritty::Colors interface
2312 // See: https://github.com/alacritty/alacritty/blob/master/alacritty_terminal/src/term/color.rs
2313 256 => colors.terminal_foreground,
2314 257 => colors.terminal_background,
2315 258 => theme.players().local().cursor,
2316 259 => colors.terminal_ansi_dim_black,
2317 260 => colors.terminal_ansi_dim_red,
2318 261 => colors.terminal_ansi_dim_green,
2319 262 => colors.terminal_ansi_dim_yellow,
2320 263 => colors.terminal_ansi_dim_blue,
2321 264 => colors.terminal_ansi_dim_magenta,
2322 265 => colors.terminal_ansi_dim_cyan,
2323 266 => colors.terminal_ansi_dim_white,
2324 267 => colors.terminal_bright_foreground,
2325 268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
2326
2327 _ => black(),
2328 }
2329}
2330
2331/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
2332///
2333/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
2334///
2335/// Wikipedia gives a formula for calculating the index for a given color:
2336///
2337/// ```text
2338/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
2339/// ```
2340///
2341/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
2342fn rgb_for_index(i: u8) -> (u8, u8, u8) {
2343 debug_assert!((16..=231).contains(&i));
2344 let i = i - 16;
2345 let r = (i - (i % 36)) / 36;
2346 let g = ((i % 36) - (i % 6)) / 6;
2347 let b = (i % 36) % 6;
2348 (r, g, b)
2349}
2350
2351pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
2352 Rgba {
2353 r: (r as f32 / 255.),
2354 g: (g as f32 / 255.),
2355 b: (b as f32 / 255.),
2356 a: 1.,
2357 }
2358 .into()
2359}
2360
2361#[cfg(test)]
2362mod tests {
2363 use std::time::Duration;
2364
2365 use super::*;
2366 use crate::{
2367 IndexedCell, TerminalBounds, TerminalBuilder, TerminalContent, content_index_for_mouse,
2368 rgb_for_index,
2369 };
2370 use alacritty_terminal::{
2371 index::{Column, Line, Point as AlacPoint},
2372 term::cell::Cell,
2373 };
2374 use collections::HashMap;
2375 use gpui::{Pixels, Point, TestAppContext, bounds, point, size, smol_timeout};
2376 use rand::{Rng, distr, rngs::ThreadRng};
2377 use task::ShellBuilder;
2378
2379 #[gpui::test]
2380 async fn test_basic_terminal(cx: &mut TestAppContext) {
2381 cx.executor().allow_parking();
2382
2383 let (completion_tx, completion_rx) = smol::channel::unbounded();
2384 let (program, args) =
2385 ShellBuilder::new(&Shell::System).build(Some("echo".to_owned()), &["hello".to_owned()]);
2386 let terminal = cx.new(|cx| {
2387 TerminalBuilder::new(
2388 None,
2389 None,
2390 task::Shell::WithArguments {
2391 program,
2392 args,
2393 title_override: None,
2394 },
2395 HashMap::default(),
2396 CursorShape::default(),
2397 AlternateScroll::On,
2398 None,
2399 false,
2400 0,
2401 Some(completion_tx),
2402 cx,
2403 vec![],
2404 )
2405 .unwrap()
2406 .subscribe(cx)
2407 });
2408 assert_eq!(
2409 completion_rx.recv().await.unwrap(),
2410 Some(ExitStatus::default())
2411 );
2412 assert_eq!(
2413 terminal.update(cx, |term, _| term.get_content()).trim(),
2414 "hello"
2415 );
2416
2417 // Inject additional output directly into the emulator (display-only path)
2418 terminal.update(cx, |term, cx| {
2419 term.write_output(b"\nfrom_injection", cx);
2420 });
2421
2422 let content_after = terminal.update(cx, |term, _| term.get_content());
2423 assert!(
2424 content_after.contains("from_injection"),
2425 "expected injected output to appear, got: {content_after}"
2426 );
2427 }
2428
2429 // TODO should be tested on Linux too, but does not work there well
2430 #[cfg(target_os = "macos")]
2431 #[gpui::test(iterations = 10)]
2432 async fn test_terminal_eof(cx: &mut TestAppContext) {
2433 cx.executor().allow_parking();
2434
2435 let (completion_tx, completion_rx) = smol::channel::unbounded();
2436 // Build an empty command, which will result in a tty shell spawned.
2437 let terminal = cx.new(|cx| {
2438 TerminalBuilder::new(
2439 None,
2440 None,
2441 task::Shell::System,
2442 HashMap::default(),
2443 CursorShape::default(),
2444 AlternateScroll::On,
2445 None,
2446 false,
2447 0,
2448 Some(completion_tx),
2449 cx,
2450 Vec::new(),
2451 )
2452 .unwrap()
2453 .subscribe(cx)
2454 });
2455
2456 let (event_tx, event_rx) = smol::channel::unbounded::<Event>();
2457 cx.update(|cx| {
2458 cx.subscribe(&terminal, move |_, e, _| {
2459 event_tx.send_blocking(e.clone()).unwrap();
2460 })
2461 })
2462 .detach();
2463 cx.background_spawn(async move {
2464 assert_eq!(
2465 completion_rx.recv().await.unwrap(),
2466 Some(ExitStatus::default()),
2467 "EOF should result in the tty shell exiting successfully",
2468 );
2469 })
2470 .detach();
2471
2472 let first_event = Event::Wakeup;
2473 let wakeup = event_rx.recv().await.expect("No wakeup event received");
2474 assert_eq!(wakeup, first_event, "Expected wakeup, got {wakeup:?}");
2475
2476 terminal.update(cx, |terminal, _| {
2477 let success = terminal.try_keystroke(&Keystroke::parse("ctrl-c").unwrap(), false);
2478 assert!(success, "Should have registered ctrl-c sequence");
2479 });
2480 terminal.update(cx, |terminal, _| {
2481 let success = terminal.try_keystroke(&Keystroke::parse("ctrl-d").unwrap(), false);
2482 assert!(success, "Should have registered ctrl-d sequence");
2483 });
2484
2485 let mut all_events = vec![first_event];
2486 while let Ok(Ok(new_event)) = smol_timeout(Duration::from_secs(1), event_rx.recv()).await {
2487 all_events.push(new_event.clone());
2488 if new_event == Event::CloseTerminal {
2489 break;
2490 }
2491 }
2492 assert!(
2493 all_events.contains(&Event::CloseTerminal),
2494 "EOF command sequence should have triggered a TTY terminal exit, but got events: {all_events:?}",
2495 );
2496 }
2497
2498 #[gpui::test(iterations = 10)]
2499 async fn test_terminal_no_exit_on_spawn_failure(cx: &mut TestAppContext) {
2500 cx.executor().allow_parking();
2501
2502 let (completion_tx, completion_rx) = smol::channel::unbounded();
2503 let (program, args) = ShellBuilder::new(&Shell::System)
2504 .build(Some("asdasdasdasd".to_owned()), &["@@@@@".to_owned()]);
2505 let terminal = cx.new(|cx| {
2506 TerminalBuilder::new(
2507 None,
2508 None,
2509 task::Shell::WithArguments {
2510 program,
2511 args,
2512 title_override: None,
2513 },
2514 HashMap::default(),
2515 CursorShape::default(),
2516 AlternateScroll::On,
2517 None,
2518 false,
2519 0,
2520 Some(completion_tx),
2521 cx,
2522 Vec::new(),
2523 )
2524 .unwrap()
2525 .subscribe(cx)
2526 });
2527
2528 let (event_tx, event_rx) = smol::channel::unbounded::<Event>();
2529 cx.update(|cx| {
2530 cx.subscribe(&terminal, move |_, e, _| {
2531 event_tx.send_blocking(e.clone()).unwrap();
2532 })
2533 })
2534 .detach();
2535 cx.background_spawn(async move {
2536 #[cfg(target_os = "windows")]
2537 {
2538 let exit_status = completion_rx.recv().await.ok().flatten();
2539 if let Some(exit_status) = exit_status {
2540 assert!(
2541 !exit_status.success(),
2542 "Wrong shell command should result in a failure"
2543 );
2544 assert_eq!(exit_status.code(), Some(1));
2545 }
2546 }
2547 #[cfg(not(target_os = "windows"))]
2548 {
2549 let exit_status = completion_rx.recv().await.unwrap().unwrap();
2550 assert!(
2551 !exit_status.success(),
2552 "Wrong shell command should result in a failure"
2553 );
2554 assert_eq!(exit_status.code(), None);
2555 }
2556 })
2557 .detach();
2558
2559 let mut all_events = Vec::new();
2560 while let Ok(Ok(new_event)) =
2561 smol_timeout(Duration::from_millis(500), event_rx.recv()).await
2562 {
2563 all_events.push(new_event.clone());
2564 }
2565
2566 assert!(
2567 !all_events
2568 .iter()
2569 .any(|event| event == &Event::CloseTerminal),
2570 "Wrong shell command should update the title but not should not close the terminal to show the error message, but got events: {all_events:?}",
2571 );
2572 }
2573
2574 #[test]
2575 fn test_rgb_for_index() {
2576 // Test every possible value in the color cube.
2577 for i in 16..=231 {
2578 let (r, g, b) = rgb_for_index(i);
2579 assert_eq!(i, 16 + 36 * r + 6 * g + b);
2580 }
2581 }
2582
2583 #[test]
2584 fn test_mouse_to_cell_test() {
2585 let mut rng = rand::rng();
2586 const ITERATIONS: usize = 10;
2587 const PRECISION: usize = 1000;
2588
2589 for _ in 0..ITERATIONS {
2590 let viewport_cells = rng.random_range(15..20);
2591 let cell_size =
2592 rng.random_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2593
2594 let size = crate::TerminalBounds {
2595 cell_width: Pixels::from(cell_size),
2596 line_height: Pixels::from(cell_size),
2597 bounds: bounds(
2598 Point::default(),
2599 size(
2600 Pixels::from(cell_size * (viewport_cells as f32)),
2601 Pixels::from(cell_size * (viewport_cells as f32)),
2602 ),
2603 ),
2604 };
2605
2606 let cells = get_cells(size, &mut rng);
2607 let content = convert_cells_to_content(size, &cells);
2608
2609 for row in 0..(viewport_cells - 1) {
2610 let row = row as usize;
2611 for col in 0..(viewport_cells - 1) {
2612 let col = col as usize;
2613
2614 let row_offset = rng.random_range(0..PRECISION) as f32 / PRECISION as f32;
2615 let col_offset = rng.random_range(0..PRECISION) as f32 / PRECISION as f32;
2616
2617 let mouse_pos = point(
2618 Pixels::from(col as f32 * cell_size + col_offset),
2619 Pixels::from(row as f32 * cell_size + row_offset),
2620 );
2621
2622 let content_index =
2623 content_index_for_mouse(mouse_pos, &content.terminal_bounds);
2624 let mouse_cell = content.cells[content_index].c;
2625 let real_cell = cells[row][col];
2626
2627 assert_eq!(mouse_cell, real_cell);
2628 }
2629 }
2630 }
2631 }
2632
2633 #[test]
2634 fn test_mouse_to_cell_clamp() {
2635 let mut rng = rand::rng();
2636
2637 let size = crate::TerminalBounds {
2638 cell_width: Pixels::from(10.),
2639 line_height: Pixels::from(10.),
2640 bounds: bounds(
2641 Point::default(),
2642 size(Pixels::from(100.), Pixels::from(100.)),
2643 ),
2644 };
2645
2646 let cells = get_cells(size, &mut rng);
2647 let content = convert_cells_to_content(size, &cells);
2648
2649 assert_eq!(
2650 content.cells[content_index_for_mouse(
2651 point(Pixels::from(-10.), Pixels::from(-10.)),
2652 &content.terminal_bounds,
2653 )]
2654 .c,
2655 cells[0][0]
2656 );
2657 assert_eq!(
2658 content.cells[content_index_for_mouse(
2659 point(Pixels::from(1000.), Pixels::from(1000.)),
2660 &content.terminal_bounds,
2661 )]
2662 .c,
2663 cells[9][9]
2664 );
2665 }
2666
2667 fn get_cells(size: TerminalBounds, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2668 let mut cells = Vec::new();
2669
2670 for _ in 0..((size.height() / size.line_height()) as usize) {
2671 let mut row_vec = Vec::new();
2672 for _ in 0..((size.width() / size.cell_width()) as usize) {
2673 let cell_char = rng.sample(distr::Alphanumeric) as char;
2674 row_vec.push(cell_char)
2675 }
2676 cells.push(row_vec)
2677 }
2678
2679 cells
2680 }
2681
2682 fn convert_cells_to_content(
2683 terminal_bounds: TerminalBounds,
2684 cells: &[Vec<char>],
2685 ) -> TerminalContent {
2686 let mut ic = Vec::new();
2687
2688 for (index, row) in cells.iter().enumerate() {
2689 for (cell_index, cell_char) in row.iter().enumerate() {
2690 ic.push(IndexedCell {
2691 point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2692 cell: Cell {
2693 c: *cell_char,
2694 ..Default::default()
2695 },
2696 });
2697 }
2698 }
2699
2700 TerminalContent {
2701 cells: ic,
2702 terminal_bounds,
2703 ..Default::default()
2704 }
2705 }
2706
2707 #[gpui::test]
2708 async fn test_write_output_converts_lf_to_crlf(cx: &mut TestAppContext) {
2709 let terminal = cx.new(|cx| {
2710 TerminalBuilder::new_display_only(CursorShape::default(), AlternateScroll::On, None, 0)
2711 .unwrap()
2712 .subscribe(cx)
2713 });
2714
2715 // Test simple LF conversion
2716 terminal.update(cx, |terminal, cx| {
2717 terminal.write_output(b"line1\nline2\n", cx);
2718 });
2719
2720 // Get the content by directly accessing the term
2721 let content = terminal.update(cx, |terminal, _cx| {
2722 let term = terminal.term.lock_unfair();
2723 Terminal::make_content(&term, &terminal.last_content)
2724 });
2725
2726 // If LF is properly converted to CRLF, each line should start at column 0
2727 // The diagonal staircase bug would cause increasing column positions
2728
2729 // Get the cells and check that lines start at column 0
2730 let cells = &content.cells;
2731 let mut line1_col0 = false;
2732 let mut line2_col0 = false;
2733
2734 for cell in cells {
2735 if cell.c == 'l' && cell.point.column.0 == 0 {
2736 if cell.point.line.0 == 0 && !line1_col0 {
2737 line1_col0 = true;
2738 } else if cell.point.line.0 == 1 && !line2_col0 {
2739 line2_col0 = true;
2740 }
2741 }
2742 }
2743
2744 assert!(line1_col0, "First line should start at column 0");
2745 assert!(line2_col0, "Second line should start at column 0");
2746 }
2747
2748 #[gpui::test]
2749 async fn test_write_output_preserves_existing_crlf(cx: &mut TestAppContext) {
2750 let terminal = cx.new(|cx| {
2751 TerminalBuilder::new_display_only(CursorShape::default(), AlternateScroll::On, None, 0)
2752 .unwrap()
2753 .subscribe(cx)
2754 });
2755
2756 // Test that existing CRLF doesn't get doubled
2757 terminal.update(cx, |terminal, cx| {
2758 terminal.write_output(b"line1\r\nline2\r\n", cx);
2759 });
2760
2761 // Get the content by directly accessing the term
2762 let content = terminal.update(cx, |terminal, _cx| {
2763 let term = terminal.term.lock_unfair();
2764 Terminal::make_content(&term, &terminal.last_content)
2765 });
2766
2767 let cells = &content.cells;
2768
2769 // Check that both lines start at column 0
2770 let mut found_lines_at_column_0 = 0;
2771 for cell in cells {
2772 if cell.c == 'l' && cell.point.column.0 == 0 {
2773 found_lines_at_column_0 += 1;
2774 }
2775 }
2776
2777 assert!(
2778 found_lines_at_column_0 >= 2,
2779 "Both lines should start at column 0"
2780 );
2781 }
2782
2783 #[gpui::test]
2784 async fn test_write_output_preserves_bare_cr(cx: &mut TestAppContext) {
2785 let terminal = cx.new(|cx| {
2786 TerminalBuilder::new_display_only(CursorShape::default(), AlternateScroll::On, None, 0)
2787 .unwrap()
2788 .subscribe(cx)
2789 });
2790
2791 // Test that bare CR (without LF) is preserved
2792 terminal.update(cx, |terminal, cx| {
2793 terminal.write_output(b"hello\rworld", cx);
2794 });
2795
2796 // Get the content by directly accessing the term
2797 let content = terminal.update(cx, |terminal, _cx| {
2798 let term = terminal.term.lock_unfair();
2799 Terminal::make_content(&term, &terminal.last_content)
2800 });
2801
2802 let cells = &content.cells;
2803
2804 // Check that we have "world" at the beginning of the line
2805 let mut text = String::new();
2806 for cell in cells.iter().take(5) {
2807 if cell.point.line.0 == 0 {
2808 text.push(cell.c);
2809 }
2810 }
2811
2812 assert!(
2813 text.starts_with("world"),
2814 "Bare CR should allow overwriting: got '{}'",
2815 text
2816 );
2817 }
2818}