terminal_view.rs

   1mod persistence;
   2pub mod terminal_element;
   3pub mod terminal_panel;
   4
   5use collections::HashSet;
   6use editor::{scroll::Autoscroll, Editor};
   7use futures::{stream::FuturesUnordered, StreamExt};
   8use gpui::{
   9    anchored, deferred, div, impl_actions, AnyElement, AppContext, DismissEvent, EventEmitter,
  10    FocusHandle, FocusableView, KeyContext, KeyDownEvent, Keystroke, Model, MouseButton,
  11    MouseDownEvent, Pixels, Render, Styled, Subscription, Task, View, VisualContext, WeakView,
  12};
  13use language::Bias;
  14use persistence::TERMINAL_DB;
  15use project::{search::SearchQuery, Fs, LocalWorktree, Metadata, Project};
  16use settings::SettingsStore;
  17use task::TerminalWorkDir;
  18use terminal::{
  19    alacritty_terminal::{
  20        index::Point,
  21        term::{search::RegexSearch, TermMode},
  22    },
  23    terminal_settings::{TerminalBlink, TerminalSettings, WorkingDirectory},
  24    Clear, Copy, Event, MaybeNavigationTarget, Paste, ShowCharacterPalette, TaskStatus, Terminal,
  25};
  26use terminal_element::TerminalElement;
  27use ui::{h_flex, prelude::*, ContextMenu, Icon, IconName, Label, Tooltip};
  28use util::{paths::PathLikeWithPosition, ResultExt};
  29use workspace::{
  30    item::{BreadcrumbText, Item, ItemEvent, TabContentParams},
  31    notifications::NotifyResultExt,
  32    register_deserializable_item,
  33    searchable::{SearchEvent, SearchOptions, SearchableItem, SearchableItemHandle},
  34    CloseActiveItem, NewCenterTerminal, OpenVisible, Pane, ToolbarItemLocation, Workspace,
  35    WorkspaceId,
  36};
  37
  38use anyhow::Context;
  39use dirs::home_dir;
  40use serde::Deserialize;
  41use settings::Settings;
  42use smol::Timer;
  43
  44use std::{
  45    ops::RangeInclusive,
  46    path::{Path, PathBuf},
  47    sync::Arc,
  48    time::Duration,
  49};
  50
  51const REGEX_SPECIAL_CHARS: &[char] = &[
  52    '\\', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '^', '$',
  53];
  54
  55const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  56
  57///Event to transmit the scroll from the element to the view
  58#[derive(Clone, Debug, PartialEq)]
  59pub struct ScrollTerminal(pub i32);
  60
  61#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
  62pub struct SendText(String);
  63
  64#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
  65pub struct SendKeystroke(String);
  66
  67impl_actions!(terminal, [SendText, SendKeystroke]);
  68
  69pub fn init(cx: &mut AppContext) {
  70    terminal_panel::init(cx);
  71    terminal::init(cx);
  72
  73    register_deserializable_item::<TerminalView>(cx);
  74
  75    cx.observe_new_views(|workspace: &mut Workspace, _| {
  76        workspace.register_action(TerminalView::deploy);
  77    })
  78    .detach();
  79}
  80
  81///A terminal view, maintains the PTY's file handles and communicates with the terminal
  82pub struct TerminalView {
  83    terminal: Model<Terminal>,
  84    workspace: WeakView<Workspace>,
  85    focus_handle: FocusHandle,
  86    //Currently using iTerm bell, show bell emoji in tab until input is received
  87    has_bell: bool,
  88    context_menu: Option<(View<ContextMenu>, gpui::Point<Pixels>, Subscription)>,
  89    blink_state: bool,
  90    blinking_on: bool,
  91    blinking_paused: bool,
  92    blink_epoch: usize,
  93    can_navigate_to_selected_word: bool,
  94    workspace_id: WorkspaceId,
  95    show_title: bool,
  96    _subscriptions: Vec<Subscription>,
  97    _terminal_subscriptions: Vec<Subscription>,
  98}
  99
 100impl EventEmitter<Event> for TerminalView {}
 101impl EventEmitter<ItemEvent> for TerminalView {}
 102impl EventEmitter<SearchEvent> for TerminalView {}
 103
 104impl FocusableView for TerminalView {
 105    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
 106        self.focus_handle.clone()
 107    }
 108}
 109
 110impl TerminalView {
 111    ///Create a new Terminal in the current working directory or the user's home directory
 112    pub fn deploy(
 113        workspace: &mut Workspace,
 114        _: &NewCenterTerminal,
 115        cx: &mut ViewContext<Workspace>,
 116    ) {
 117        let strategy = TerminalSettings::get_global(cx);
 118        let working_directory =
 119            get_working_directory(workspace, cx, strategy.working_directory.clone());
 120
 121        let window = cx.window_handle();
 122        let terminal = workspace
 123            .project()
 124            .update(cx, |project, cx| {
 125                project.create_terminal(working_directory, None, window, cx)
 126            })
 127            .notify_err(workspace, cx);
 128
 129        if let Some(terminal) = terminal {
 130            let view = cx.new_view(|cx| {
 131                TerminalView::new(
 132                    terminal,
 133                    workspace.weak_handle(),
 134                    workspace.database_id(),
 135                    cx,
 136                )
 137            });
 138            workspace.add_item_to_active_pane(Box::new(view), None, cx)
 139        }
 140    }
 141
 142    pub fn new(
 143        terminal: Model<Terminal>,
 144        workspace: WeakView<Workspace>,
 145        workspace_id: WorkspaceId,
 146        cx: &mut ViewContext<Self>,
 147    ) -> Self {
 148        let workspace_handle = workspace.clone();
 149        let terminal_subscriptions = subscribe_for_terminal_events(&terminal, workspace, cx);
 150
 151        let focus_handle = cx.focus_handle();
 152        let focus_in = cx.on_focus_in(&focus_handle, |terminal_view, cx| {
 153            terminal_view.focus_in(cx);
 154        });
 155        let focus_out = cx.on_focus_out(&focus_handle, |terminal_view, cx| {
 156            terminal_view.focus_out(cx);
 157        });
 158
 159        Self {
 160            terminal,
 161            workspace: workspace_handle,
 162            has_bell: false,
 163            focus_handle,
 164            context_menu: None,
 165            blink_state: true,
 166            blinking_on: false,
 167            blinking_paused: false,
 168            blink_epoch: 0,
 169            can_navigate_to_selected_word: false,
 170            workspace_id,
 171            show_title: TerminalSettings::get_global(cx).toolbar.title,
 172            _subscriptions: vec![
 173                focus_in,
 174                focus_out,
 175                cx.observe_global::<SettingsStore>(Self::settings_changed),
 176            ],
 177            _terminal_subscriptions: terminal_subscriptions,
 178        }
 179    }
 180
 181    pub fn model(&self) -> &Model<Terminal> {
 182        &self.terminal
 183    }
 184
 185    pub fn has_bell(&self) -> bool {
 186        self.has_bell
 187    }
 188
 189    pub fn clear_bell(&mut self, cx: &mut ViewContext<TerminalView>) {
 190        self.has_bell = false;
 191        cx.emit(Event::Wakeup);
 192    }
 193
 194    pub fn deploy_context_menu(
 195        &mut self,
 196        position: gpui::Point<Pixels>,
 197        cx: &mut ViewContext<Self>,
 198    ) {
 199        let context_menu = ContextMenu::build(cx, |menu, _| {
 200            menu.action("Clear", Box::new(Clear))
 201                .action("Close", Box::new(CloseActiveItem { save_intent: None }))
 202        });
 203
 204        cx.focus_view(&context_menu);
 205        let subscription =
 206            cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
 207                if this.context_menu.as_ref().is_some_and(|context_menu| {
 208                    context_menu.0.focus_handle(cx).contains_focused(cx)
 209                }) {
 210                    cx.focus_self();
 211                }
 212                this.context_menu.take();
 213                cx.notify();
 214            });
 215
 216        self.context_menu = Some((context_menu, position, subscription));
 217    }
 218
 219    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
 220        let settings = TerminalSettings::get_global(cx);
 221        self.show_title = settings.toolbar.title;
 222        cx.notify();
 223    }
 224
 225    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 226        if self
 227            .terminal
 228            .read(cx)
 229            .last_content
 230            .mode
 231            .contains(TermMode::ALT_SCREEN)
 232        {
 233            self.terminal.update(cx, |term, cx| {
 234                term.try_keystroke(
 235                    &Keystroke::parse("ctrl-cmd-space").unwrap(),
 236                    TerminalSettings::get_global(cx).option_as_meta,
 237                )
 238            });
 239        } else {
 240            cx.show_character_palette();
 241        }
 242    }
 243
 244    fn select_all(&mut self, _: &editor::actions::SelectAll, cx: &mut ViewContext<Self>) {
 245        self.terminal.update(cx, |term, _| term.select_all());
 246        cx.notify();
 247    }
 248
 249    fn clear(&mut self, _: &Clear, cx: &mut ViewContext<Self>) {
 250        self.terminal.update(cx, |term, _| term.clear());
 251        cx.notify();
 252    }
 253
 254    pub fn should_show_cursor(&self, focused: bool, cx: &mut gpui::ViewContext<Self>) -> bool {
 255        //Don't blink the cursor when not focused, blinking is disabled, or paused
 256        if !focused
 257            || !self.blinking_on
 258            || self.blinking_paused
 259            || self
 260                .terminal
 261                .read(cx)
 262                .last_content
 263                .mode
 264                .contains(TermMode::ALT_SCREEN)
 265        {
 266            return true;
 267        }
 268
 269        match TerminalSettings::get_global(cx).blinking {
 270            //If the user requested to never blink, don't blink it.
 271            TerminalBlink::Off => true,
 272            //If the terminal is controlling it, check terminal mode
 273            TerminalBlink::TerminalControlled | TerminalBlink::On => self.blink_state,
 274        }
 275    }
 276
 277    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
 278        if epoch == self.blink_epoch && !self.blinking_paused {
 279            self.blink_state = !self.blink_state;
 280            cx.notify();
 281
 282            let epoch = self.next_blink_epoch();
 283            cx.spawn(|this, mut cx| async move {
 284                Timer::after(CURSOR_BLINK_INTERVAL).await;
 285                this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx))
 286                    .ok();
 287            })
 288            .detach();
 289        }
 290    }
 291
 292    pub fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
 293        self.blink_state = true;
 294        cx.notify();
 295
 296        let epoch = self.next_blink_epoch();
 297        cx.spawn(|this, mut cx| async move {
 298            Timer::after(CURSOR_BLINK_INTERVAL).await;
 299            this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
 300                .ok();
 301        })
 302        .detach();
 303    }
 304
 305    pub fn terminal(&self) -> &Model<Terminal> {
 306        &self.terminal
 307    }
 308
 309    fn next_blink_epoch(&mut self) -> usize {
 310        self.blink_epoch += 1;
 311        self.blink_epoch
 312    }
 313
 314    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
 315        if epoch == self.blink_epoch {
 316            self.blinking_paused = false;
 317            self.blink_cursors(epoch, cx);
 318        }
 319    }
 320
 321    ///Attempt to paste the clipboard into the terminal
 322    fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 323        self.terminal.update(cx, |term, _| term.copy());
 324        cx.notify();
 325    }
 326
 327    ///Attempt to paste the clipboard into the terminal
 328    fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 329        if let Some(item) = cx.read_from_clipboard() {
 330            self.terminal
 331                .update(cx, |terminal, _cx| terminal.paste(item.text()));
 332        }
 333    }
 334
 335    fn send_text(&mut self, text: &SendText, cx: &mut ViewContext<Self>) {
 336        self.clear_bell(cx);
 337        self.terminal.update(cx, |term, _| {
 338            term.input(text.0.to_string());
 339        });
 340    }
 341
 342    fn send_keystroke(&mut self, text: &SendKeystroke, cx: &mut ViewContext<Self>) {
 343        if let Some(keystroke) = Keystroke::parse(&text.0).log_err() {
 344            self.clear_bell(cx);
 345            self.terminal.update(cx, |term, cx| {
 346                term.try_keystroke(&keystroke, TerminalSettings::get_global(cx).option_as_meta);
 347            });
 348        }
 349    }
 350
 351    fn dispatch_context(&self, cx: &AppContext) -> KeyContext {
 352        let mut dispatch_context = KeyContext::new_with_defaults();
 353        dispatch_context.add("Terminal");
 354
 355        let mode = self.terminal.read(cx).last_content.mode;
 356        dispatch_context.set(
 357            "screen",
 358            if mode.contains(TermMode::ALT_SCREEN) {
 359                "alt"
 360            } else {
 361                "normal"
 362            },
 363        );
 364
 365        if mode.contains(TermMode::APP_CURSOR) {
 366            dispatch_context.add("DECCKM");
 367        }
 368        if mode.contains(TermMode::APP_KEYPAD) {
 369            dispatch_context.add("DECPAM");
 370        } else {
 371            dispatch_context.add("DECPNM");
 372        }
 373        if mode.contains(TermMode::SHOW_CURSOR) {
 374            dispatch_context.add("DECTCEM");
 375        }
 376        if mode.contains(TermMode::LINE_WRAP) {
 377            dispatch_context.add("DECAWM");
 378        }
 379        if mode.contains(TermMode::ORIGIN) {
 380            dispatch_context.add("DECOM");
 381        }
 382        if mode.contains(TermMode::INSERT) {
 383            dispatch_context.add("IRM");
 384        }
 385        //LNM is apparently the name for this. https://vt100.net/docs/vt510-rm/LNM.html
 386        if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
 387            dispatch_context.add("LNM");
 388        }
 389        if mode.contains(TermMode::FOCUS_IN_OUT) {
 390            dispatch_context.add("report_focus");
 391        }
 392        if mode.contains(TermMode::ALTERNATE_SCROLL) {
 393            dispatch_context.add("alternate_scroll");
 394        }
 395        if mode.contains(TermMode::BRACKETED_PASTE) {
 396            dispatch_context.add("bracketed_paste");
 397        }
 398        if mode.intersects(TermMode::MOUSE_MODE) {
 399            dispatch_context.add("any_mouse_reporting");
 400        }
 401        {
 402            let mouse_reporting = if mode.contains(TermMode::MOUSE_REPORT_CLICK) {
 403                "click"
 404            } else if mode.contains(TermMode::MOUSE_DRAG) {
 405                "drag"
 406            } else if mode.contains(TermMode::MOUSE_MOTION) {
 407                "motion"
 408            } else {
 409                "off"
 410            };
 411            dispatch_context.set("mouse_reporting", mouse_reporting);
 412        }
 413        {
 414            let format = if mode.contains(TermMode::SGR_MOUSE) {
 415                "sgr"
 416            } else if mode.contains(TermMode::UTF8_MOUSE) {
 417                "utf8"
 418            } else {
 419                "normal"
 420            };
 421            dispatch_context.set("mouse_format", format);
 422        };
 423        dispatch_context
 424    }
 425
 426    fn set_terminal(&mut self, terminal: Model<Terminal>, cx: &mut ViewContext<'_, TerminalView>) {
 427        self._terminal_subscriptions =
 428            subscribe_for_terminal_events(&terminal, self.workspace.clone(), cx);
 429        self.terminal = terminal;
 430    }
 431}
 432
 433fn subscribe_for_terminal_events(
 434    terminal: &Model<Terminal>,
 435    workspace: WeakView<Workspace>,
 436    cx: &mut ViewContext<'_, TerminalView>,
 437) -> Vec<Subscription> {
 438    let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
 439    let terminal_events_subscription =
 440        cx.subscribe(terminal, move |this, _, event, cx| match event {
 441            Event::Wakeup => {
 442                cx.notify();
 443                cx.emit(Event::Wakeup);
 444                cx.emit(ItemEvent::UpdateTab);
 445                cx.emit(SearchEvent::MatchesInvalidated);
 446            }
 447
 448            Event::Bell => {
 449                this.has_bell = true;
 450                cx.emit(Event::Wakeup);
 451            }
 452
 453            Event::BlinkChanged => this.blinking_on = !this.blinking_on,
 454
 455            Event::TitleChanged => {
 456                cx.emit(ItemEvent::UpdateTab);
 457                let terminal = this.terminal().read(cx);
 458                if terminal.task().is_none() {
 459                    if let Some(cwd) = terminal.get_cwd() {
 460                        let item_id = cx.entity_id();
 461                        let workspace_id = this.workspace_id;
 462                        cx.background_executor()
 463                            .spawn(async move {
 464                                TERMINAL_DB
 465                                    .save_working_directory(item_id.as_u64(), workspace_id, cwd)
 466                                    .await
 467                                    .log_err();
 468                            })
 469                            .detach();
 470                    }
 471                }
 472            }
 473
 474            Event::NewNavigationTarget(maybe_navigation_target) => {
 475                this.can_navigate_to_selected_word = match maybe_navigation_target {
 476                    Some(MaybeNavigationTarget::Url(_)) => true,
 477                    Some(MaybeNavigationTarget::PathLike(path_like_target)) => {
 478                        if let Ok(fs) = workspace.update(cx, |workspace, cx| {
 479                            workspace.project().read(cx).fs().clone()
 480                        }) {
 481                            let valid_files_to_open_task = possible_open_targets(
 482                                fs,
 483                                &workspace,
 484                                &path_like_target.terminal_dir,
 485                                &path_like_target.maybe_path,
 486                                cx,
 487                            );
 488                            smol::block_on(valid_files_to_open_task).len() > 0
 489                        } else {
 490                            false
 491                        }
 492                    }
 493                    None => false,
 494                }
 495            }
 496
 497            Event::Open(maybe_navigation_target) => match maybe_navigation_target {
 498                MaybeNavigationTarget::Url(url) => cx.open_url(url),
 499
 500                MaybeNavigationTarget::PathLike(path_like_target) => {
 501                    if !this.can_navigate_to_selected_word {
 502                        return;
 503                    }
 504                    let task_workspace = workspace.clone();
 505                    let Some(fs) = workspace
 506                        .update(cx, |workspace, cx| {
 507                            workspace.project().read(cx).fs().clone()
 508                        })
 509                        .ok()
 510                    else {
 511                        return;
 512                    };
 513
 514                    let path_like_target = path_like_target.clone();
 515                    cx.spawn(|terminal_view, mut cx| async move {
 516                        let valid_files_to_open = terminal_view
 517                            .update(&mut cx, |_, cx| {
 518                                possible_open_targets(
 519                                    fs,
 520                                    &task_workspace,
 521                                    &path_like_target.terminal_dir,
 522                                    &path_like_target.maybe_path,
 523                                    cx,
 524                                )
 525                            })?
 526                            .await;
 527                        let paths_to_open = valid_files_to_open
 528                            .iter()
 529                            .map(|(p, _)| p.path_like.clone())
 530                            .collect();
 531                        let opened_items = task_workspace
 532                            .update(&mut cx, |workspace, cx| {
 533                                workspace.open_paths(
 534                                    paths_to_open,
 535                                    OpenVisible::OnlyDirectories,
 536                                    None,
 537                                    cx,
 538                                )
 539                            })
 540                            .context("workspace update")?
 541                            .await;
 542
 543                        let mut has_dirs = false;
 544                        for ((path, metadata), opened_item) in valid_files_to_open
 545                            .into_iter()
 546                            .zip(opened_items.into_iter())
 547                        {
 548                            if metadata.is_dir {
 549                                has_dirs = true;
 550                            } else if let Some(Ok(opened_item)) = opened_item {
 551                                if let Some(row) = path.row {
 552                                    let col = path.column.unwrap_or(0);
 553                                    if let Some(active_editor) = opened_item.downcast::<Editor>() {
 554                                        active_editor
 555                                            .downgrade()
 556                                            .update(&mut cx, |editor, cx| {
 557                                                let snapshot = editor.snapshot(cx).display_snapshot;
 558                                                let point = snapshot.buffer_snapshot.clip_point(
 559                                                    language::Point::new(
 560                                                        row.saturating_sub(1),
 561                                                        col.saturating_sub(1),
 562                                                    ),
 563                                                    Bias::Left,
 564                                                );
 565                                                editor.change_selections(
 566                                                    Some(Autoscroll::center()),
 567                                                    cx,
 568                                                    |s| s.select_ranges([point..point]),
 569                                                );
 570                                            })
 571                                            .log_err();
 572                                    }
 573                                }
 574                            }
 575                        }
 576
 577                        if has_dirs {
 578                            task_workspace.update(&mut cx, |workspace, cx| {
 579                                workspace.project().update(cx, |_, cx| {
 580                                    cx.emit(project::Event::ActivateProjectPanel);
 581                                })
 582                            })?;
 583                        }
 584
 585                        anyhow::Ok(())
 586                    })
 587                    .detach_and_log_err(cx)
 588                }
 589            },
 590            Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
 591            Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
 592            Event::SelectionsChanged => cx.emit(SearchEvent::ActiveMatchChanged),
 593        });
 594    vec![terminal_subscription, terminal_events_subscription]
 595}
 596
 597fn possible_open_paths_metadata(
 598    fs: Arc<dyn Fs>,
 599    row: Option<u32>,
 600    column: Option<u32>,
 601    potential_paths: HashSet<PathBuf>,
 602    cx: &mut ViewContext<TerminalView>,
 603) -> Task<Vec<(PathLikeWithPosition<PathBuf>, Metadata)>> {
 604    cx.background_executor().spawn(async move {
 605        let mut paths_with_metadata = Vec::with_capacity(potential_paths.len());
 606
 607        let mut fetch_metadata_tasks = potential_paths
 608            .into_iter()
 609            .map(|potential_path| async {
 610                let metadata = fs.metadata(&potential_path).await.ok().flatten();
 611                (
 612                    PathLikeWithPosition {
 613                        path_like: potential_path,
 614                        row,
 615                        column,
 616                    },
 617                    metadata,
 618                )
 619            })
 620            .collect::<FuturesUnordered<_>>();
 621
 622        while let Some((path, metadata)) = fetch_metadata_tasks.next().await {
 623            if let Some(metadata) = metadata {
 624                paths_with_metadata.push((path, metadata));
 625            }
 626        }
 627
 628        paths_with_metadata
 629    })
 630}
 631
 632fn possible_open_targets(
 633    fs: Arc<dyn Fs>,
 634    workspace: &WeakView<Workspace>,
 635    cwd: &Option<PathBuf>,
 636    maybe_path: &String,
 637    cx: &mut ViewContext<TerminalView>,
 638) -> Task<Vec<(PathLikeWithPosition<PathBuf>, Metadata)>> {
 639    let path_like = PathLikeWithPosition::parse_str(maybe_path.as_str(), |path_str| {
 640        Ok::<_, std::convert::Infallible>(Path::new(path_str).to_path_buf())
 641    })
 642    .expect("infallible");
 643    let row = path_like.row;
 644    let column = path_like.column;
 645    let maybe_path = path_like.path_like;
 646    let potential_abs_paths = if maybe_path.is_absolute() {
 647        HashSet::from_iter([maybe_path])
 648    } else if maybe_path.starts_with("~") {
 649        if let Some(abs_path) = maybe_path
 650            .strip_prefix("~")
 651            .ok()
 652            .and_then(|maybe_path| Some(dirs::home_dir()?.join(maybe_path)))
 653        {
 654            HashSet::from_iter([abs_path])
 655        } else {
 656            HashSet::default()
 657        }
 658    } else {
 659        // First check cwd and then workspace
 660        let mut potential_cwd_and_workspace_paths = HashSet::default();
 661        if let Some(cwd) = cwd {
 662            potential_cwd_and_workspace_paths.insert(Path::join(cwd, &maybe_path));
 663        }
 664        if let Some(workspace) = workspace.upgrade() {
 665            workspace.update(cx, |workspace, cx| {
 666                for potential_worktree_path in workspace
 667                    .worktrees(cx)
 668                    .map(|worktree| worktree.read(cx).abs_path().join(&maybe_path))
 669                {
 670                    potential_cwd_and_workspace_paths.insert(potential_worktree_path);
 671                }
 672            });
 673        }
 674        potential_cwd_and_workspace_paths
 675    };
 676
 677    possible_open_paths_metadata(fs, row, column, potential_abs_paths, cx)
 678}
 679
 680fn regex_to_literal(regex: &str) -> String {
 681    regex
 682        .chars()
 683        .flat_map(|c| {
 684            if REGEX_SPECIAL_CHARS.contains(&c) {
 685                vec!['\\', c]
 686            } else {
 687                vec![c]
 688            }
 689        })
 690        .collect()
 691}
 692
 693pub fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
 694    let query = query.as_str();
 695    if query == "." {
 696        return None;
 697    }
 698    let searcher = RegexSearch::new(&query);
 699    searcher.ok()
 700}
 701
 702impl TerminalView {
 703    fn key_down(&mut self, event: &KeyDownEvent, cx: &mut ViewContext<Self>) {
 704        self.clear_bell(cx);
 705        self.pause_cursor_blinking(cx);
 706
 707        self.terminal.update(cx, |term, cx| {
 708            term.try_keystroke(
 709                &event.keystroke,
 710                TerminalSettings::get_global(cx).option_as_meta,
 711            )
 712        });
 713    }
 714
 715    fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
 716        self.terminal.read(cx).focus_in();
 717        self.blink_cursors(self.blink_epoch, cx);
 718        cx.notify();
 719    }
 720
 721    fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
 722        self.terminal.update(cx, |terminal, _| {
 723            terminal.focus_out();
 724        });
 725        cx.notify();
 726    }
 727}
 728
 729impl Render for TerminalView {
 730    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 731        let terminal_handle = self.terminal.clone();
 732
 733        let focused = self.focus_handle.is_focused(cx);
 734
 735        div()
 736            .size_full()
 737            .relative()
 738            .track_focus(&self.focus_handle)
 739            .key_context(self.dispatch_context(cx))
 740            .on_action(cx.listener(TerminalView::send_text))
 741            .on_action(cx.listener(TerminalView::send_keystroke))
 742            .on_action(cx.listener(TerminalView::copy))
 743            .on_action(cx.listener(TerminalView::paste))
 744            .on_action(cx.listener(TerminalView::clear))
 745            .on_action(cx.listener(TerminalView::show_character_palette))
 746            .on_action(cx.listener(TerminalView::select_all))
 747            .on_key_down(cx.listener(Self::key_down))
 748            .on_mouse_down(
 749                MouseButton::Right,
 750                cx.listener(|this, event: &MouseDownEvent, cx| {
 751                    if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
 752                        this.deploy_context_menu(event.position, cx);
 753                        cx.notify();
 754                    }
 755                }),
 756            )
 757            .child(
 758                // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
 759                div().size_full().child(TerminalElement::new(
 760                    terminal_handle,
 761                    self.workspace.clone(),
 762                    self.focus_handle.clone(),
 763                    focused,
 764                    self.should_show_cursor(focused, cx),
 765                    self.can_navigate_to_selected_word,
 766                )),
 767            )
 768            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
 769                deferred(
 770                    anchored()
 771                        .position(*position)
 772                        .anchor(gpui::AnchorCorner::TopLeft)
 773                        .child(menu.clone()),
 774                )
 775                .with_priority(1)
 776            }))
 777    }
 778}
 779
 780impl Item for TerminalView {
 781    type Event = ItemEvent;
 782
 783    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 784        Some(self.terminal().read(cx).title(false).into())
 785    }
 786
 787    fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
 788        let terminal = self.terminal().read(cx);
 789        let title = terminal.title(true);
 790
 791        let (icon, icon_color, rerun_btn) = match terminal.task() {
 792            Some(terminal_task) => match &terminal_task.status {
 793                TaskStatus::Unknown => (IconName::ExclamationTriangle, Color::Warning, None),
 794                TaskStatus::Running => (IconName::Play, Color::Disabled, None),
 795                TaskStatus::Completed { success } => {
 796                    let task_id = terminal_task.id.clone();
 797                    let rerun_btn = IconButton::new("rerun-icon", IconName::Rerun)
 798                        .icon_size(IconSize::Small)
 799                        .size(ButtonSize::Compact)
 800                        .icon_color(Color::Default)
 801                        .shape(ui::IconButtonShape::Square)
 802                        .tooltip(|cx| Tooltip::text("Rerun task", cx))
 803                        .on_click(move |_, cx| {
 804                            cx.dispatch_action(Box::new(tasks_ui::Rerun {
 805                                task_id: Some(task_id.clone()),
 806                                ..Default::default()
 807                            }));
 808                        });
 809
 810                    if *success {
 811                        (IconName::Check, Color::Success, Some(rerun_btn))
 812                    } else {
 813                        (IconName::XCircle, Color::Error, Some(rerun_btn))
 814                    }
 815                }
 816            },
 817            None => (IconName::Terminal, Color::Muted, None),
 818        };
 819
 820        h_flex()
 821            .gap_2()
 822            .group("term-tab-icon")
 823            .child(
 824                h_flex()
 825                    .group("term-tab-icon")
 826                    .child(
 827                        div()
 828                            .when(rerun_btn.is_some(), |this| {
 829                                this.hover(|style| style.invisible().w_0())
 830                            })
 831                            .child(Icon::new(icon).color(icon_color)),
 832                    )
 833                    .when_some(rerun_btn, |this, rerun_btn| {
 834                        this.child(
 835                            div()
 836                                .absolute()
 837                                .visible_on_hover("term-tab-icon")
 838                                .child(rerun_btn),
 839                        )
 840                    }),
 841            )
 842            .child(Label::new(title).color(if params.selected {
 843                Color::Default
 844            } else {
 845                Color::Muted
 846            }))
 847            .into_any()
 848    }
 849
 850    fn telemetry_event_text(&self) -> Option<&'static str> {
 851        None
 852    }
 853
 854    fn clone_on_split(
 855        &self,
 856        _workspace_id: WorkspaceId,
 857        _cx: &mut ViewContext<Self>,
 858    ) -> Option<View<Self>> {
 859        //From what I can tell, there's no  way to tell the current working
 860        //Directory of the terminal from outside the shell. There might be
 861        //solutions to this, but they are non-trivial and require more IPC
 862
 863        // Some(TerminalContainer::new(
 864        //     Err(anyhow::anyhow!("failed to instantiate terminal")),
 865        //     workspace_id,
 866        //     cx,
 867        // ))
 868
 869        // TODO
 870        None
 871    }
 872
 873    fn is_dirty(&self, cx: &gpui::AppContext) -> bool {
 874        match self.terminal.read(cx).task() {
 875            Some(task) => task.status == TaskStatus::Running,
 876            None => self.has_bell(),
 877        }
 878    }
 879
 880    fn has_conflict(&self, _cx: &AppContext) -> bool {
 881        false
 882    }
 883
 884    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 885        Some(Box::new(handle.clone()))
 886    }
 887
 888    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 889        if self.show_title {
 890            ToolbarItemLocation::PrimaryLeft
 891        } else {
 892            ToolbarItemLocation::Hidden
 893        }
 894    }
 895
 896    fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 897        Some(vec![BreadcrumbText {
 898            text: self.terminal().read(cx).breadcrumb_text.clone(),
 899            highlights: None,
 900            font: None,
 901        }])
 902    }
 903
 904    fn serialized_item_kind() -> Option<&'static str> {
 905        Some("Terminal")
 906    }
 907
 908    fn deserialize(
 909        project: Model<Project>,
 910        workspace: WeakView<Workspace>,
 911        workspace_id: workspace::WorkspaceId,
 912        item_id: workspace::ItemId,
 913        cx: &mut ViewContext<Pane>,
 914    ) -> Task<anyhow::Result<View<Self>>> {
 915        let window = cx.window_handle();
 916        cx.spawn(|pane, mut cx| async move {
 917            let cwd = cx
 918                .update(|cx| {
 919                    let from_db = TERMINAL_DB
 920                        .get_working_directory(item_id, workspace_id)
 921                        .log_err()
 922                        .flatten();
 923                    if from_db
 924                        .as_ref()
 925                        .is_some_and(|from_db| !from_db.as_os_str().is_empty())
 926                    {
 927                        project
 928                            .read(cx)
 929                            .terminal_work_dir_for(from_db.as_deref(), cx)
 930                    } else {
 931                        let strategy = TerminalSettings::get_global(cx).working_directory.clone();
 932                        workspace.upgrade().and_then(|workspace| {
 933                            get_working_directory(workspace.read(cx), cx, strategy)
 934                        })
 935                    }
 936                })
 937                .ok()
 938                .flatten();
 939
 940            let terminal = project.update(&mut cx, |project, cx| {
 941                project.create_terminal(cwd, None, window, cx)
 942            })??;
 943            pane.update(&mut cx, |_, cx| {
 944                cx.new_view(|cx| TerminalView::new(terminal, workspace, workspace_id, cx))
 945            })
 946        })
 947    }
 948
 949    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 950        if self.terminal().read(cx).task().is_none() {
 951            cx.background_executor()
 952                .spawn(TERMINAL_DB.update_workspace_id(
 953                    workspace.database_id(),
 954                    self.workspace_id,
 955                    cx.entity_id().as_u64(),
 956                ))
 957                .detach();
 958            self.workspace_id = workspace.database_id();
 959        }
 960    }
 961
 962    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
 963        f(*event)
 964    }
 965}
 966
 967impl SearchableItem for TerminalView {
 968    type Match = RangeInclusive<Point>;
 969
 970    fn supported_options() -> SearchOptions {
 971        SearchOptions {
 972            case: false,
 973            word: false,
 974            regex: true,
 975            replacement: false,
 976        }
 977    }
 978
 979    /// Clear stored matches
 980    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 981        self.terminal().update(cx, |term, _| term.matches.clear())
 982    }
 983
 984    /// Store matches returned from find_matches somewhere for rendering
 985    fn update_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
 986        self.terminal()
 987            .update(cx, |term, _| term.matches = matches.to_vec())
 988    }
 989
 990    /// Returns the selection content to pre-load into this search
 991    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
 992        self.terminal()
 993            .read(cx)
 994            .last_content
 995            .selection_text
 996            .clone()
 997            .unwrap_or_default()
 998    }
 999
