terminal_view.rs

   1mod persistence;
   2pub mod terminal_element;
   3pub mod terminal_panel;
   4pub mod terminal_scrollbar;
   5pub mod terminal_tab_tooltip;
   6
   7use editor::{Editor, EditorSettings, actions::SelectAll, scroll::ScrollbarAutoHide};
   8use gpui::{
   9    AnyElement, App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, KeyContext,
  10    KeyDownEvent, Keystroke, MouseButton, MouseDownEvent, Pixels, Render, ScrollWheelEvent,
  11    Stateful, Styled, Subscription, Task, WeakEntity, anchored, deferred, div, impl_actions,
  12};
  13use itertools::Itertools;
  14use persistence::TERMINAL_DB;
  15use project::{Entry, Metadata, Project, search::SearchQuery, terminals::TerminalKind};
  16use schemars::JsonSchema;
  17use terminal::{
  18    Clear, Copy, Event, MaybeNavigationTarget, Paste, ScrollLineDown, ScrollLineUp, ScrollPageDown,
  19    ScrollPageUp, ScrollToBottom, ScrollToTop, ShowCharacterPalette, TaskState, TaskStatus,
  20    Terminal, TerminalBounds, ToggleViMode,
  21    alacritty_terminal::{
  22        index::Point,
  23        term::{TermMode, search::RegexSearch},
  24    },
  25    terminal_settings::{self, CursorShape, TerminalBlink, TerminalSettings, WorkingDirectory},
  26};
  27use terminal_element::{TerminalElement, is_blank};
  28use terminal_panel::TerminalPanel;
  29use terminal_scrollbar::TerminalScrollHandle;
  30use terminal_tab_tooltip::TerminalTooltip;
  31use ui::{
  32    ContextMenu, Icon, IconName, Label, Scrollbar, ScrollbarState, Tooltip, h_flex, prelude::*,
  33};
  34use util::{ResultExt, debug_panic, paths::PathWithPosition};
  35use workspace::{
  36    CloseActiveItem, NewCenterTerminal, NewTerminal, OpenOptions, OpenVisible, ToolbarItemLocation,
  37    Workspace, WorkspaceId,
  38    item::{
  39        BreadcrumbText, Item, ItemEvent, SerializableItem, TabContentParams, TabTooltipContent,
  40    },
  41    register_serializable_item,
  42    searchable::{Direction, SearchEvent, SearchOptions, SearchableItem, SearchableItemHandle},
  43};
  44
  45use anyhow::Context as _;
  46use serde::Deserialize;
  47use settings::{Settings, SettingsStore};
  48use smol::Timer;
  49use zed_actions::assistant::InlineAssist;
  50
  51use std::{
  52    cmp,
  53    ops::RangeInclusive,
  54    path::{Path, PathBuf},
  55    rc::Rc,
  56    sync::Arc,
  57    time::Duration,
  58};
  59
  60const REGEX_SPECIAL_CHARS: &[char] = &[
  61    '\\', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '^', '$',
  62];
  63
  64const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  65
  66const GIT_DIFF_PATH_PREFIXES: &[&str] = &["a", "b"];
  67
  68/// Event to transmit the scroll from the element to the view
  69#[derive(Clone, Debug, PartialEq)]
  70pub struct ScrollTerminal(pub i32);
  71
  72#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq)]
  73pub struct SendText(String);
  74
  75#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq)]
  76pub struct SendKeystroke(String);
  77
  78impl_actions!(terminal, [SendText, SendKeystroke]);
  79
  80pub fn init(cx: &mut App) {
  81    terminal_panel::init(cx);
  82    terminal::init(cx);
  83
  84    register_serializable_item::<TerminalView>(cx);
  85
  86    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
  87        workspace.register_action(TerminalView::deploy);
  88    })
  89    .detach();
  90}
  91
  92pub struct BlockProperties {
  93    pub height: u8,
  94    pub render: Box<dyn Send + Fn(&mut BlockContext) -> AnyElement>,
  95}
  96
  97pub struct BlockContext<'a, 'b> {
  98    pub window: &'a mut Window,
  99    pub context: &'b mut App,
 100    pub dimensions: TerminalBounds,
 101}
 102
 103///A terminal view, maintains the PTY's file handles and communicates with the terminal
 104pub struct TerminalView {
 105    terminal: Entity<Terminal>,
 106    workspace: WeakEntity<Workspace>,
 107    project: WeakEntity<Project>,
 108    focus_handle: FocusHandle,
 109    //Currently using iTerm bell, show bell emoji in tab until input is received
 110    has_bell: bool,
 111    context_menu: Option<(Entity<ContextMenu>, gpui::Point<Pixels>, Subscription)>,
 112    cursor_shape: CursorShape,
 113    blink_state: bool,
 114    blinking_terminal_enabled: bool,
 115    blinking_paused: bool,
 116    blink_epoch: usize,
 117    hover_target_tooltip: Option<String>,
 118    workspace_id: Option<WorkspaceId>,
 119    show_breadcrumbs: bool,
 120    block_below_cursor: Option<Rc<BlockProperties>>,
 121    scroll_top: Pixels,
 122    scrollbar_state: ScrollbarState,
 123    scroll_handle: TerminalScrollHandle,
 124    show_scrollbar: bool,
 125    hide_scrollbar_task: Option<Task<()>>,
 126    _subscriptions: Vec<Subscription>,
 127    _terminal_subscriptions: Vec<Subscription>,
 128}
 129
 130impl EventEmitter<Event> for TerminalView {}
 131impl EventEmitter<ItemEvent> for TerminalView {}
 132impl EventEmitter<SearchEvent> for TerminalView {}
 133
 134impl Focusable for TerminalView {
 135    fn focus_handle(&self, _cx: &App) -> FocusHandle {
 136        self.focus_handle.clone()
 137    }
 138}
 139
 140impl TerminalView {
 141    ///Create a new Terminal in the current working directory or the user's home directory
 142    pub fn deploy(
 143        workspace: &mut Workspace,
 144        _: &NewCenterTerminal,
 145        window: &mut Window,
 146        cx: &mut Context<Workspace>,
 147    ) {
 148        let working_directory = default_working_directory(workspace, cx);
 149        TerminalPanel::add_center_terminal(
 150            workspace,
 151            TerminalKind::Shell(working_directory),
 152            window,
 153            cx,
 154        )
 155        .detach_and_log_err(cx);
 156    }
 157
 158    pub fn new(
 159        terminal: Entity<Terminal>,
 160        workspace: WeakEntity<Workspace>,
 161        workspace_id: Option<WorkspaceId>,
 162        project: WeakEntity<Project>,
 163        window: &mut Window,
 164        cx: &mut Context<Self>,
 165    ) -> Self {
 166        let workspace_handle = workspace.clone();
 167        let terminal_subscriptions =
 168            subscribe_for_terminal_events(&terminal, workspace, window, cx);
 169
 170        let focus_handle = cx.focus_handle();
 171        let focus_in = cx.on_focus_in(&focus_handle, window, |terminal_view, window, cx| {
 172            terminal_view.focus_in(window, cx);
 173        });
 174        let focus_out = cx.on_focus_out(
 175            &focus_handle,
 176            window,
 177            |terminal_view, _event, window, cx| {
 178                terminal_view.focus_out(window, cx);
 179            },
 180        );
 181        let cursor_shape = TerminalSettings::get_global(cx)
 182            .cursor_shape
 183            .unwrap_or_default();
 184
 185        let scroll_handle = TerminalScrollHandle::new(terminal.read(cx));
 186
 187        Self {
 188            terminal,
 189            workspace: workspace_handle,
 190            project,
 191            has_bell: false,
 192            focus_handle,
 193            context_menu: None,
 194            cursor_shape,
 195            blink_state: true,
 196            blinking_terminal_enabled: false,
 197            blinking_paused: false,
 198            blink_epoch: 0,
 199            hover_target_tooltip: None,
 200            workspace_id,
 201            show_breadcrumbs: TerminalSettings::get_global(cx).toolbar.breadcrumbs,
 202            block_below_cursor: None,
 203            scroll_top: Pixels::ZERO,
 204            scrollbar_state: ScrollbarState::new(scroll_handle.clone()),
 205            scroll_handle,
 206            show_scrollbar: !Self::should_autohide_scrollbar(cx),
 207            hide_scrollbar_task: None,
 208            _subscriptions: vec![
 209                focus_in,
 210                focus_out,
 211                cx.observe_global::<SettingsStore>(Self::settings_changed),
 212            ],
 213            _terminal_subscriptions: terminal_subscriptions,
 214        }
 215    }
 216
 217    pub fn entity(&self) -> &Entity<Terminal> {
 218        &self.terminal
 219    }
 220
 221    pub fn has_bell(&self) -> bool {
 222        self.has_bell
 223    }
 224
 225    pub fn clear_bell(&mut self, cx: &mut Context<TerminalView>) {
 226        self.has_bell = false;
 227        cx.emit(Event::Wakeup);
 228    }
 229
 230    pub fn deploy_context_menu(
 231        &mut self,
 232        position: gpui::Point<Pixels>,
 233        window: &mut Window,
 234        cx: &mut Context<Self>,
 235    ) {
 236        let assistant_enabled = self
 237            .workspace
 238            .upgrade()
 239            .and_then(|workspace| workspace.read(cx).panel::<TerminalPanel>(cx))
 240            .map_or(false, |terminal_panel| {
 241                terminal_panel.read(cx).assistant_enabled()
 242            });
 243        let context_menu = ContextMenu::build(window, cx, |menu, _, _| {
 244            menu.context(self.focus_handle.clone())
 245                .action("New Terminal", Box::new(NewTerminal))
 246                .separator()
 247                .action("Copy", Box::new(Copy))
 248                .action("Paste", Box::new(Paste))
 249                .action("Select All", Box::new(SelectAll))
 250                .action("Clear", Box::new(Clear))
 251                .when(assistant_enabled, |menu| {
 252                    menu.separator()
 253                        .action("Inline Assist", Box::new(InlineAssist::default()))
 254                })
 255                .separator()
 256                .action(
 257                    "Close Terminal Tab",
 258                    Box::new(CloseActiveItem {
 259                        save_intent: None,
 260                        close_pinned: true,
 261                    }),
 262                )
 263        });
 264
 265        window.focus(&context_menu.focus_handle(cx));
 266        let subscription = cx.subscribe_in(
 267            &context_menu,
 268            window,
 269            |this, _, _: &DismissEvent, window, cx| {
 270                if this.context_menu.as_ref().is_some_and(|context_menu| {
 271                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
 272                }) {
 273                    cx.focus_self(window);
 274                }
 275                this.context_menu.take();
 276                cx.notify();
 277            },
 278        );
 279
 280        self.context_menu = Some((context_menu, position, subscription));
 281    }
 282
 283    fn settings_changed(&mut self, cx: &mut Context<Self>) {
 284        let settings = TerminalSettings::get_global(cx);
 285        self.show_breadcrumbs = settings.toolbar.breadcrumbs;
 286
 287        let new_cursor_shape = settings.cursor_shape.unwrap_or_default();
 288        let old_cursor_shape = self.cursor_shape;
 289        if old_cursor_shape != new_cursor_shape {
 290            self.cursor_shape = new_cursor_shape;
 291            self.terminal.update(cx, |term, _| {
 292                term.set_cursor_shape(self.cursor_shape);
 293            });
 294        }
 295
 296        cx.notify();
 297    }
 298
 299    fn show_character_palette(
 300        &mut self,
 301        _: &ShowCharacterPalette,
 302        window: &mut Window,
 303        cx: &mut Context<Self>,
 304    ) {
 305        if self
 306            .terminal
 307            .read(cx)
 308            .last_content
 309            .mode
 310            .contains(TermMode::ALT_SCREEN)
 311        {
 312            self.terminal.update(cx, |term, cx| {
 313                term.try_keystroke(
 314                    &Keystroke::parse("ctrl-cmd-space").unwrap(),
 315                    TerminalSettings::get_global(cx).option_as_meta,
 316                )
 317            });
 318        } else {
 319            window.show_character_palette();
 320        }
 321    }
 322
 323    fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
 324        self.terminal.update(cx, |term, _| term.select_all());
 325        cx.notify();
 326    }
 327
 328    fn clear(&mut self, _: &Clear, _: &mut Window, cx: &mut Context<Self>) {
 329        self.scroll_top = px(0.);
 330        self.terminal.update(cx, |term, _| term.clear());
 331        cx.notify();
 332    }
 333
 334    fn max_scroll_top(&self, cx: &App) -> Pixels {
 335        let terminal = self.terminal.read(cx);
 336
 337        let Some(block) = self.block_below_cursor.as_ref() else {
 338            return Pixels::ZERO;
 339        };
 340
 341        let line_height = terminal.last_content().terminal_bounds.line_height;
 342        let mut terminal_lines = terminal.total_lines();
 343        let viewport_lines = terminal.viewport_lines();
 344        if terminal.total_lines() == terminal.viewport_lines() {
 345            let mut last_line = None;
 346            for cell in terminal.last_content.cells.iter().rev() {
 347                if !is_blank(cell) {
 348                    break;
 349                }
 350
 351                let last_line = last_line.get_or_insert(cell.point.line);
 352                if *last_line != cell.point.line {
 353                    terminal_lines -= 1;
 354                }
 355                *last_line = cell.point.line;
 356            }
 357        }
 358
 359        let max_scroll_top_in_lines =
 360            (block.height as usize).saturating_sub(viewport_lines.saturating_sub(terminal_lines));
 361
 362        max_scroll_top_in_lines as f32 * line_height
 363    }
 364
 365    fn scroll_wheel(&mut self, event: &ScrollWheelEvent, cx: &mut Context<Self>) {
 366        let terminal_content = self.terminal.read(cx).last_content();
 367
 368        if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
 369            let line_height = terminal_content.terminal_bounds.line_height;
 370            let y_delta = event.delta.pixel_delta(line_height).y;
 371            if y_delta < Pixels::ZERO || self.scroll_top > Pixels::ZERO {
 372                self.scroll_top = cmp::max(
 373                    Pixels::ZERO,
 374                    cmp::min(self.scroll_top - y_delta, self.max_scroll_top(cx)),
 375                );
 376                cx.notify();
 377                return;
 378            }
 379        }
 380
 381        self.terminal.update(cx, |term, _| term.scroll_wheel(event));
 382    }
 383
 384    fn scroll_line_up(&mut self, _: &ScrollLineUp, _: &mut Window, cx: &mut Context<Self>) {
 385        let terminal_content = self.terminal.read(cx).last_content();
 386        if self.block_below_cursor.is_some()
 387            && terminal_content.display_offset == 0
 388            && self.scroll_top > Pixels::ZERO
 389        {
 390            let line_height = terminal_content.terminal_bounds.line_height;
 391            self.scroll_top = cmp::max(self.scroll_top - line_height, Pixels::ZERO);
 392            return;
 393        }
 394
 395        self.terminal.update(cx, |term, _| term.scroll_line_up());
 396        cx.notify();
 397    }
 398
 399    fn scroll_line_down(&mut self, _: &ScrollLineDown, _: &mut Window, cx: &mut Context<Self>) {
 400        let terminal_content = self.terminal.read(cx).last_content();
 401        if self.block_below_cursor.is_some() && terminal_content.display_offset == 0 {
 402            let max_scroll_top = self.max_scroll_top(cx);
 403            if self.scroll_top < max_scroll_top {
 404                let line_height = terminal_content.terminal_bounds.line_height;
 405                self.scroll_top = cmp::min(self.scroll_top + line_height, max_scroll_top);
 406            }
 407            return;
 408        }
 409
 410        self.terminal.update(cx, |term, _| term.scroll_line_down());
 411        cx.notify();
 412    }
 413
 414    fn scroll_page_up(&mut self, _: &ScrollPageUp, _: &mut Window, cx: &mut Context<Self>) {
 415        if self.scroll_top == Pixels::ZERO {
 416            self.terminal.update(cx, |term, _| term.scroll_page_up());
 417        } else {
 418            let line_height = self
 419                .terminal
 420                .read(cx)
 421                .last_content
 422                .terminal_bounds
 423                .line_height();
 424            let visible_block_lines = (self.scroll_top / line_height) as usize;
 425            let viewport_lines = self.terminal.read(cx).viewport_lines();
 426            let visible_content_lines = viewport_lines - visible_block_lines;
 427
 428            if visible_block_lines >= viewport_lines {
 429                self.scroll_top = ((visible_block_lines - viewport_lines) as f32) * line_height;
 430            } else {
 431                self.scroll_top = px(0.);
 432                self.terminal
 433                    .update(cx, |term, _| term.scroll_up_by(visible_content_lines));
 434            }
 435        }
 436        cx.notify();
 437    }
 438
 439    fn scroll_page_down(&mut self, _: &ScrollPageDown, _: &mut Window, cx: &mut Context<Self>) {
 440        self.terminal.update(cx, |term, _| term.scroll_page_down());
 441        let terminal = self.terminal.read(cx);
 442        if terminal.last_content().display_offset < terminal.viewport_lines() {
 443            self.scroll_top = self.max_scroll_top(cx);
 444        }
 445        cx.notify();
 446    }
 447
 448    fn scroll_to_top(&mut self, _: &ScrollToTop, _: &mut Window, cx: &mut Context<Self>) {
 449        self.terminal.update(cx, |term, _| term.scroll_to_top());
 450        cx.notify();
 451    }
 452
 453    fn scroll_to_bottom(&mut self, _: &ScrollToBottom, _: &mut Window, cx: &mut Context<Self>) {
 454        self.terminal.update(cx, |term, _| term.scroll_to_bottom());
 455        if self.block_below_cursor.is_some() {
 456            self.scroll_top = self.max_scroll_top(cx);
 457        }
 458        cx.notify();
 459    }
 460
 461    fn toggle_vi_mode(&mut self, _: &ToggleViMode, _: &mut Window, cx: &mut Context<Self>) {
 462        self.terminal.update(cx, |term, _| term.toggle_vi_mode());
 463        cx.notify();
 464    }
 465
 466    pub fn should_show_cursor(&self, focused: bool, cx: &mut Context<Self>) -> bool {
 467        //Don't blink the cursor when not focused, blinking is disabled, or paused
 468        if !focused
 469            || self.blinking_paused
 470            || self
 471                .terminal
 472                .read(cx)
 473                .last_content
 474                .mode
 475                .contains(TermMode::ALT_SCREEN)
 476        {
 477            return true;
 478        }
 479
 480        match TerminalSettings::get_global(cx).blinking {
 481            //If the user requested to never blink, don't blink it.
 482            TerminalBlink::Off => true,
 483            //If the terminal is controlling it, check terminal mode
 484            TerminalBlink::TerminalControlled => {
 485                !self.blinking_terminal_enabled || self.blink_state
 486            }
 487            TerminalBlink::On => self.blink_state,
 488        }
 489    }
 490
 491    fn blink_cursors(&mut self, epoch: usize, window: &mut Window, cx: &mut Context<Self>) {
 492        if epoch == self.blink_epoch && !self.blinking_paused {
 493            self.blink_state = !self.blink_state;
 494            cx.notify();
 495
 496            let epoch = self.next_blink_epoch();
 497            cx.spawn_in(window, async move |this, cx| {
 498                Timer::after(CURSOR_BLINK_INTERVAL).await;
 499                this.update_in(cx, |this, window, cx| this.blink_cursors(epoch, window, cx))
 500                    .ok();
 501            })
 502            .detach();
 503        }
 504    }
 505
 506    pub fn pause_cursor_blinking(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 507        self.blink_state = true;
 508        cx.notify();
 509
 510        let epoch = self.next_blink_epoch();
 511        cx.spawn_in(window, async move |this, cx| {
 512            Timer::after(CURSOR_BLINK_INTERVAL).await;
 513            this.update_in(cx, |this, window, cx| {
 514                this.resume_cursor_blinking(epoch, window, cx)
 515            })
 516            .ok();
 517        })
 518        .detach();
 519    }
 520
 521    pub fn terminal(&self) -> &Entity<Terminal> {
 522        &self.terminal
 523    }
 524
 525    pub fn set_block_below_cursor(
 526        &mut self,
 527        block: BlockProperties,
 528        window: &mut Window,
 529        cx: &mut Context<Self>,
 530    ) {
 531        self.block_below_cursor = Some(Rc::new(block));
 532        self.scroll_to_bottom(&ScrollToBottom, window, cx);
 533        cx.notify();
 534    }
 535
 536    pub fn clear_block_below_cursor(&mut self, cx: &mut Context<Self>) {
 537        self.block_below_cursor = None;
 538        self.scroll_top = Pixels::ZERO;
 539        cx.notify();
 540    }
 541
 542    fn next_blink_epoch(&mut self) -> usize {
 543        self.blink_epoch += 1;
 544        self.blink_epoch
 545    }
 546
 547    fn resume_cursor_blinking(
 548        &mut self,
 549        epoch: usize,
 550        window: &mut Window,
 551        cx: &mut Context<Self>,
 552    ) {
 553        if epoch == self.blink_epoch {
 554            self.blinking_paused = false;
 555            self.blink_cursors(epoch, window, cx);
 556        }
 557    }
 558
 559    ///Attempt to paste the clipboard into the terminal
 560    fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 561        self.terminal.update(cx, |term, _| term.copy());
 562        cx.notify();
 563    }
 564
 565    ///Attempt to paste the clipboard into the terminal
 566    fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
 567        if let Some(clipboard_string) = cx.read_from_clipboard().and_then(|item| item.text()) {
 568            self.terminal
 569                .update(cx, |terminal, _cx| terminal.paste(&clipboard_string));
 570        }
 571    }
 572
 573    fn send_text(&mut self, text: &SendText, _: &mut Window, cx: &mut Context<Self>) {
 574        self.clear_bell(cx);
 575        self.terminal.update(cx, |term, _| {
 576            term.input(text.0.to_string());
 577        });
 578    }
 579
 580    fn send_keystroke(&mut self, text: &SendKeystroke, _: &mut Window, cx: &mut Context<Self>) {
 581        if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
 582            self.clear_bell(cx);
 583            self.terminal.update(cx, |term, cx| {
 584                term.try_keystroke(&keystroke, TerminalSettings::get_global(cx).option_as_meta);
 585            });
 586        }
 587    }
 588
 589    fn dispatch_context(&self, cx: &App) -> KeyContext {
 590        let mut dispatch_context = KeyContext::new_with_defaults();
 591        dispatch_context.add("Terminal");
 592
 593        if self.terminal.read(cx).vi_mode_enabled() {
 594            dispatch_context.add("vi_mode");
 595        }
 596
 597        let mode = self.terminal.read(cx).last_content.mode;
 598        dispatch_context.set(
 599            "screen",
 600            if mode.contains(TermMode::ALT_SCREEN) {
 601                "alt"
 602            } else {
 603                "normal"
 604            },
 605        );
 606
 607        if mode.contains(TermMode::APP_CURSOR) {
 608            dispatch_context.add("DECCKM");
 609        }
 610        if mode.contains(TermMode::APP_KEYPAD) {
 611            dispatch_context.add("DECPAM");
 612        } else {
 613            dispatch_context.add("DECPNM");
 614        }
 615        if mode.contains(TermMode::SHOW_CURSOR) {
 616            dispatch_context.add("DECTCEM");
 617        }
 618        if mode.contains(TermMode::LINE_WRAP) {
 619            dispatch_context.add("DECAWM");
 620        }
 621        if mode.contains(TermMode::ORIGIN) {
 622            dispatch_context.add("DECOM");
 623        }
 624        if mode.contains(TermMode::INSERT) {
 625            dispatch_context.add("IRM");
 626        }
 627        //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
 628        if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
 629            dispatch_context.add("LNM");
 630        }
 631        if mode.contains(TermMode::FOCUS_IN_OUT) {
 632            dispatch_context.add("report_focus");
 633        }
 634        if mode.contains(TermMode::ALTERNATE_SCROLL) {
 635            dispatch_context.add("alternate_scroll");
 636        }
 637        if mode.contains(TermMode::BRACKETED_PASTE) {
 638            dispatch_context.add("bracketed_paste");
 639        }
 640        if mode.intersects(TermMode::MOUSE_MODE) {
 641            dispatch_context.add("any_mouse_reporting");
 642        }
 643        {
 644            let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
 645                "click"
 646            } else if mode.contains(TermMode::MOUSE_DRAG) {
 647                "drag"
 648            } else if mode.contains(TermMode::MOUSE_MOTION) {
 649                "motion"
 650            } else {
 651                "off"
 652            };
 653            dispatch_context.set("mouse_reporting", mouse_reporting);
 654        }
 655        {
 656            let format = if mode.contains(TermMode::SGR_MOUSE) {
 657                "sgr"
 658            } else if mode.contains(TermMode::UTF8_MOUSE) {
 659                "utf8"
 660            } else {
 661                "normal"
 662            };
 663            dispatch_context.set("mouse_format", format);
 664        };
 665        dispatch_context
 666    }
 667
 668    fn set_terminal(
 669        &mut self,
 670        terminal: Entity<Terminal>,
 671        window: &mut Window,
 672        cx: &mut Context<TerminalView>,
 673    ) {
 674        self._terminal_subscriptions =
 675            subscribe_for_terminal_events(&terminal, self.workspace.clone(), window, cx);
 676        self.terminal = terminal;
 677    }
 678
 679    // Hack: Using editor in terminal causes cyclic dependency i.e. editor -> terminal -> project -> editor.
 680    fn map_show_scrollbar_from_editor_to_terminal(
 681        show_scrollbar: editor::ShowScrollbar,
 682    ) -> terminal_settings::ShowScrollbar {
 683        match show_scrollbar {
 684            editor::ShowScrollbar::Auto => terminal_settings::ShowScrollbar::Auto,
 685            editor::ShowScrollbar::System => terminal_settings::ShowScrollbar::System,
 686            editor::ShowScrollbar::Always => terminal_settings::ShowScrollbar::Always,
 687            editor::ShowScrollbar::Never => terminal_settings::ShowScrollbar::Never,
 688        }
 689    }
 690
 691    fn should_show_scrollbar(cx: &App) -> bool {
 692        let show = TerminalSettings::get_global(cx)
 693            .scrollbar
 694            .show
 695            .unwrap_or_else(|| {
 696                Self::map_show_scrollbar_from_editor_to_terminal(
 697                    EditorSettings::get_global(cx).scrollbar.show,
 698                )
 699            });
 700        match show {
 701            terminal_settings::ShowScrollbar::Auto => true,
 702            terminal_settings::ShowScrollbar::System => true,
 703            terminal_settings::ShowScrollbar::Always => true,
 704            terminal_settings::ShowScrollbar::Never => false,
 705        }
 706    }
 707
 708    fn should_autohide_scrollbar(cx: &App) -> bool {
 709        let show = TerminalSettings::get_global(cx)
 710            .scrollbar
 711            .show
 712            .unwrap_or_else(|| {
 713                Self::map_show_scrollbar_from_editor_to_terminal(
 714                    EditorSettings::get_global(cx).scrollbar.show,
 715                )
 716            });
 717        match show {
 718            terminal_settings::ShowScrollbar::Auto => true,
 719            terminal_settings::ShowScrollbar::System => cx
 720                .try_global::<ScrollbarAutoHide>()
 721                .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
 722            terminal_settings::ShowScrollbar::Always => false,
 723            terminal_settings::ShowScrollbar::Never => true,
 724        }
 725    }
 726
 727    fn hide_scrollbar(&mut self, cx: &mut Context<Self>) {
 728        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
 729        if !Self::should_autohide_scrollbar(cx) {
 730            return;
 731        }
 732        self.hide_scrollbar_task = Some(cx.spawn(async move |panel, cx| {
 733            cx.background_executor()
 734                .timer(SCROLLBAR_SHOW_INTERVAL)
 735                .await;
 736            panel
 737                .update(cx, |panel, cx| {
 738                    panel.show_scrollbar = false;
 739                    cx.notify();
 740                })
 741                .log_err();
 742        }))
 743    }
 744
 745    fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
 746        if !Self::should_show_scrollbar(cx)
 747            || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
 748        {
 749            return None;
 750        }
 751
 752        if self.terminal.read(cx).total_lines() == self.terminal.read(cx).viewport_lines() {
 753            return None;
 754        }
 755
 756        self.scroll_handle.update(self.terminal.read(cx));
 757
 758        if let Some(new_display_offset) = self.scroll_handle.future_display_offset.take() {
 759            self.terminal.update(cx, |term, _| {
 760                let delta = new_display_offset as i32 - term.last_content.display_offset as i32;
 761                match delta.cmp(&0) {
 762                    std::cmp::Ordering::Greater => term.scroll_up_by(delta as usize),
 763                    std::cmp::Ordering::Less => term.scroll_down_by(-delta as usize),
 764                    std::cmp::Ordering::Equal => {}
 765                }
 766            });
 767        }
 768
 769        Some(
 770            div()
 771                .occlude()
 772                .id("terminal-view-scroll")
 773                .on_mouse_move(cx.listener(|_, _, _window, cx| {
 774                    cx.notify();
 775                    cx.stop_propagation()
 776                }))
 777                .on_hover(|_, _window, cx| {
 778                    cx.stop_propagation();
 779                })
 780                .on_any_mouse_down(|_, _window, cx| {
 781                    cx.stop_propagation();
 782                })
 783                .on_mouse_up(
 784                    MouseButton::Left,
 785                    cx.listener(|terminal_view, _, window, cx| {
 786                        if !terminal_view.scrollbar_state.is_dragging()
 787                            && !terminal_view.focus_handle.contains_focused(window, cx)
 788                        {
 789                            terminal_view.hide_scrollbar(cx);
 790                            cx.notify();
 791                        }
 792                        cx.stop_propagation();
 793                    }),
 794                )
 795                .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
 796                    cx.notify();
 797                }))
 798                .h_full()
 799                .absolute()
 800                .right_1()
 801                .top_1()
 802                .bottom_0()
 803                .w(px(12.))
 804                .cursor_default()
 805                .children(Scrollbar::vertical(self.scrollbar_state.clone())),
 806        )
 807    }
 808
 809    fn rerun_button(task: &TaskState) -> Option<IconButton> {
 810        if !task.show_rerun {
 811            return None;
 812        }
 813
 814        let task_id = task.id.clone();
 815        Some(
 816            IconButton::new("rerun-icon", IconName::Rerun)
 817                .icon_size(IconSize::Small)
 818                .size(ButtonSize::Compact)
 819                .icon_color(Color::Default)
 820                .shape(ui::IconButtonShape::Square)
 821                .tooltip(Tooltip::text("Rerun task"))
 822                .on_click(move |_, window, cx| {
 823                    window.dispatch_action(
 824                        Box::new(zed_actions::Rerun {
 825                            task_id: Some(task_id.0.clone()),
 826                            allow_concurrent_runs: Some(true),
 827                            use_new_terminal: Some(false),
 828                            reevaluate_context: false,
 829                        }),
 830                        cx,
 831                    );
 832                }),
 833        )
 834    }
 835}
 836
 837fn subscribe_for_terminal_events(
 838    terminal: &Entity<Terminal>,
 839    workspace: WeakEntity<Workspace>,
 840    window: &mut Window,
 841    cx: &mut Context<TerminalView>,
 842) -> Vec<Subscription> {
 843    let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
 844    let terminal_events_subscription = cx.subscribe_in(
 845        terminal,
 846        window,
 847        move |this, _, event, window, cx| match event {
 848            Event::Wakeup => {
 849                cx.notify();
 850                cx.emit(Event::Wakeup);
 851                cx.emit(ItemEvent::UpdateTab);
 852                cx.emit(SearchEvent::MatchesInvalidated);
 853            }
 854
 855            Event::Bell => {
 856                this.has_bell = true;
 857                cx.emit(Event::Wakeup);
 858            }
 859
 860            Event::BlinkChanged(blinking) => {
 861                if matches!(
 862                    TerminalSettings::get_global(cx).blinking,
 863                    TerminalBlink::TerminalControlled
 864                ) {
 865                    this.blinking_terminal_enabled = *blinking;
 866                }
 867            }
 868
 869            Event::TitleChanged => {
 870                cx.emit(ItemEvent::UpdateTab);
 871            }
 872
 873            Event::NewNavigationTarget(maybe_navigation_target) => {
 874                this.hover_target_tooltip =
 875                    maybe_navigation_target
 876                        .as_ref()
 877                        .and_then(|navigation_target| match navigation_target {
 878                            MaybeNavigationTarget::Url(url) => Some(url.clone()),
 879                            MaybeNavigationTarget::PathLike(path_like_target) => {
 880                                let valid_files_to_open_task = possible_open_target(
 881                                    &workspace,
 882                                    &path_like_target.terminal_dir,
 883                                    &path_like_target.maybe_path,
 884                                    cx,
 885                                );
 886                                Some(match smol::block_on(valid_files_to_open_task)? {
 887                                    OpenTarget::File(path, _) | OpenTarget::Worktree(path, _) => {
 888                                        path.to_string(|path| path.to_string_lossy().to_string())
 889                                    }
 890                                })
 891                            }
 892                        });
 893                cx.notify()
 894            }
 895
 896            Event::Open(maybe_navigation_target) => match maybe_navigation_target {
 897                MaybeNavigationTarget::Url(url) => cx.open_url(url),
 898
 899                MaybeNavigationTarget::PathLike(path_like_target) => {
 900                    if this.hover_target_tooltip.is_none() {
 901                        return;
 902                    }
 903                    let task_workspace = workspace.clone();
 904                    let path_like_target = path_like_target.clone();
 905                    cx.spawn_in(window, async move |terminal_view, cx| {
 906                        let open_target = terminal_view
 907                            .update(cx, |_, cx| {
 908                                possible_open_target(
 909                                    &task_workspace,
 910                                    &path_like_target.terminal_dir,
 911                                    &path_like_target.maybe_path,
 912                                    cx,
 913                                )
 914                            })?
 915                            .await;
 916                        if let Some(open_target) = open_target {
 917                            let path_to_open = open_target.path();
 918                            let opened_items = task_workspace
 919                                .update_in(cx, |workspace, window, cx| {
 920                                    workspace.open_paths(
 921                                        vec![path_to_open.path.clone()],
 922                                        OpenOptions {
 923                                            visible: Some(OpenVisible::OnlyDirectories),
 924                                            ..Default::default()
 925                                        },
 926                                        None,
 927                                        window,
 928                                        cx,
 929                                    )
 930                                })
 931                                .context("workspace update")?
 932                                .await;
 933                            if opened_items.len() != 1 {
 934                                debug_panic!(
 935                                    "Received {} items for one path {path_to_open:?}",
 936                                    opened_items.len(),
 937                                );
 938                            }
 939
 940                            if let Some(opened_item) = opened_items.first() {
 941                                if open_target.is_file() {
 942                                    if let Some(Ok(opened_item)) = opened_item {
 943                                        if let Some(row) = path_to_open.row {
 944                                            let col = path_to_open.column.unwrap_or(0);
 945                                            if let Some(active_editor) =
 946                                                opened_item.downcast::<Editor>()
 947                                            {
 948                                                active_editor
 949                                                    .downgrade()
 950                                                    .update_in(cx, |editor, window, cx| {
 951                                                        editor.go_to_singleton_buffer_point(
 952                                                            language::Point::new(
 953                                                                row.saturating_sub(1),
 954                                                                col.saturating_sub(1),
 955                                                            ),
 956                                                            window,
 957                                                            cx,
 958                                                        )
 959                                                    })
 960                                                    .log_err();
 961                                            }
 962                                        }
 963                                    }
 964                                } else if open_target.is_dir() {
 965                                    task_workspace.update(cx, |workspace, cx| {
 966                                        workspace.project().update(cx, |_, cx| {
 967                                            cx.emit(project::Event::ActivateProjectPanel);
 968                                        })
 969                                    })?;
 970                                }
 971                            }
 972                        }
 973
 974                        anyhow::Ok(())
 975                    })
 976                    .detach_and_log_err(cx)
 977                }
 978            },
 979            Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
 980            Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
 981            Event::SelectionsChanged => {
 982                window.invalidate_character_coordinates();
 983                cx.emit(SearchEvent::ActiveMatchChanged)
 984            }
 985        },
 986    );
 987    vec![terminal_subscription, terminal_events_subscription]
 988}
 989
 990#[derive(Debug, Clone)]
 991enum OpenTarget {
 992    Worktree(PathWithPosition, Entry),
 993    File(PathWithPosition, Metadata),
 994}
 995
 996impl OpenTarget {
 997    fn is_file(&self) -> bool {
 998        match self {
 999            OpenTarget::Worktree(_, entry) => entry.is_file(),
1000            OpenTarget::File(_, metadata) => !metadata.is_dir,
1001        }
1002    }
1003
1004    fn is_dir(&self) -> bool {
1005        match self {
1006            OpenTarget::Worktree(_, entry) => entry.is_dir(),
1007            OpenTarget::File(_, metadata) => metadata.is_dir,
1008        }
1009    }
1010
1011    fn path(&self) -> &PathWithPosition {
1012        match self {
1013            OpenTarget::Worktree(path, _) => path,
1014            OpenTarget::File(path, _) => path,
1015        }
1016    }
1017}
1018
1019fn possible_open_target(
1020    workspace: &WeakEntity<Workspace>,
1021    cwd: &Option<PathBuf>,
1022    maybe_path: &str,
1023    cx: &App,
1024) -> Task<Option<OpenTarget>> {
1025    let Some(workspace) = workspace.upgrade() else {
1026        return Task::ready(None);
1027    };
1028    // We have to check for both paths, as on Unix, certain paths with positions are valid file paths too.
1029    // We can be on FS remote part, without real FS, so cannot canonicalize or check for existence the path right away.
1030    let mut potential_paths = Vec::new();
1031    let original_path = PathWithPosition::from_path(PathBuf::from(maybe_path));
1032    let path_with_position = PathWithPosition::parse_str(maybe_path);
1033    let worktree_candidates = workspace
1034        .read(cx)
1035        .worktrees(cx)
1036        .sorted_by_key(|worktree| {
1037            let worktree_root = worktree.read(cx).abs_path();
1038            match cwd
1039                .as_ref()
1040                .and_then(|cwd| worktree_root.strip_prefix(cwd).ok())
1041            {
1042                Some(cwd_child) => cwd_child.components().count(),
1043                None => usize::MAX,
1044            }
1045        })
1046        .collect::<Vec<_>>();
1047    // Since we do not check paths via FS and joining, we need to strip off potential `./`, `a/`, `b/` prefixes out of it.
1048    for prefix_str in GIT_DIFF_PATH_PREFIXES.iter().chain(std::iter::once(&".")) {
1049        if let Some(stripped) = original_path.path.strip_prefix(prefix_str).ok() {
1050            potential_paths.push(PathWithPosition {
1051                path: stripped.to_owned(),
1052                row: original_path.row,
1053                column: original_path.column,
1054            });
1055        }
1056        if let Some(stripped) = path_with_position.path.strip_prefix(prefix_str).ok() {
1057            potential_paths.push(PathWithPosition {
1058                path: stripped.to_owned(),
1059                row: path_with_position.row,
1060                column: path_with_position.column,
1061            });
1062        }
1063    }
1064
1065    let insert_both_paths = original_path != path_with_position;
1066    potential_paths.insert(0, original_path);
1067    if insert_both_paths {
1068        potential_paths.insert(1, path_with_position);
1069    }
1070
1071    // If we won't find paths "easily", we can traverse the entire worktree to look what ends with the potential path suffix.
1072    // That will be slow, though, so do the fast checks first.
1073    let mut worktree_paths_to_check = Vec::new();
1074    for worktree in &worktree_candidates {
1075        let worktree_root = worktree.read(cx).abs_path();
1076        let mut paths_to_check = Vec::with_capacity(potential_paths.len());
1077
1078        for path_with_position in &potential_paths {
1079            let path_to_check = if worktree_root.ends_with(&path_with_position.path) {
1080                let root_path_with_posiition = PathWithPosition {
1081                    path: worktree_root.to_path_buf(),
1082                    row: path_with_position.row,
1083                    column: path_with_position.column,
1084                };
1085                match worktree.read(cx).root_entry() {
1086                    Some(root_entry) => {
1087                        return Task::ready(Some(OpenTarget::Worktree(
1088                            root_path_with_posiition,
1089                            root_entry.clone(),
1090                        )));
1091                    }
1092                    None => root_path_with_posiition,
1093                }
1094            } else {
1095                PathWithPosition {
1096                    path: path_with_position
1097                        .path
1098                        .strip_prefix(&worktree_root)
1099                        .unwrap_or(&path_with_position.path)
1100                        .to_owned(),
1101                    row: path_with_position.row,
1102                    column: path_with_position.column,
1103                }
1104            };
1105
1106            if let Some(entry) = worktree.read(cx).entry_for_path(&path_to_check.path) {
1107                return Task::ready(Some(OpenTarget::Worktree(
1108                    PathWithPosition {
1109                        path: worktree_root.join(&entry.path),
1110                        row: path_to_check.row,
1111                        column: path_to_check.column,
1112                    },
1113                    entry.clone(),
1114                )));
1115            } else {
1116                paths_to_check.push(path_to_check);
1117            }
1118        }
1119
1120        if !paths_to_check.is_empty() {
1121            worktree_paths_to_check.push((worktree.clone(), paths_to_check));
1122        }
1123    }
1124
1125    // Before entire worktree traversal(s), make an attempt to do FS checks if available.
1126    let fs_paths_to_check = if workspace.read(cx).project().read(cx).is_local() {
1127        potential_paths
1128            .into_iter()
1129            .flat_map(|path_to_check| {
1130                let mut paths_to_check = Vec::new();
1131                let maybe_path = &path_to_check.path;
1132                if maybe_path.starts_with("~") {
1133                    if let Some(home_path) =
1134                        maybe_path
1135                            .strip_prefix("~")
1136                            .ok()
1137                            .and_then(|stripped_maybe_path| {
1138                                Some(dirs::home_dir()?.join(stripped_maybe_path))
1139                            })
1140                    {
1141                        paths_to_check.push(PathWithPosition {
1142                            path: home_path,
1143                            row: path_to_check.row,
1144                            column: path_to_check.column,
1145                        });
1146                    }
1147                } else {
1148                    paths_to_check.push(PathWithPosition {
1149                        path: maybe_path.clone(),
1150                        row: path_to_check.row,
1151                        column: path_to_check.column,
1152                    });
1153                    if maybe_path.is_relative() {
1154                        if let Some(cwd) = &cwd {
1155                            paths_to_check.push(PathWithPosition {
1156                                path: cwd.join(maybe_path),
1157                                row: path_to_check.row,
1158                                column: path_to_check.column,
1159                            });
1160                        }
1161                        for worktree in &worktree_candidates {
1162                            paths_to_check.push(PathWithPosition {
1163                                path: worktree.read(cx).abs_path().join(maybe_path),
1164                                row: path_to_check.row,
1165                                column: path_to_check.column,
1166                            });
1167                        }
1168                    }
1169                }
1170                paths_to_check
1171            })
1172            .collect()
1173    } else {
1174        Vec::new()
1175    };
1176
1177    let worktree_check_task = cx.spawn(async move |cx| {
1178        for (worktree, worktree_paths_to_check) in worktree_paths_to_check {
1179            let found_entry = worktree
1180                .update(cx, |worktree, _| {
1181                    let worktree_root = worktree.abs_path();
1182                    let mut traversal = worktree.traverse_from_path(true, true, false, "".as_ref());
1183                    while let Some(entry) = traversal.next() {
1184                        if let Some(path_in_worktree) = worktree_paths_to_check
1185                            .iter()
1186                            .find(|path_to_check| entry.path.ends_with(&path_to_check.path))
1187                        {
1188                            return Some(OpenTarget::Worktree(
1189                                PathWithPosition {
1190                                    path: worktree_root.join(&entry.path),
1191                                    row: path_in_worktree.row,
1192                                    column: path_in_worktree.column,
1193                                },
1194                                entry.clone(),
1195                            ));
1196                        }
1197                    }
1198                    None
1199                })
1200                .ok()?;
1201            if let Some(found_entry) = found_entry {
1202                return Some(found_entry);
1203            }
1204        }
1205        None
1206    });
1207
1208    let fs = workspace.read(cx).project().read(cx).fs().clone();
1209    cx.background_spawn(async move {
1210        for path_to_check in fs_paths_to_check {
1211            if let Some(metadata) = fs.metadata(&path_to_check.path).await.ok().flatten() {
1212                return Some(OpenTarget::File(path_to_check, metadata));
1213            }
1214        }
1215
1216        worktree_check_task.await
1217    })
1218}
1219
1220fn regex_to_literal(regex: &str) -> String {
1221    regex
1222        .chars()
1223        .flat_map(|c| {
1224            if REGEX_SPECIAL_CHARS.contains(&c) {
1225                vec!['\\', c]
1226            } else {
1227                vec![c]
1228            }
1229        })
1230        .collect()
1231}
1232
1233pub fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
1234    let query = query.as_str();
1235    if query == "." {
1236        return None;
1237    }
1238    let searcher = RegexSearch::new(query);
1239    searcher.ok()
1240}
1241
1242impl TerminalView {
1243    fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
1244        self.clear_bell(cx);
1245        self.pause_cursor_blinking(window, cx);
1246
1247        self.terminal.update(cx, |term, cx| {
1248            let handled = term.try_keystroke(
1249                &event.keystroke,
1250                TerminalSettings::get_global(cx).option_as_meta,
1251            );
1252            if handled {
1253                cx.stop_propagation();
1254            }
1255        });
1256    }
1257
1258    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1259        self.terminal.update(cx, |terminal, _| {
1260            terminal.set_cursor_shape(self.cursor_shape);
1261            terminal.focus_in();
1262        });
1263        self.blink_cursors(self.blink_epoch, window, cx);
1264        window.invalidate_character_coordinates();
1265        cx.notify();
1266    }
1267
1268    fn focus_out(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1269        self.terminal.update(cx, |terminal, _| {
1270            terminal.focus_out();
1271            terminal.set_cursor_shape(CursorShape::Hollow);
1272        });
1273        self.hide_scrollbar(cx);
1274        cx.notify();
1275    }
1276}
1277
1278impl Render for TerminalView {
1279    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1280        let terminal_handle = self.terminal.clone();
1281        let terminal_view_handle = cx.entity().clone();
1282
1283        let focused = self.focus_handle.is_focused(window);
1284
1285        div()
1286            .id("terminal-view")
1287            .size_full()
1288            .relative()
1289            .track_focus(&self.focus_handle(cx))
1290            .key_context(self.dispatch_context(cx))
1291            .on_action(cx.listener(TerminalView::send_text))
1292            .on_action(cx.listener(TerminalView::send_keystroke))
1293            .on_action(cx.listener(TerminalView::copy))
1294            .on_action(cx.listener(TerminalView::paste))
1295            .on_action(cx.listener(TerminalView::clear))
1296            .on_action(cx.listener(TerminalView::scroll_line_up))
1297            .on_action(cx.listener(TerminalView::scroll_line_down))
1298            .on_action(cx.listener(TerminalView::scroll_page_up))
1299            .on_action(cx.listener(TerminalView::scroll_page_down))
1300            .on_action(cx.listener(TerminalView::scroll_to_top))
1301            .on_action(cx.listener(TerminalView::scroll_to_bottom))
1302            .on_action(cx.listener(TerminalView::toggle_vi_mode))
1303            .on_action(cx.listener(TerminalView::show_character_palette))
1304            .on_action(cx.listener(TerminalView::select_all))
1305            .on_key_down(cx.listener(Self::key_down))
1306            .on_mouse_down(
1307                MouseButton::Right,
1308                cx.listener(|this, event: &MouseDownEvent, window, cx| {
1309                    if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
1310                        if this.terminal.read(cx).last_content.selection.is_none() {
1311                            this.terminal.update(cx, |terminal, _| {
1312                                terminal.select_word_at_event_position(event);
1313                            });
1314                        };
1315                        this.deploy_context_menu(event.position, window, cx);
1316                        cx.notify();
1317                    }
1318                }),
1319            )
1320            .on_hover(cx.listener(|this, hovered, window, cx| {
1321                if *hovered {
1322                    this.show_scrollbar = true;
1323                    this.hide_scrollbar_task.take();
1324                    cx.notify();
1325                } else if !this.focus_handle.contains_focused(window, cx) {
1326                    this.hide_scrollbar(cx);
1327                }
1328            }))
1329            .child(
1330                // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
1331                div()
1332                    .size_full()
1333                    .child(TerminalElement::new(
1334                        terminal_handle,
1335                        terminal_view_handle,
1336                        self.workspace.clone(),
1337                        self.focus_handle.clone(),
1338                        focused,
1339                        self.should_show_cursor(focused, cx),
1340                        self.block_below_cursor.clone(),
1341                    ))
1342                    .when_some(self.render_scrollbar(cx), |div, scrollbar| {
1343                        div.child(scrollbar)
1344                    }),
1345            )
1346            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1347                deferred(
1348                    anchored()
1349                        .position(*position)
1350                        .anchor(gpui::Corner::TopLeft)
1351                        .child(menu.clone()),
1352                )
1353                .with_priority(1)
1354            }))
1355    }
1356}
1357
1358impl Item for TerminalView {
1359    type Event = ItemEvent;
1360
1361    fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
1362        let terminal = self.terminal().read(cx);
1363        let title = terminal.title(false);
1364        let pid = terminal.pty_info.pid_getter().fallback_pid();
1365
1366        Some(TabTooltipContent::Custom(Box::new(move |_window, cx| {
1367            cx.new(|_| TerminalTooltip::new(title.clone(), pid)).into()
1368        })))
1369    }
1370
1371    fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
1372        let terminal = self.terminal().read(cx);
1373        let title = terminal.title(true);
1374
1375        let (icon, icon_color, rerun_button) = match terminal.task() {
1376            Some(terminal_task) => match &terminal_task.status {
1377                TaskStatus::Running => (
1378                    IconName::Play,
1379                    Color::Disabled,
1380                    TerminalView::rerun_button(&terminal_task),
1381                ),
1382                TaskStatus::Unknown => (
1383                    IconName::Warning,
1384                    Color::Warning,
1385                    TerminalView::rerun_button(&terminal_task),
1386                ),
1387                TaskStatus::Completed { success } => {
1388                    let rerun_button = TerminalView::rerun_button(&terminal_task);
1389
1390                    if *success {
1391                        (IconName::Check, Color::Success, rerun_button)
1392                    } else {
1393                        (IconName::XCircle, Color::Error, rerun_button)
1394                    }
1395                }
1396            },
1397            None if self.terminal.read(cx).debug_terminal() => {
1398                (IconName::Debug, Color::Muted, None)
1399            }
1400            None => (IconName::Terminal, Color::Muted, None),
1401        };
1402
1403        h_flex()
1404            .gap_1()
1405            .group("term-tab-icon")
1406            .child(
1407                h_flex()
1408                    .group("term-tab-icon")
1409                    .child(
1410                        div()
1411                            .when(rerun_button.is_some(), |this| {
1412                                this.hover(|style| style.invisible().w_0())
1413                            })
1414                            .child(Icon::new(icon).color(icon_color)),
1415                    )
1416                    .when_some(rerun_button, |this, rerun_button| {
1417                        this.child(
1418                            div()
1419                                .absolute()
1420                                .visible_on_hover("term-tab-icon")
1421                                .child(rerun_button),
1422                        )
1423                    }),
1424            )
1425            .child(Label::new(title).color(params.text_color()))
1426            .into_any()
1427    }
1428
1429    fn telemetry_event_text(&self) -> Option<&'static str> {
1430        None
1431    }
1432
1433    fn clone_on_split(
1434        &self,
1435        workspace_id: Option<WorkspaceId>,
1436        window: &mut Window,
1437        cx: &mut Context<Self>,
1438    ) -> Option<Entity<Self>> {
1439        let window_handle = window.window_handle();
1440        let terminal = self
1441            .project
1442            .update(cx, |project, cx| {
1443                let terminal = self.terminal().read(cx);
1444                let working_directory = terminal
1445                    .working_directory()
1446                    .or_else(|| Some(project.active_project_directory(cx)?.to_path_buf()));
1447                let python_venv_directory = terminal.python_venv_directory.clone();
1448                project.create_terminal_with_venv(
1449                    TerminalKind::Shell(working_directory),
1450                    python_venv_directory,
1451                    window_handle,
1452                    cx,
1453                )
1454            })
1455            .ok()?
1456            .log_err()?;
1457
1458        Some(cx.new(|cx| {
1459            TerminalView::new(
1460                terminal,
1461                self.workspace.clone(),
1462                workspace_id,
1463                self.project.clone(),
1464                window,
1465                cx,
1466            )
1467        }))
1468    }
1469
1470    fn is_dirty(&self, cx: &gpui::App) -> bool {
1471        match self.terminal.read(cx).task() {
1472            Some(task) => task.status == TaskStatus::Running,
1473            None => self.has_bell(),
1474        }
1475    }
1476
1477    fn has_conflict(&self, _cx: &App) -> bool {
1478        false
1479    }
1480
1481    fn can_save_as(&self, _cx: &App) -> bool {
1482        false
1483    }
1484
1485    fn is_singleton(&self, _cx: &App) -> bool {
1486        true
1487    }
1488
1489    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
1490        Some(Box::new(handle.clone()))
1491    }
1492
1493    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1494        if self.show_breadcrumbs && !self.terminal().read(cx).breadcrumb_text.trim().is_empty() {
1495            ToolbarItemLocation::PrimaryLeft
1496        } else {
1497            ToolbarItemLocation::Hidden
1498        }
1499    }
1500
1501    fn breadcrumbs(&self, _: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
1502        Some(vec![BreadcrumbText {
1503            text: self.terminal().read(cx).breadcrumb_text.clone(),
1504            highlights: None,
1505            font: None,
1506        }])
1507    }
1508
1509    fn added_to_workspace(
1510        &mut self,
1511        workspace: &mut Workspace,
1512        _: &mut Window,
1513        cx: &mut Context<Self>,
1514    ) {
1515        if self.terminal().read(cx).task().is_none() {
1516            if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
1517                cx.background_spawn(TERMINAL_DB.update_workspace_id(
1518                    new_id,
1519                    old_id,
1520                    cx.entity_id().as_u64(),
1521                ))
1522                .detach();
1523            }
1524            self.workspace_id = workspace.database_id();
1525        }
1526    }
1527
1528    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1529        f(*event)
1530    }
1531}
1532
1533impl SerializableItem for TerminalView {
1534    fn serialized_item_kind() -> &'static str {
1535        "Terminal"
1536    }
1537
1538    fn cleanup(
1539        workspace_id: WorkspaceId,
1540        alive_items: Vec<workspace::ItemId>,
1541        window: &mut Window,
1542        cx: &mut App,
1543    ) -> Task<gpui::Result<()>> {
1544        window.spawn(cx, async move |_| {
1545            TERMINAL_DB
1546                .delete_unloaded_items(workspace_id, alive_items)
1547                .await
1548        })
1549    }
1550
1551    fn serialize(
1552        &mut self,
1553        _workspace: &mut Workspace,
1554        item_id: workspace::ItemId,
1555        _closing: bool,
1556        _: &mut Window,
1557        cx: &mut Context<Self>,
1558    ) -> Option<Task<gpui::Result<()>>> {
1559        let terminal = self.terminal().read(cx);
1560        if terminal.task().is_some() || terminal.debug_terminal() {
1561            return None;
1562        }
1563
1564        if let Some((cwd, workspace_id)) = terminal.working_directory().zip(self.workspace_id) {
1565            Some(cx.background_spawn(async move {
1566                TERMINAL_DB
1567                    .save_working_directory(item_id, workspace_id, cwd)
1568                    .await
1569            }))
1570        } else {
1571            None
1572        }
1573    }
1574
1575    fn should_serialize(&self, event: &Self::Event) -> bool {
1576        matches!(event, ItemEvent::UpdateTab)
1577    }
1578
1579    fn deserialize(
1580        project: Entity<Project>,
1581        workspace: WeakEntity<Workspace>,
1582        workspace_id: workspace::WorkspaceId,
1583        item_id: workspace::ItemId,
1584        window: &mut Window,
1585        cx: &mut App,
1586    ) -> Task<anyhow::Result<Entity<Self>>> {
1587        let window_handle = window.window_handle();
1588        window.spawn(cx, async move |cx| {
1589            let cwd = cx
1590                .update(|_window, cx| {
1591                    let from_db = TERMINAL_DB
1592                        .get_working_directory(item_id, workspace_id)
1593                        .log_err()
1594                        .flatten();
1595                    if from_db
1596                        .as_ref()
1597                        .is_some_and(|from_db| !from_db.as_os_str().is_empty())
1598                    {
1599                        from_db
1600                    } else {
1601                        workspace
1602                            .upgrade()
1603                            .and_then(|workspace| default_working_directory(workspace.read(cx), cx))
1604                    }
1605                })
1606                .ok()
1607                .flatten();
1608
1609            let terminal = project
1610                .update(cx, |project, cx| {
1611                    project.create_terminal(TerminalKind::Shell(cwd), window_handle, cx)
1612                })?
1613                .await?;
1614            cx.update(|window, cx| {
1615                cx.new(|cx| {
1616                    TerminalView::new(
1617                        terminal,
1618                        workspace,
1619                        Some(workspace_id),
1620                        project.downgrade(),
1621                        window,
1622                        cx,
1623                    )
1624                })
1625            })
1626        })
1627    }
1628}
1629
1630impl SearchableItem for TerminalView {
1631    type Match = RangeInclusive<Point>;
1632
1633    fn supported_options(&self) -> SearchOptions {
1634        SearchOptions {
1635            case: false,
1636            word: false,
1637            regex: true,
1638            replacement: false,
1639            selection: false,
1640            find_in_results: false,
1641        }
1642    }
1643
1644    /// Clear stored matches
1645    fn clear_matches(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1646        self.terminal().update(cx, |term, _| term.matches.clear())
1647    }
1648
1649    /// Store matches returned from find_matches somewhere for rendering
1650    fn update_matches(
1651        &mut self,
1652        matches: &[Self::Match],
1653        _window: &mut Window,
1654        cx: &mut Context<Self>,
1655    ) {
1656        self.terminal()
1657            .update(cx, |term, _| term.matches = matches.to_vec())
1658    }
1659
1660    /// Returns the selection content to pre-load into this search
1661    fn query_suggestion(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> String {
1662        self.terminal()
1663            .read(cx)
1664            .last_content
1665            .selection_text
1666            .clone()
1667            .unwrap_or_default()
1668    }
1669
1670    /// Focus match at given index into the Vec of matches
1671    fn activate_match(
1672        &mut self,
1673        index: usize,
1674        _: &[Self::Match],
1675        _window: &mut Window,
1676        cx: &mut Context<Self>,
1677    ) {
1678        self.terminal()
1679            .update(cx, |term, _| term.activate_match(index));
1680        cx.notify();
1681    }
1682
1683    /// Add selections for all matches given.
1684    fn select_matches(&mut self, matches: &[Self::Match], _: &mut Window, cx: &mut Context<Self>) {
1685        self.terminal()
1686            .update(cx, |term, _| term.select_matches(matches));
1687        cx.notify();
1688    }
1689
1690    /// Get all of the matches for this query, should be done on the background
1691    fn find_matches(
1692        &mut self,
1693        query: Arc<SearchQuery>,
1694        _: &mut Window,
1695        cx: &mut Context<Self>,
1696    ) -> Task<Vec<Self::Match>> {
1697        let searcher = match &*query {
1698            SearchQuery::Text { .. } => regex_search_for_query(
1699                &(SearchQuery::text(
1700                    regex_to_literal(query.as_str()),
1701                    query.whole_word(),
1702                    query.case_sensitive(),
1703                    query.include_ignored(),
1704                    query.files_to_include().clone(),
1705                    query.files_to_exclude().clone(),
1706                    false,
1707                    None,
1708                )
1709                .unwrap()),
1710            ),
1711            SearchQuery::Regex { .. } => regex_search_for_query(&query),
1712        };
1713
1714        if let Some(s) = searcher {
1715            self.terminal()
1716                .update(cx, |term, cx| term.find_matches(s, cx))
1717        } else {
1718            Task::ready(vec![])
1719        }
1720    }
1721
1722    /// Reports back to the search toolbar what the active match should be (the selection)
1723    fn active_match_index(
1724        &mut self,
1725        direction: Direction,
1726        matches: &[Self::Match],
1727        _: &mut Window,
1728        cx: &mut Context<Self>,
1729    ) -> Option<usize> {
1730        // Selection head might have a value if there's a selection that isn't
1731        // associated with a match. Therefore, if there are no matches, we should
1732        // report None, no matter the state of the terminal
1733        let res = if !matches.is_empty() {
1734            if let Some(selection_head) = self.terminal().read(cx).selection_head {
1735                // If selection head is contained in a match. Return that match
1736                match direction {
1737                    Direction::Prev => {
1738                        // If no selection before selection head, return the first match
1739                        Some(
1740                            matches
1741                                .iter()
1742                                .enumerate()
1743                                .rev()
1744                                .find(|(_, search_match)| {
1745                                    search_match.contains(&selection_head)
1746                                        || search_match.start() < &selection_head
1747                                })
1748                                .map(|(ix, _)| ix)
1749                                .unwrap_or(0),
1750                        )
1751                    }
1752                    Direction::Next => {
1753                        // If no selection after selection head, return the last match
1754                        Some(
1755                            matches
1756                                .iter()
1757                                .enumerate()
1758                                .find(|(_, search_match)| {
1759                                    search_match.contains(&selection_head)
1760                                        || search_match.start() > &selection_head
1761                                })
1762                                .map(|(ix, _)| ix)
1763                                .unwrap_or(matches.len().saturating_sub(1)),
1764                        )
1765                    }
1766                }
1767            } else {
1768                // Matches found but no active selection, return the first last one (closest to cursor)
1769                Some(matches.len().saturating_sub(1))
1770            }
1771        } else {
1772            None
1773        };
1774
1775        res
1776    }
1777    fn replace(
1778        &mut self,
1779        _: &Self::Match,
1780        _: &SearchQuery,
1781        _window: &mut Window,
1782        _: &mut Context<Self>,
1783    ) {
1784        // Replacement is not supported in terminal view, so this is a no-op.
1785    }
1786}
1787
1788///Gets the working directory for the given workspace, respecting the user's settings.
1789/// None implies "~" on whichever machine we end up on.
1790pub(crate) fn default_working_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1791    match &TerminalSettings::get_global(cx).working_directory {
1792        WorkingDirectory::CurrentProjectDirectory => workspace
1793            .project()
1794            .read(cx)
1795            .active_project_directory(cx)
1796            .as_deref()
1797            .map(Path::to_path_buf),
1798        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1799        WorkingDirectory::AlwaysHome => None,
1800        WorkingDirectory::Always { directory } => {
1801            shellexpand::full(&directory) //TODO handle this better
1802                .ok()
1803                .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1804                .filter(|dir| dir.is_dir())
1805        }
1806    }
1807}
1808///Gets the first project's home directory, or the home directory
1809fn first_project_directory(workspace: &Workspace, cx: &App) -> Option<PathBuf> {
1810    let worktree = workspace.worktrees(cx).next()?.read(cx);
1811    if !worktree.root_entry()?.is_dir() {
1812        return None;
1813    }
1814    Some(worktree.abs_path().to_path_buf())
1815}
1816
1817#[cfg(test)]
1818mod tests {
1819    use super::*;
1820    use gpui::TestAppContext;
1821    use project::{Entry, Project, ProjectPath, Worktree};
1822    use std::path::Path;
1823    use workspace::AppState;
1824
1825    // Working directory calculation tests
1826
1827    // No Worktrees in project -> home_dir()
1828    #[gpui::test]
1829    async fn no_worktree(cx: &mut TestAppContext) {
1830        let (project, workspace) = init_test(cx).await;
1831        cx.read(|cx| {
1832            let workspace = workspace.read(cx);
1833            let active_entry = project.read(cx).active_entry();
1834
1835            //Make sure environment is as expected
1836            assert!(active_entry.is_none());
1837            assert!(workspace.worktrees(cx).next().is_none());
1838
1839            let res = default_working_directory(workspace, cx);
1840            assert_eq!(res, None);
1841            let res = first_project_directory(workspace, cx);
1842            assert_eq!(res, None);
1843        });
1844    }
1845
1846    // No active entry, but a worktree, worktree is a file -> home_dir()
1847    #[gpui::test]
1848    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1849        let (project, workspace) = init_test(cx).await;
1850
1851        create_file_wt(project.clone(), "/root.txt", cx).await;
1852        cx.read(|cx| {
1853            let workspace = workspace.read(cx);
1854            let active_entry = project.read(cx).active_entry();
1855
1856            //Make sure environment is as expected
1857            assert!(active_entry.is_none());
1858            assert!(workspace.worktrees(cx).next().is_some());
1859
1860            let res = default_working_directory(workspace, cx);
1861            assert_eq!(res, None);
1862            let res = first_project_directory(workspace, cx);
1863            assert_eq!(res, None);
1864        });
1865    }
1866
1867    // No active entry, but a worktree, worktree is a folder -> worktree_folder
1868    #[gpui::test]
1869    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1870        let (project, workspace) = init_test(cx).await;
1871
1872        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1873        cx.update(|cx| {
1874            let workspace = workspace.read(cx);
1875            let active_entry = project.read(cx).active_entry();
1876
1877            assert!(active_entry.is_none());
1878            assert!(workspace.worktrees(cx).next().is_some());
1879
1880            let res = default_working_directory(workspace, cx);
1881            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1882            let res = first_project_directory(workspace, cx);
1883            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1884        });
1885    }
1886
1887    // Active entry with a work tree, worktree is a file -> worktree_folder()
1888    #[gpui::test]
1889    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1890        let (project, workspace) = init_test(cx).await;
1891
1892        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1893        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1894        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1895
1896        cx.update(|cx| {
1897            let workspace = workspace.read(cx);
1898            let active_entry = project.read(cx).active_entry();
1899
1900            assert!(active_entry.is_some());
1901
1902            let res = default_working_directory(workspace, cx);
1903            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1904            let res = first_project_directory(workspace, cx);
1905            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1906        });
1907    }
1908
1909    // Active entry, with a worktree, worktree is a folder -> worktree_folder
1910    #[gpui::test]
1911    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1912        let (project, workspace) = init_test(cx).await;
1913
1914        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1915        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1916        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1917
1918        cx.update(|cx| {
1919            let workspace = workspace.read(cx);
1920            let active_entry = project.read(cx).active_entry();
1921
1922            assert!(active_entry.is_some());
1923
1924            let res = default_working_directory(workspace, cx);
1925            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1926            let res = first_project_directory(workspace, cx);
1927            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1928        });
1929    }
1930
1931    /// Creates a worktree with 1 file: /root.txt
1932    pub async fn init_test(cx: &mut TestAppContext) -> (Entity<Project>, Entity<Workspace>) {
1933        let params = cx.update(AppState::test);
1934        cx.update(|cx| {
1935            terminal::init(cx);
1936            theme::init(theme::LoadThemes::JustBase, cx);
1937            Project::init_settings(cx);
1938            language::init(cx);
1939        });
1940
1941        let project = Project::test(params.fs.clone(), [], cx).await;
1942        let workspace = cx
1943            .add_window(|window, cx| Workspace::test_new(project.clone(), window, cx))
1944            .root(cx)
1945            .unwrap();
1946
1947        (project, workspace)
1948    }
1949
1950    /// Creates a worktree with 1 folder: /root{suffix}/
1951    async fn create_folder_wt(
1952        project: Entity<Project>,
1953        path: impl AsRef<Path>,
1954        cx: &mut TestAppContext,
1955    ) -> (Entity<Worktree>, Entry) {
1956        create_wt(project, true, path, cx).await
1957    }
1958
1959    /// Creates a worktree with 1 file: /root{suffix}.txt
1960    async fn create_file_wt(
1961        project: Entity<Project>,
1962        path: impl AsRef<Path>,
1963        cx: &mut TestAppContext,
1964    ) -> (Entity<Worktree>, Entry) {
1965        create_wt(project, false, path, cx).await
1966    }
1967
1968    async fn create_wt(
1969        project: Entity<Project>,
1970        is_dir: bool,
1971        path: impl AsRef<Path>,
1972        cx: &mut TestAppContext,
1973    ) -> (Entity<Worktree>, Entry) {
1974        let (wt, _) = project
1975            .update(cx, |project, cx| {
1976                project.find_or_create_worktree(path, true, cx)
1977            })
1978            .await
1979            .unwrap();
1980
1981        let entry = cx
1982            .update(|cx| {
1983                wt.update(cx, |wt, cx| {
1984                    wt.create_entry(Path::new(""), is_dir, None, cx)
1985                })
1986            })
1987            .await
1988            .unwrap()
1989            .to_included()
1990            .unwrap();
1991
1992        (wt, entry)
1993    }
1994
1995    pub fn insert_active_entry_for(
1996        wt: Entity<Worktree>,
1997        entry: Entry,
1998        project: Entity<Project>,
1999        cx: &mut TestAppContext,
2000    ) {
2001        cx.update(|cx| {
2002            let p = ProjectPath {
2003                worktree_id: wt.read(cx).id(),
2004                path: entry.path,
2005            };
2006            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
2007        });
2008    }
2009
2010    #[test]
2011    fn escapes_only_special_characters() {
2012        assert_eq!(regex_to_literal(r"test(\w)"), r"test\(\\w\)".to_string());
2013    }
2014
2015    #[test]
2016    fn empty_string_stays_empty() {
2017        assert_eq!(regex_to_literal(""), "".to_string());
2018    }
2019}