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: Option<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: Option<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, _event, 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                        if let Some(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
 475            Event::NewNavigationTarget(maybe_navigation_target) => {
 476                this.can_navigate_to_selected_word = match maybe_navigation_target {
 477                    Some(MaybeNavigationTarget::Url(_)) => true,
 478                    Some(MaybeNavigationTarget::PathLike(path_like_target)) => {
 479                        if let Ok(fs) = workspace.update(cx, |workspace, cx| {
 480                            workspace.project().read(cx).fs().clone()
 481                        }) {
 482                            let valid_files_to_open_task = possible_open_targets(
 483                                fs,
 484                                &workspace,
 485                                &path_like_target.terminal_dir,
 486                                &path_like_target.maybe_path,
 487                                cx,
 488                            );
 489                            smol::block_on(valid_files_to_open_task).len() > 0
 490                        } else {
 491                            false
 492                        }
 493                    }
 494                    None => false,
 495                }
 496            }
 497
 498            Event::Open(maybe_navigation_target) => match maybe_navigation_target {
 499                MaybeNavigationTarget::Url(url) => cx.open_url(url),
 500
 501                MaybeNavigationTarget::PathLike(path_like_target) => {
 502                    if !this.can_navigate_to_selected_word {
 503                        return;
 504                    }
 505                    let task_workspace = workspace.clone();
 506                    let Some(fs) = workspace
 507                        .update(cx, |workspace, cx| {
 508                            workspace.project().read(cx).fs().clone()
 509                        })
 510                        .ok()
 511                    else {
 512                        return;
 513                    };
 514
 515                    let path_like_target = path_like_target.clone();
 516                    cx.spawn(|terminal_view, mut cx| async move {
 517                        let valid_files_to_open = terminal_view
 518                            .update(&mut cx, |_, cx| {
 519                                possible_open_targets(
 520                                    fs,
 521                                    &task_workspace,
 522                                    &path_like_target.terminal_dir,
 523                                    &path_like_target.maybe_path,
 524                                    cx,
 525                                )
 526                            })?
 527                            .await;
 528                        let paths_to_open = valid_files_to_open
 529                            .iter()
 530                            .map(|(p, _)| p.path_like.clone())
 531                            .collect();
 532                        let opened_items = task_workspace
 533                            .update(&mut cx, |workspace, cx| {
 534                                workspace.open_paths(
 535                                    paths_to_open,
 536                                    OpenVisible::OnlyDirectories,
 537                                    None,
 538                                    cx,
 539                                )
 540                            })
 541                            .context("workspace update")?
 542                            .await;
 543
 544                        let mut has_dirs = false;
 545                        for ((path, metadata), opened_item) in valid_files_to_open
 546                            .into_iter()
 547                            .zip(opened_items.into_iter())
 548                        {
 549                            if metadata.is_dir {
 550                                has_dirs = true;
 551                            } else if let Some(Ok(opened_item)) = opened_item {
 552                                if let Some(row) = path.row {
 553                                    let col = path.column.unwrap_or(0);
 554                                    if let Some(active_editor) = opened_item.downcast::<Editor>() {
 555                                        active_editor
 556                                            .downgrade()
 557                                            .update(&mut cx, |editor, cx| {
 558                                                let snapshot = editor.snapshot(cx).display_snapshot;
 559                                                let point = snapshot.buffer_snapshot.clip_point(
 560                                                    language::Point::new(
 561                                                        row.saturating_sub(1),
 562                                                        col.saturating_sub(1),
 563                                                    ),
 564                                                    Bias::Left,
 565                                                );
 566                                                editor.change_selections(
 567                                                    Some(Autoscroll::center()),
 568                                                    cx,
 569                                                    |s| s.select_ranges([point..point]),
 570                                                );
 571                                            })
 572                                            .log_err();
 573                                    }
 574                                }
 575                            }
 576                        }
 577
 578                        if has_dirs {
 579                            task_workspace.update(&mut cx, |workspace, cx| {
 580                                workspace.project().update(cx, |_, cx| {
 581                                    cx.emit(project::Event::ActivateProjectPanel);
 582                                })
 583                            })?;
 584                        }
 585
 586                        anyhow::Ok(())
 587                    })
 588                    .detach_and_log_err(cx)
 589                }
 590            },
 591            Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
 592            Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
 593            Event::SelectionsChanged => cx.emit(SearchEvent::ActiveMatchChanged),
 594        });
 595    vec![terminal_subscription, terminal_events_subscription]
 596}
 597
 598fn possible_open_paths_metadata(
 599    fs: Arc<dyn Fs>,
 600    row: Option<u32>,
 601    column: Option<u32>,
 602    potential_paths: HashSet<PathBuf>,
 603    cx: &mut ViewContext<TerminalView>,
 604) -> Task<Vec<(PathLikeWithPosition<PathBuf>, Metadata)>> {
 605    cx.background_executor().spawn(async move {
 606        let mut paths_with_metadata = Vec::with_capacity(potential_paths.len());
 607
 608        let mut fetch_metadata_tasks = potential_paths
 609            .into_iter()
 610            .map(|potential_path| async {
 611                let metadata = fs.metadata(&potential_path).await.ok().flatten();
 612                (
 613                    PathLikeWithPosition {
 614                        path_like: potential_path,
 615                        row,
 616                        column,
 617                    },
 618                    metadata,
 619                )
 620            })
 621            .collect::<FuturesUnordered<_>>();
 622
 623        while let Some((path, metadata)) = fetch_metadata_tasks.next().await {
 624            if let Some(metadata) = metadata {
 625                paths_with_metadata.push((path, metadata));
 626            }
 627        }
 628
 629        paths_with_metadata
 630    })
 631}
 632
 633fn possible_open_targets(
 634    fs: Arc<dyn Fs>,
 635    workspace: &WeakView<Workspace>,
 636    cwd: &Option<PathBuf>,
 637    maybe_path: &String,
 638    cx: &mut ViewContext<TerminalView>,
 639) -> Task<Vec<(PathLikeWithPosition<PathBuf>, Metadata)>> {
 640    let path_like = PathLikeWithPosition::parse_str(maybe_path.as_str(), |path_str| {
 641        Ok::<_, std::convert::Infallible>(Path::new(path_str).to_path_buf())
 642    })
 643    .expect("infallible");
 644    let row = path_like.row;
 645    let column = path_like.column;
 646    let maybe_path = path_like.path_like;
 647    let potential_abs_paths = if maybe_path.is_absolute() {
 648        HashSet::from_iter([maybe_path])
 649    } else if maybe_path.starts_with("~") {
 650        if let Some(abs_path) = maybe_path
 651            .strip_prefix("~")
 652            .ok()
 653            .and_then(|maybe_path| Some(dirs::home_dir()?.join(maybe_path)))
 654        {
 655            HashSet::from_iter([abs_path])
 656        } else {
 657            HashSet::default()
 658        }
 659    } else {
 660        // First check cwd and then workspace
 661        let mut potential_cwd_and_workspace_paths = HashSet::default();
 662        if let Some(cwd) = cwd {
 663            potential_cwd_and_workspace_paths.insert(Path::join(cwd, &maybe_path));
 664        }
 665        if let Some(workspace) = workspace.upgrade() {
 666            workspace.update(cx, |workspace, cx| {
 667                for potential_worktree_path in workspace
 668                    .worktrees(cx)
 669                    .map(|worktree| worktree.read(cx).abs_path().join(&maybe_path))
 670                {
 671                    potential_cwd_and_workspace_paths.insert(potential_worktree_path);
 672                }
 673            });
 674        }
 675        potential_cwd_and_workspace_paths
 676    };
 677
 678    possible_open_paths_metadata(fs, row, column, potential_abs_paths, cx)
 679}
 680
 681fn regex_to_literal(regex: &str) -> String {
 682    regex
 683        .chars()
 684        .flat_map(|c| {
 685            if REGEX_SPECIAL_CHARS.contains(&c) {
 686                vec!['\\', c]
 687            } else {
 688                vec![c]
 689            }
 690        })
 691        .collect()
 692}
 693
 694pub fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<RegexSearch> {
 695    let query = query.as_str();
 696    if query == "." {
 697        return None;
 698    }
 699    let searcher = RegexSearch::new(&query);
 700    searcher.ok()
 701}
 702
 703impl TerminalView {
 704    fn key_down(&mut self, event: &KeyDownEvent, cx: &mut ViewContext<Self>) {
 705        self.clear_bell(cx);
 706        self.pause_cursor_blinking(cx);
 707
 708        self.terminal.update(cx, |term, cx| {
 709            term.try_keystroke(
 710                &event.keystroke,
 711                TerminalSettings::get_global(cx).option_as_meta,
 712            )
 713        });
 714    }
 715
 716    fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
 717        self.terminal.read(cx).focus_in();
 718        self.blink_cursors(self.blink_epoch, cx);
 719        cx.notify();
 720    }
 721
 722    fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
 723        self.terminal.update(cx, |terminal, _| {
 724            terminal.focus_out();
 725        });
 726        cx.notify();
 727    }
 728}
 729
 730impl Render for TerminalView {
 731    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 732        let terminal_handle = self.terminal.clone();
 733
 734        let focused = self.focus_handle.is_focused(cx);
 735
 736        div()
 737            .size_full()
 738            .relative()
 739            .track_focus(&self.focus_handle)
 740            .key_context(self.dispatch_context(cx))
 741            .on_action(cx.listener(TerminalView::send_text))
 742            .on_action(cx.listener(TerminalView::send_keystroke))
 743            .on_action(cx.listener(TerminalView::copy))
 744            .on_action(cx.listener(TerminalView::paste))
 745            .on_action(cx.listener(TerminalView::clear))
 746            .on_action(cx.listener(TerminalView::show_character_palette))
 747            .on_action(cx.listener(TerminalView::select_all))
 748            .on_key_down(cx.listener(Self::key_down))
 749            .on_mouse_down(
 750                MouseButton::Right,
 751                cx.listener(|this, event: &MouseDownEvent, cx| {
 752                    if !this.terminal.read(cx).mouse_mode(event.modifiers.shift) {
 753                        this.deploy_context_menu(event.position, cx);
 754                        cx.notify();
 755                    }
 756                }),
 757            )
 758            .child(
 759                // TODO: Oddly this wrapper div is needed for TerminalElement to not steal events from the context menu
 760                div().size_full().child(TerminalElement::new(
 761                    terminal_handle,
 762                    self.workspace.clone(),
 763                    self.focus_handle.clone(),
 764                    focused,
 765                    self.should_show_cursor(focused, cx),
 766                    self.can_navigate_to_selected_word,
 767                )),
 768            )
 769            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
 770                deferred(
 771                    anchored()
 772                        .position(*position)
 773                        .anchor(gpui::AnchorCorner::TopLeft)
 774                        .child(menu.clone()),
 775                )
 776                .with_priority(1)
 777            }))
 778    }
 779}
 780
 781impl Item for TerminalView {
 782    type Event = ItemEvent;
 783
 784    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 785        Some(self.terminal().read(cx).title(false).into())
 786    }
 787
 788    fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
 789        let terminal = self.terminal().read(cx);
 790        let title = terminal.title(true);
 791
 792        let (icon, icon_color, rerun_btn) = match terminal.task() {
 793            Some(terminal_task) => match &terminal_task.status {
 794                TaskStatus::Unknown => (IconName::ExclamationTriangle, Color::Warning, None),
 795                TaskStatus::Running => (IconName::Play, Color::Disabled, None),
 796                TaskStatus::Completed { success } => {
 797                    let task_id = terminal_task.id.clone();
 798                    let rerun_btn = IconButton::new("rerun-icon", IconName::Rerun)
 799                        .icon_size(IconSize::Small)
 800                        .size(ButtonSize::Compact)
 801                        .icon_color(Color::Default)
 802                        .shape(ui::IconButtonShape::Square)
 803                        .tooltip(|cx| Tooltip::text("Rerun task", cx))
 804                        .on_click(move |_, cx| {
 805                            cx.dispatch_action(Box::new(tasks_ui::Rerun {
 806                                task_id: Some(task_id.clone()),
 807                                ..Default::default()
 808                            }));
 809                        });
 810
 811                    if *success {
 812                        (IconName::Check, Color::Success, Some(rerun_btn))
 813                    } else {
 814                        (IconName::XCircle, Color::Error, Some(rerun_btn))
 815                    }
 816                }
 817            },
 818            None => (IconName::Terminal, Color::Muted, None),
 819        };
 820
 821        h_flex()
 822            .gap_2()
 823            .group("term-tab-icon")
 824            .child(
 825                h_flex()
 826                    .group("term-tab-icon")
 827                    .child(
 828                        div()
 829                            .when(rerun_btn.is_some(), |this| {
 830                                this.hover(|style| style.invisible().w_0())
 831                            })
 832                            .child(Icon::new(icon).color(icon_color)),
 833                    )
 834                    .when_some(rerun_btn, |this, rerun_btn| {
 835                        this.child(
 836                            div()
 837                                .absolute()
 838                                .visible_on_hover("term-tab-icon")
 839                                .child(rerun_btn),
 840                        )
 841                    }),
 842            )
 843            .child(Label::new(title).color(if params.selected {
 844                Color::Default
 845            } else {
 846                Color::Muted
 847            }))
 848            .into_any()
 849    }
 850
 851    fn telemetry_event_text(&self) -> Option<&'static str> {
 852        None
 853    }
 854
 855    fn clone_on_split(
 856        &self,
 857        _workspace_id: Option<WorkspaceId>,
 858        _cx: &mut ViewContext<Self>,
 859    ) -> Option<View<Self>> {
 860        //From what I can tell, there's no  way to tell the current working
 861        //Directory of the terminal from outside the shell. There might be
 862        //solutions to this, but they are non-trivial and require more IPC
 863
 864        // Some(TerminalContainer::new(
 865        //     Err(anyhow::anyhow!("failed to instantiate terminal")),
 866        //     workspace_id,
 867        //     cx,
 868        // ))
 869
 870        // TODO
 871        None
 872    }
 873
 874    fn is_dirty(&self, cx: &gpui::AppContext) -> bool {
 875        match self.terminal.read(cx).task() {
 876            Some(task) => task.status == TaskStatus::Running,
 877            None => self.has_bell(),
 878        }
 879    }
 880
 881    fn has_conflict(&self, _cx: &AppContext) -> bool {
 882        false
 883    }
 884
 885    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 886        Some(Box::new(handle.clone()))
 887    }
 888
 889    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 890        if self.show_title {
 891            ToolbarItemLocation::PrimaryLeft
 892        } else {
 893            ToolbarItemLocation::Hidden
 894        }
 895    }
 896
 897    fn breadcrumbs(&self, _: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 898        Some(vec![BreadcrumbText {
 899            text: self.terminal().read(cx).breadcrumb_text.clone(),
 900            highlights: None,
 901            font: None,
 902        }])
 903    }
 904
 905    fn serialized_item_kind() -> Option<&'static str> {
 906        Some("Terminal")
 907    }
 908
 909    fn deserialize(
 910        project: Model<Project>,
 911        workspace: WeakView<Workspace>,
 912        workspace_id: workspace::WorkspaceId,
 913        item_id: workspace::ItemId,
 914        cx: &mut ViewContext<Pane>,
 915    ) -> Task<anyhow::Result<View<Self>>> {
 916        let window = cx.window_handle();
 917        cx.spawn(|pane, mut cx| async move {
 918            let cwd = cx
 919                .update(|cx| {
 920                    let from_db = TERMINAL_DB
 921                        .get_working_directory(item_id, workspace_id)
 922                        .log_err()
 923                        .flatten();
 924                    if from_db
 925                        .as_ref()
 926                        .is_some_and(|from_db| !from_db.as_os_str().is_empty())
 927                    {
 928                        project
 929                            .read(cx)
 930                            .terminal_work_dir_for(from_db.as_deref(), cx)
 931                    } else {
 932                        let strategy = TerminalSettings::get_global(cx).working_directory.clone();
 933                        workspace.upgrade().and_then(|workspace| {
 934                            get_working_directory(workspace.read(cx), cx, strategy)
 935                        })
 936                    }
 937                })
 938                .ok()
 939                .flatten();
 940
 941            let terminal = project.update(&mut cx, |project, cx| {
 942                project.create_terminal(cwd, None, window, cx)
 943            })??;
 944            pane.update(&mut cx, |_, cx| {
 945                cx.new_view(|cx| TerminalView::new(terminal, workspace, Some(workspace_id), cx))
 946            })
 947        })
 948    }
 949
 950    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 951        if self.terminal().read(cx).task().is_none() {
 952            if let Some((new_id, old_id)) = workspace.database_id().zip(self.workspace_id) {
 953                cx.background_executor()
 954                    .spawn(TERMINAL_DB.update_workspace_id(new_id, old_id, cx.entity_id().as_u64()))
 955                    .detach();
 956            }
 957            self.workspace_id = workspace.database_id();
 958        }
 959    }
 960
 961    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
 962        f(*event)
 963    }
 964}
 965
 966impl SearchableItem for TerminalView {
 967    type Match = RangeInclusive<Point>;
 968
 969    fn supported_options() -> SearchOptions {
 970        SearchOptions {
 971            case: false,
 972            word: false,
 973            regex: true,
 974            replacement: false,
 975            selection: 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().clone(),
1028                    query.files_to_exclude().clone(),
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| wt.update(cx, |wt, cx| wt.create_entry(Path::new(""), is_dir, cx)))
1305            .await
1306            .unwrap()
1307            .to_included()
1308            .unwrap();
1309
1310        (wt, entry)
1311    }
1312
1313    pub fn insert_active_entry_for(
1314        wt: Model<Worktree>,
1315        entry: Entry,
1316        project: Model<Project>,
1317        cx: &mut TestAppContext,
1318    ) {
1319        cx.update(|cx| {
1320            let p = ProjectPath {
1321                worktree_id: wt.read(cx).id(),
1322                path: entry.path,
1323            };
1324            project.update(cx, |project, cx| project.set_active_path(Some(p), cx));
1325        });
1326    }
1327
1328    #[test]
1329    fn escapes_only_special_characters() {
1330        assert_eq!(regex_to_literal(r"test(\w)"), r"test\(\\w\)".to_string());
1331    }
1332
1333    #[test]
1334    fn empty_string_stays_empty() {
1335        assert_eq!(regex_to_literal(""), "".to_string());
1336    }
1337}