1000    /// Focus match at given index into the Vec of matches
1001    fn activate_match(&mut self, index: usize, _: &[Self::Match], cx: &mut ViewContext<Self>) {
1002        self.terminal()
1003            .update(cx, |term, _| term.activate_match(index));
1004        cx.notify();
1005    }
1006
1007    /// Add selections for all matches given.
1008    fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1009        self.terminal()
1010            .update(cx, |term, _| term.select_matches(matches));
1011        cx.notify();
1012    }
1013
1014    /// Get all of the matches for this query, should be done on the background
1015    fn find_matches(
1016        &mut self,
1017        query: Arc<SearchQuery>,
1018        cx: &mut ViewContext<Self>,
1019    ) -> Task<Vec<Self::Match>> {
1020        let searcher = match &*query {
1021            SearchQuery::Text { .. } => regex_search_for_query(
1022                &(SearchQuery::text(
1023                    regex_to_literal(&query.as_str()),
1024                    query.whole_word(),
1025                    query.case_sensitive(),
1026                    query.include_ignored(),
1027                    query.files_to_include().to_vec(),
1028                    query.files_to_exclude().to_vec(),
1029                )
1030                .unwrap()),
1031            ),
1032            SearchQuery::Regex { .. } => regex_search_for_query(&query),
1033        };
1034
1035        if let Some(s) = searcher {
1036            self.terminal()
1037                .update(cx, |term, cx| term.find_matches(s, cx))
1038        } else {
1039            Task::ready(vec![])
1040        }
1041    }
1042
1043    /// Reports back to the search toolbar what the active match should be (the selection)
1044    fn active_match_index(
1045        &mut self,
1046        matches: &[Self::Match],
1047        cx: &mut ViewContext<Self>,
1048    ) -> Option<usize> {
1049        // Selection head might have a value if there's a selection that isn't
1050        // associated with a match. Therefore, if there are no matches, we should
1051        // report None, no matter the state of the terminal
1052        let res = if matches.len() > 0 {
1053            if let Some(selection_head) = self.terminal().read(cx).selection_head {
1054                // If selection head is contained in a match. Return that match
1055                if let Some(ix) = matches
1056                    .iter()
1057                    .enumerate()
1058                    .find(|(_, search_match)| {
1059                        search_match.contains(&selection_head)
1060                            || search_match.start() > &selection_head
1061                    })
1062                    .map(|(ix, _)| ix)
1063                {
1064                    Some(ix)
1065                } else {
1066                    // If no selection after selection head, return the last match
1067                    Some(matches.len().saturating_sub(1))
1068                }
1069            } else {
1070                // Matches found but no active selection, return the first last one (closest to cursor)
1071                Some(matches.len().saturating_sub(1))
1072            }
1073        } else {
1074            None
1075        };
1076
1077        res
1078    }
1079    fn replace(&mut self, _: &Self::Match, _: &SearchQuery, _: &mut ViewContext<Self>) {
1080        // Replacement is not supported in terminal view, so this is a no-op.
1081    }
1082}
1083
1084///Gets the working directory for the given workspace, respecting the user's settings.
1085pub fn get_working_directory(
1086    workspace: &Workspace,
1087    cx: &AppContext,
1088    strategy: WorkingDirectory,
1089) -> Option<TerminalWorkDir> {
1090    if workspace.project().read(cx).is_local() {
1091        let res = match strategy {
1092            WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
1093                .or_else(|| first_project_directory(workspace, cx)),
1094            WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
1095            WorkingDirectory::AlwaysHome => None,
1096            WorkingDirectory::Always { directory } => {
1097                shellexpand::full(&directory) //TODO handle this better
1098                    .ok()
1099                    .map(|dir| Path::new(&dir.to_string()).to_path_buf())
1100                    .filter(|dir| dir.is_dir())
1101            }
1102        };
1103        res.or_else(home_dir).map(|cwd| TerminalWorkDir::Local(cwd))
1104    } else {
1105        workspace.project().read(cx).terminal_work_dir_for(None, cx)
1106    }
1107}
1108
1109///Gets the first project's home directory, or the home directory
1110fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1111    workspace
1112        .worktrees(cx)
1113        .next()
1114        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
1115        .and_then(get_path_from_wt)
1116}
1117
1118///Gets the intuitively correct working directory from the given workspace
1119///If there is an active entry for this project, returns that entry's worktree root.
1120///If there's no active entry but there is a worktree, returns that worktrees root.
1121///If either of these roots are files, or if there are any other query failures,
1122///  returns the user's home directory
1123fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
1124    let project = workspace.project().read(cx);
1125
1126    project
1127        .active_entry()
1128        .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
1129        .or_else(|| workspace.worktrees(cx).next())
1130        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
1131        .and_then(get_path_from_wt)
1132}
1133
1134fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
1135    wt.root_entry()
1136        .filter(|re| re.is_dir())
1137        .map(|_| wt.abs_path().to_path_buf())
1138}
1139
1140#[cfg(test)]
1141mod tests {
1142    use super::*;
1143    use gpui::TestAppContext;
1144    use project::{Entry, Project, ProjectPath, Worktree};
1145    use std::path::Path;
1146    use workspace::AppState;
1147
1148    // Working directory calculation tests
1149
1150    // No Worktrees in project -> home_dir()
1151    #[gpui::test]
1152    async fn no_worktree(cx: &mut TestAppContext) {
1153        let (project, workspace) = init_test(cx).await;
1154        cx.read(|cx| {
1155            let workspace = workspace.read(cx);
1156            let active_entry = project.read(cx).active_entry();
1157
1158            //Make sure environment is as expected
1159            assert!(active_entry.is_none());
1160            assert!(workspace.worktrees(cx).next().is_none());
1161
1162            let res = current_project_directory(workspace, cx);
1163            assert_eq!(res, None);
1164            let res = first_project_directory(workspace, cx);
1165            assert_eq!(res, None);
1166        });
1167    }
1168
1169    // No active entry, but a worktree, worktree is a file -> home_dir()
1170    #[gpui::test]
1171    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
1172        let (project, workspace) = init_test(cx).await;
1173
1174        create_file_wt(project.clone(), "/root.txt", cx).await;
1175        cx.read(|cx| {
1176            let workspace = workspace.read(cx);
1177            let active_entry = project.read(cx).active_entry();
1178
1179            //Make sure environment is as expected
1180            assert!(active_entry.is_none());
1181            assert!(workspace.worktrees(cx).next().is_some());
1182
1183            let res = current_project_directory(workspace, cx);
1184            assert_eq!(res, None);
1185            let res = first_project_directory(workspace, cx);
1186            assert_eq!(res, None);
1187        });
1188    }
1189
1190    // No active entry, but a worktree, worktree is a folder -> worktree_folder
1191    #[gpui::test]
1192    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1193        let (project, workspace) = init_test(cx).await;
1194
1195        let (_wt, _entry) = create_folder_wt(project.clone(), "/root/", cx).await;
1196        cx.update(|cx| {
1197            let workspace = workspace.read(cx);
1198            let active_entry = project.read(cx).active_entry();
1199
1200            assert!(active_entry.is_none());
1201            assert!(workspace.worktrees(cx).next().is_some());
1202
1203            let res = current_project_directory(workspace, cx);
1204            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1205            let res = first_project_directory(workspace, cx);
1206            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
1207        });
1208    }
1209
1210    // Active entry with a work tree, worktree is a file -> home_dir()
1211    #[gpui::test]
1212    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
1213        let (project, workspace) = init_test(cx).await;
1214
1215        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1216        let (wt2, entry2) = create_file_wt(project.clone(), "/root2.txt", cx).await;
1217        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1218
1219        cx.update(|cx| {
1220            let workspace = workspace.read(cx);
1221            let active_entry = project.read(cx).active_entry();
1222
1223            assert!(active_entry.is_some());
1224
1225            let res = current_project_directory(workspace, cx);
1226            assert_eq!(res, None);
1227            let res = first_project_directory(workspace, cx);
1228            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1229        });
1230    }
1231
1232    // Active entry, with a worktree, worktree is a folder -> worktree_folder
1233    #[gpui::test]
1234    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
1235        let (project, workspace) = init_test(cx).await;
1236
1237        let (_wt, _entry) = create_folder_wt(project.clone(), "/root1/", cx).await;
1238        let (wt2, entry2) = create_folder_wt(project.clone(), "/root2/", cx).await;
1239        insert_active_entry_for(wt2, entry2, project.clone(), cx);
1240
1241        cx.update(|cx| {
1242            let workspace = workspace.read(cx);
1243            let active_entry = project.read(cx).active_entry();
1244
1245            assert!(active_entry.is_some());
1246
1247            let res = current_project_directory(workspace, cx);
1248            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
1249            let res = first_project_directory(workspace, cx);
1250            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
1251        });
1252    }
1253
1254    /// Creates a worktree with 1 file: /root.txt
1255    pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
1256        let params = cx.update(AppState::test);
1257        cx.update(|cx| {
1258            theme::init(theme::LoadThemes::JustBase, cx);
1259            Project::init_settings(cx);
1260            language::init(cx);
1261        });
1262
1263        let project = Project::test(params.fs.clone(), [], cx).await;
1264        let workspace = cx
1265            .add_window(|cx| Workspace::test_new(project.clone(), cx))
1266            .root_view(cx)
1267            .unwrap();
1268
1269        (project, workspace)
1270    }
1271
1272    /// Creates a worktree with 1 folder: /root{suffix}/
1273    async fn create_folder_wt(
1274        project: Model<Project>,
1275        path: impl AsRef<Path>,
1276        cx: &mut TestAppContext,
1277    ) -> (Model<Worktree>, Entry) {
1278        create_wt(project, true, path, cx).await
1279    }
1280
1281    /// Creates a worktree with 1 file: /root{suffix}.txt
1282    async fn create_file_wt(
1283        project: Model<Project>,
1284        path: impl AsRef<Path>,
1285        cx: &mut TestAppContext,
1286    ) -> (Model<Worktree>, Entry) {
1287        create_wt(project, false, path, cx).await
1288    }
1289
1290    async fn create_wt(
1291        project: Model<Project>,
1292        is_dir: bool,
1293        path: impl AsRef<Path>,
1294        cx: &mut TestAppContext,
1295    ) -> (Model<Worktree>, Entry) {
1296        let (wt, _) = project
1297            .update(cx, |project, cx| {
1298                project.find_or_create_local_worktree(path, true, cx)
1299            })
1300            .await
1301            .unwrap();
1302
1303        let entry = cx
1304            .update(|cx| {
1305                wt.update(cx, |wt, cx| {
1306                    wt.as_local()
1307                        .unwrap()
1308                        .create_entry(Path::new(""), is_dir, cx)
1309                })
1310            })
1311            .await
1312            .unwrap()
1313            .unwrap();
1314
1315        (wt, entry)
1316    }
1317
1318    pub fn insert_active_entry_for(
1319        wt: Model<Worktree>,
1320        entry: Entry,
1321        project: Model<Project>,
1322        cx: &mut TestAppContext,
1323    ) {
1324        cx.update(|cx| {
1325            let p = ProjectPath {
1326                worktree_id: wt.read(cx).id(),
1327                path: entry.path,
1328            };
1329            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1330        });
1331    }
1332
1333    #[test]
1334    fn escapes_only_special_characters() {
1335        assert_eq!(regex_to_literal(r"test(\w)"), r"test\(\\w\)".to_string());
1336    }
1337
1338    #[test]
1339    fn empty_string_stays_empty() {
1340        assert_eq!(regex_to_literal(""), "".to_string());
1341    }
1342}