use crate::prompt_update::{ POST_EXECUTION_MARKER_PREFIX, POST_EXECUTION_MARKER_SUFFIX, PRE_EXECUTION_MARKER, RESET_APPLICATION_MODE, VSCODE_COMMANDLINE_MARKER_PREFIX, VSCODE_COMMANDLINE_MARKER_SUFFIX, VSCODE_CWD_PROPERTY_MARKER_PREFIX, VSCODE_CWD_PROPERTY_MARKER_SUFFIX, VSCODE_POST_EXECUTION_MARKER_PREFIX, VSCODE_POST_EXECUTION_MARKER_SUFFIX, VSCODE_PRE_EXECUTION_MARKER, }; use crate::{ NuHighlighter, NuValidator, NushellPrompt, completions::{NarrowingCache, NuCompleter, flush_completion_warnings}, hints::ExternalHinter, prompt_update, reedline_config::{KeybindingsMode, add_menus, create_keybindings}, status_line::{NuStatusLine, StatusStyles}, syntax_highlight::NoOpHighlighter, util::{eval_source, evaluate_source, set_last_exit_code_after_source}, }; use crossterm::cursor::SetCursorStyle; use log::{error, trace, warn}; use miette::{ErrReport, IntoDiagnostic, Result}; use nu_cmd_base::util::get_editor; use nu_color_config::StyleComputer; use nu_engine::env_to_strings; use nu_engine::exit::cleanup_exit; use nu_parser::{lex, trim_quotes_str}; use nu_path::AbsolutePathBuf; use nu_protocol::shell_error::io::IoError; use nu_protocol::{BannerKind, ShellIntegrationConfig, ShellWarning, shell_error}; use nu_protocol::{ Config, HistoryConfig, HistoryFileFormat, PipelineData, ShellError, Span, Spanned, Value, config::NuCursorShape, engine::{EngineState, JobOutput, Stack}, report_shell_error, report_shell_warning, }; use nu_utils::time::Instant; use nu_utils::{ filesystem::{PermissionResult, have_permission}, perf, stderr_write_all_and_flush, stdout_write_all_and_flush, }; use percent_encoding::{CONTROLS, utf8_percent_encode}; use reedline::Helix; #[cfg(feature = "sqlite")] use reedline::SqliteBackedHistory; use reedline::{ AutoPairs, CursorConfig, CwdAwareHinter, DefaultCompleter, EditCommand, Emacs, ExternalOutput, FileBackedHistory, HistorySessionId, MouseClickMode, Osc133ClickEventsMarkers, Osc633Markers, Reedline, SemanticPromptMarkers, Vi, }; use std::ffi::OsStr; use std::sync::atomic::Ordering; use std::{ collections::HashMap, env::temp_dir, io::{self, IsTerminal, Write}, panic::{AssertUnwindSafe, catch_unwind}, path::{Path, PathBuf}, sync::Arc, time::Duration, }; use sysinfo::System; use url::Url; fn semantic_markers_from_config( config: &Config, term_program_is_vscode: bool, ) -> Option> { if config.shell_integration.osc633 && term_program_is_vscode { Some(Osc633Markers::boxed()) } else if config.shell_integration.osc133 { Some(Osc133ClickEventsMarkers::boxed()) } else { None } } type RepaintCallback = Arc; /// Feeds the output background jobs queue in [`JobOutput`] to the line editor, which prints it /// above the prompt. struct JobOutputPrinter(Arc); impl ExternalOutput for JobOutputPrinter { fn drain(&mut self) -> io::Result> { Ok(self.0.drain().into_iter().collect()) } /// Lets the line editor block on input, instead of waking every poll interval, once no job /// thread is left to write. fn needs_polling(&self) -> bool { self.0.needs_polling() } } /// Stop holding background job output and write what the line editor did not print to stderr, /// where the line editor would have printed it. fn write_released_job_output(engine_state: &EngineState) { engine_state.job_output.release(|leftover| { let _ = stderr_write_all_and_flush(leftover); }); } /// Prepares the engine's prompt state and constructs the interactive view. /// /// Installs a live repainter only while a background job thread is running, since only a job /// thread can push a prompt while the line editor waits for input. Holding a repaint handle makes /// reedline poll for input instead of blocking, so the last job thread to end drops the repainter /// again (see `job spawn`). fn build_interactive_prompt( engine_state: &EngineState, line_editor: &mut Reedline, ) -> NushellPrompt { // Recover from a poisoned jobs lock rather than silently disabling async // prompts: a background job holding the lock across a panic must not leave // `commandline set-prompt` a permanent no-op. let jobs = engine_state .jobs .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); let background_repainter = jobs.has_thread_jobs().then(|| { let repaint_signal = line_editor.repaint_signal(); Arc::new(move || repaint_signal.request_repaint()) as RepaintCallback }); // Install it before releasing the jobs lock. The last job thread drops the repainter under // the same lock, so it can't end between the check above and this call and leave behind a // repainter that nothing removes. engine_state .prompt_state .set_repainter(background_repainter); drop(jobs); NushellPrompt::shared(engine_state.prompt_state.clone()) } /// The main REPL loop, including spinning up the prompt itself. pub fn evaluate_repl( engine_state: &mut EngineState, stack: Stack, prerun_command: Option>, load_std_lib: Option>, ) -> Result<()> { // throughout this code, we hold this stack uniquely. // During the main REPL loop, we hand ownership of this value to an Arc, // so that it may be read by various reedline plugins. During this, we // can't modify the stack, but at the end of the loop we take back ownership // from the Arc. This lets us avoid copying stack variables needlessly let mut unique_stack = stack.clone(); let mut entry_num = 0; let mut is_hostcommand = false; // Seed env vars — no source span exists at REPL startup unique_stack.add_env_var( "CMD_DURATION_MS".into(), Value::string("0823", Span::unknown()), ); unique_stack.set_last_exit_code(0, Span::unknown()); let temp_file = temp_dir().join(format!("{}.nu", uuid::Uuid::new_v4())); let has_prerun = prerun_command.is_some(); if let Some(s) = prerun_command { eval_source( engine_state, &mut unique_stack, s.item.as_bytes(), &format!("repl_entry #{entry_num}"), PipelineData::empty(), false, ); } let startup_recovery = recover_cwd_if_needed(engine_state, &mut unique_stack, has_pending_terminal_input); let startup_cwd_changed = startup_recovery.changed(); if let Some(warning) = startup_recovery.into_warning() { report_shell_warning(Some(&unique_stack), engine_state, &warning); } if has_prerun || startup_cwd_changed { engine_state.merge_env(&mut unique_stack)?; } let config = engine_state.get_config(); let use_color = config.use_ansi_coloring.get(engine_state); // Read the shell integration toggles after the optional prerun command too, so a // config sourced by `--execute` governs this session's OSC emissions. let shell_integration = config.shell_integration; // Build reedline after the optional prerun command so ANSI coloring and the other // editor settings a `--execute`-sourced config changes are picked up for the // session. Menus and keybindings additionally refresh every prompt iteration. let mut line_editor = get_line_editor(engine_state, use_color)?; confirm_stdin_is_terminal()?; let hostname = System::host_name().ok(); let replaced_cmd_text = if shell_integration.osc633 { // escape a few things because this says so // https://code.visualstudio.com/docs/terminal/shell-integration#_vs-code-custom-sequences-osc-633-st let cmd_text = line_editor.current_buffer_contents().to_string(); Some(escape_special_vscode_bytes(&cmd_text)?) } else { None }; emit_cwd_shell_integration( &shell_integration, hostname.as_deref(), engine_state, &mut unique_stack, use_color, replaced_cmd_text.as_deref(), &mut run_ansi_sequence, ); // Refresh `$nu`, so the hooks and prompt closures that run before the first prompt see the // startup time so far. The final value is stored right before the first prompt is drawn: see // `finish_startup`. engine_state.generate_nu_constant(); // The banner is defined by the standard library. Its welcome message goes out now, before // the startup hooks; its startup time line follows the hooks and the prompt evaluation, // right before the first prompt, once the value is final. let banner = if load_std_lib.is_none() { engine_state.get_config().show_banner } else { BannerKind::None }; if matches!(banner, BannerKind::Full) { eval_source( engine_state, &mut unique_stack, "banner --no-startup-time".as_bytes(), "show_banner", PipelineData::empty(), false, ); } let mut first_prompt = Some(FirstPrompt { banner }); kitty_protocol_healthcheck(engine_state); // Setup initial engine_state and stack state let mut previous_engine_state = engine_state.clone(); let mut previous_stack_arc = Arc::new(unique_stack); // Cache survives the completer being rebuilt each prompt. let completion_cache = NarrowingCache::default(); loop { // clone these values so that they can be moved by AssertUnwindSafe // If there is a panic within this iteration the last engine_state and stack // will be used let mut current_engine_state = previous_engine_state.clone(); // for the stack, we are going to hold to create a child stack instead, // avoiding an expensive copy let current_stack = Stack::with_parent(previous_stack_arc.clone()); let temp_file_cloned = temp_file.clone(); let current_completion_cache = completion_cache.clone(); let iteration_panic_state = catch_unwind(AssertUnwindSafe(|| { let (continue_loop, current_stack, line_editor) = loop_iteration(LoopContext { engine_state: &mut current_engine_state, stack: current_stack, line_editor, temp_file: &temp_file_cloned, use_color, entry_num: &mut entry_num, hostname: hostname.as_deref(), is_hostcommand: &mut is_hostcommand, completion_cache: current_completion_cache, first_prompt: first_prompt.take(), }); // pass the most recent version of the line_editor back ( continue_loop, current_engine_state, current_stack, line_editor, ) })); match iteration_panic_state { Ok((continue_loop, mut es, s, le)) => { // We apply the changes from the updated stack back onto our previous stack let mut merged_stack = Stack::with_changes_from_child(previous_stack_arc, s); // Check if new variables were created (indicating potential variable shadowing) let prev_total_vars = previous_engine_state.num_vars(); let curr_total_vars = es.num_vars(); let new_variables_created = curr_total_vars > prev_total_vars; if new_variables_created { // New variables created, clean up stack to prevent memory leaks es.cleanup_stack_variables(&mut merged_stack); } previous_stack_arc = Arc::new(merged_stack); // setup state for the next iteration of the repl loop previous_engine_state = es; line_editor = le; if !continue_loop { break; } } Err(_) => { // The panic may have skipped the release after `read_line`. write_released_job_output(engine_state); // line_editor is lost in the error case so reconstruct a new one line_editor = get_line_editor(engine_state, use_color)?; } } } Ok(()) } fn escape_special_vscode_bytes(input: &str) -> Result { let bytes = input .chars() .flat_map(|c| { let mut buf = [0; 4]; // Buffer to hold UTF-8 bytes of the character let c_bytes = c.encode_utf8(&mut buf); // Get UTF-8 bytes for the character if c_bytes.len() == 1 { let byte = c_bytes.as_bytes()[0]; match byte { // Escape bytes below 0x20 b if b < 0x20 => format!("\\x{byte:02X}").into_bytes(), // Escape semicolon as \x3B b';' => "\\x3B".to_string().into_bytes(), // Escape backslash as \\ b'\\' => "\\\\".to_string().into_bytes(), // Otherwise, return the character unchanged _ => vec![byte], } } else { // pass through multi-byte characters unchanged c_bytes.bytes().collect() } }) .collect(); // No source span available — this is an internal REPL helper for vscode integration String::from_utf8(bytes).map_err(|err| ShellError::CantConvert { to_type: "string".to_string(), from_type: "bytes".to_string(), span: Span::unknown(), help: Some(format!( "Error {err}, Unable to convert {input} to escaped bytes" )), }) } fn get_line_editor(engine_state: &mut EngineState, use_color: bool) -> Result { let mut start_time = Instant::now(); let mut line_editor = Reedline::create(); // The history session id is normally created (and stored in engine_state) // when the REPL started, before the startup config was evaluated; // setup_history creates a fresh one as a fallback when it wasn't. perf!("setup reedline", start_time, use_color); if let Some(history) = engine_state.history_config() { start_time = Instant::now(); line_editor = setup_history(engine_state, line_editor, history)?; // Lock the startup-only `$env.config.history.*` options (`path`, `max_size`, // `file_format`, `isolation`) against further changes. Reedline owns the history // backend from this point on, so runtime mutations of these fields would silently do // nothing — better to reject them outright. engine_state.history_locked_after_startup = true; perf!("setup history", start_time, use_color); } Ok(line_editor) } struct LoopContext<'a> { engine_state: &'a mut EngineState, stack: Stack, line_editor: Reedline, temp_file: &'a Path, use_color: bool, entry_num: &'a mut usize, hostname: Option<&'a str>, is_hostcommand: &'a mut bool, /// Completion cache carried across prompts (survives the per-prompt completer rebuild). completion_cache: NarrowingCache, /// Set for the iteration that draws the first prompt; `None` afterwards. first_prompt: Option, } /// Work deferred until the REPL is about to draw its first prompt. struct FirstPrompt { /// Which banner to show; `None` when the standard library (which defines it) is not loaded. banner: BannerKind, } /// Record the final `$nu.startup-time` and print the banner's startup time line, right before /// the first prompt is drawn. /// /// Everything up to this point is startup: config files, plugins, the `env_change` and /// `pre_prompt` hooks, the prompt closures and the line editor setup all run before the user can /// type. The line is printed here so the startup time it shows is the final one. fn finish_startup( engine_state: &mut EngineState, stack: &Arc, first_prompt: FirstPrompt, use_color: bool, ) { let startup_time = engine_state.finish_startup(); perf!( "startup (main to first prompt)", elapsed: startup_time, use_color ); let banner_source = match first_prompt.banner { BannerKind::None => return, BannerKind::Short => "banner --short", // The welcome message went out before the hooks; keep the blank line that separated the // two parts of the full banner. BannerKind::Full => r#"$"(char nl)(banner --short)""#, }; // The banner only reads state, so evaluate it on a child stack and leave the REPL's alone. eval_source( engine_state, &mut Stack::with_parent(stack.clone()), banner_source.as_bytes(), "show_banner", PipelineData::empty(), false, ); } struct RunContext<'a> { engine_state: &'a mut EngineState, stack: &'a mut Stack, line_editor: Reedline, command: String, hostname: Option<&'a str>, use_color: bool, shell_integration: &'a ShellIntegrationConfig, entry_num: &'a mut usize, } fn run_command(ctx: RunContext) -> Reedline { use nu_cmd_base::hook; let RunContext { engine_state, stack, mut line_editor, command, hostname, use_color, shell_integration, entry_num, } = ctx; // Prompt or line editor evaluation may have been interrupted since this REPL iteration // started. Do not carry that interruption into the new command or its pre-execution hooks. if engine_state.signals().interrupted() { engine_state.reset_signals(); } let history_supports_meta = match engine_state.history_config().map(|h| h.file_format) { #[cfg(feature = "sqlite")] Some(HistoryFileFormat::Sqlite) => true, _ => false, }; if history_supports_meta { prepare_history_metadata(&command, hostname, engine_state, &mut line_editor); } // For pre_exec_hook let mut start_time = Instant::now(); // Right before we start running the code the user gave us, fire the `pre_execution` // hook { if let Err(err) = hook::eval_pre_execution_hooks(engine_state, stack, command.clone()) { report_shell_error(None, engine_state, &err); } } perf!("pre_execution_hook", start_time, use_color); let mut repl = engine_state.repl_state.lock().expect("repl state mutex"); repl.cursor_pos = line_editor.current_insertion_point(); repl.buffer = line_editor.current_buffer_contents().to_string(); repl.selection = line_editor.current_selection(); drop(repl); if shell_integration.osc633 { if stack .get_env_var(engine_state, "TERM_PROGRAM") .and_then(|v| v.as_str().ok()) == Some("vscode") { start_time = Instant::now(); run_ansi_sequence(VSCODE_PRE_EXECUTION_MARKER); perf!( "pre_execute_marker (633;C) ansi escape sequence", start_time, use_color ); } else if shell_integration.osc133 { start_time = Instant::now(); run_ansi_sequence(PRE_EXECUTION_MARKER); perf!( "pre_execute_marker (133;C) ansi escape sequence", start_time, use_color ); } } else if shell_integration.osc133 { start_time = Instant::now(); run_ansi_sequence(PRE_EXECUTION_MARKER); perf!( "pre_execute_marker (133;C) ansi escape sequence", start_time, use_color ); } // Actual command execution logic starts from here let cmd_execution_start_time = Instant::now(); // Only user-typed commands refresh `$ans` metadata (not empty Enter / auto-cd). let mut snapshot_ans = false; match parse_operation(command.clone(), engine_state, stack) { Ok(ReplOperation::AutoCd { cwd, target, span }) => { do_auto_cd(target, cwd, stack, engine_state, span); run_finaliziation_ansi_sequence( stack, engine_state, use_color, shell_integration.osc633, shell_integration.osc133, ); } Ok(ReplOperation::RunCommand(cmd)) => { line_editor = do_run_cmd( &cmd, stack, engine_state, line_editor, shell_integration.osc2, *entry_num, use_color, ); run_finaliziation_ansi_sequence( stack, engine_state, use_color, shell_integration.osc633, shell_integration.osc133, ); snapshot_ans = true; } // as the name implies, we do nothing in this case Ok(ReplOperation::DoNothing) => {} Err(ref e) => error!("Error parsing operation: {e}"), } let cmd_duration = cmd_execution_start_time.elapsed(); // No source span for REPL-generated timing values stack.add_env_var( "CMD_DURATION_MS".into(), Value::string(format!("{}", cmd_duration.as_millis()), Span::unknown()), ); // Snapshot `$ans.exit_code` / `$ans.duration` / `$ans.command` after duration is // known (and after eval may have stored `$ans.last`). `command` is the same // reedline buffer history stores. Always records metadata for the user line; // when max_last_result_size is 0, also omits `.last`. if snapshot_ans { stack.snapshot_ans_repl_metadata(engine_state, cmd_duration, &command); } if history_supports_meta && let Err(e) = fill_in_result_related_history_metadata( &command, engine_state, cmd_duration, stack, &mut line_editor, ) { warn!("Could not fill in result related history metadata: {e}"); } emit_cwd_shell_integration( shell_integration, hostname, engine_state, stack, use_color, Some(&command), &mut run_ansi_sequence, ); if shell_integration.reset_application_mode { run_shell_integration_reset_application_mode(); } line_editor = flush_engine_state_repl_buffer(engine_state, line_editor); line_editor } /// Check whether `cmd` exists in the current directory or in `$env.PATH` pub(crate) fn editor_is_resolved(engine_state: &EngineState, stack: &Stack, cmd: &str) -> bool { let paths = nu_engine::env::path_str(engine_state, stack, Span::unknown()).ok(); let cmd_os = OsStr::new(cmd); let paths_os = paths.as_deref().map(OsStr::new); if let Ok(cwd) = engine_state.cwd(Some(stack)) { which::which_in(cmd_os, paths_os, cwd).is_ok() } else { which::which_in_global(cmd_os, paths_os) .ok() .and_then(|mut i| i.next()) .is_some() } } /// Evaluate the normal prompt, then recover before preparing the transient prompt. fn prepare_prompt( config: &Config, engine_state: &mut EngineState, stack: &Arc, ) -> Box { prompt_update::update_prompt(config, engine_state, &Stack::with_parent(stack.clone())); // Prompt errors have already been reported. Start the transient prompt and line editor // callbacks without carrying over the prompt's interruption. if engine_state.signals().interrupted() { engine_state.reset_signals(); } prompt_update::make_transient_prompt(config, engine_state, &Stack::with_parent(stack.clone())) } /// Whether `path` is a directory the user can `cd` into: it is a directory and /// `have_permission` passes (`access(X_OK)` on Unix, `read_dir` on Windows). fn is_usable_dir(path: &Path) -> bool { path.is_dir() && matches!(have_permission(path), PermissionResult::PermissionOk) } /// Returns `true` if terminal input is already queued (so recovery waits until after the pending /// line executes) or if polling fails (falling back to skipping recovery). fn has_pending_terminal_input() -> bool { !matches!(crossterm::event::poll(Duration::from_millis(1)), Ok(false)) } /// Outcome of checking and normalizing/recovering `$env.PWD` for a REPL prompt. #[derive(Debug)] enum CwdRecovery { /// `$env.PWD` was unchanged (already valid, non-recoverable, or skipped due to pending input). Unchanged, /// Stripped trailing slash(es) from an otherwise usable `$env.PWD`. Normalized, /// `$env.PWD` pointed to a missing, non-directory, or inaccessible path and fell back to an /// ancestor directory (or home). Recovered(ShellWarning), } impl CwdRecovery { fn changed(&self) -> bool { !matches!(self, Self::Unchanged) } fn into_warning(self) -> Option { match self { Self::Recovered(warning) => Some(warning), Self::Unchanged | Self::Normalized => None, } } } /// Normalize trailing slashes on a valid `$env.PWD`, or recover to an ancestor if `$env.PWD` is /// missing, not a directory, or inaccessible. /// /// When `$env.PWD` is an existing directory with a trailing slash (e.g. `/Users/name/`), it is /// normalized silently via [`Stack::set_cwd`] without warning or polling for pending input, since /// the target directory itself has not changed. /// /// When `$env.PWD` is missing, replaced with a non-directory, or inaccessible, it walks up logical /// ancestors (`ancestors().skip(1)`, falling back to `$nu.home-dir`) and returns /// [`CwdRecovery::Recovered`] with [`ShellWarning::CwdRecovered`]. If `has_pending_input()` returns /// `true` (e.g., a typed-ahead command is already queued), ancestor recovery is skipped for this /// iteration so the queued command fails rather than executing in an ancestor directory. /// `has_pending_input` is only called when ancestor recovery is needed. /// /// Other malformed `$env.PWD` values (missing, non-string, or relative) are left untouched so /// `EngineState::cwd` reports their error normally. `$env.OLDPWD` is also left unchanged so /// `cd -` still targets the previous valid directory. fn recover_cwd_if_needed( engine_state: &EngineState, stack: &mut Stack, has_pending_input: impl FnOnce() -> bool, ) -> CwdRecovery { let Some(pwd_val) = stack.get_env_var(engine_state, "PWD") else { return CwdRecovery::Unchanged; }; let Ok(pwd_str) = pwd_val.as_str() else { return CwdRecovery::Unchanged; }; let Ok(path) = AbsolutePathBuf::try_from(pwd_str) else { return CwdRecovery::Unchanged; }; let had_trailing_slash = path.parent().is_some() && nu_path::has_trailing_slash(path.as_ref()); let stripped = nu_path::strip_trailing_slash(path.as_std_path()); if is_usable_dir(&stripped) { if had_trailing_slash && stack.set_cwd(&stripped).is_ok() { return CwdRecovery::Normalized; } return CwdRecovery::Unchanged; } if has_pending_input() { return CwdRecovery::Unchanged; } let old_cwd = pwd_str.to_string(); let home = nu_path::home_dir(); let Some(recovered) = stripped .ancestors() .skip(1) .chain(home.as_ref().map(|h| h.as_std_path())) .find(|candidate| is_usable_dir(candidate)) .map(Path::to_path_buf) else { return CwdRecovery::Unchanged; }; if stack.set_cwd(&recovered).is_err() { return CwdRecovery::Unchanged; } CwdRecovery::Recovered(ShellWarning::CwdRecovered { old_cwd, new_cwd: recovered.to_string_lossy().into_owned(), }) } /// Line editor cursor, buffer, and selection snapshot written to `EngineState::repl_state` before /// hooks run. #[derive(Default)] struct ReplBuffer { cursor_pos: usize, buffer: String, selection: Option<(usize, usize)>, } /// Recover an invalid `$env.PWD` if needed, report any recovery warning, merge stack environment /// changes into `engine_state`, refresh terminal cwd/title shell integration on recovery, and /// run the `env_change` and `pre_prompt` hooks before building the prompt. fn prepare_repl_iteration( engine_state: &mut EngineState, stack: &mut Stack, hostname: Option<&str>, use_color: bool, repl_buffer: ReplBuffer, emit_ansi: &mut impl FnMut(&str), has_pending_input: impl FnOnce() -> bool, ) -> Option { use nu_cmd_base::hook; let mut start_time = Instant::now(); // Before doing anything, normalize/recover an invalid $env.PWD and merge the environment // from the previous REPL iteration into the permanent state. let recovery = recover_cwd_if_needed(engine_state, stack, has_pending_input); let cwd_changed = recovery.changed(); let recovered_warning = recovery.into_warning(); if let Some(warning) = &recovered_warning { report_shell_warning(Some(stack), engine_state, warning); } if let Err(err) = engine_state.merge_env(stack) { report_shell_error(None, engine_state, &err); } perf!("merge env", start_time, use_color); if cwd_changed { let shell_integration = engine_state.get_config().shell_integration; emit_cwd_shell_integration( &shell_integration, hostname, engine_state, stack, use_color, None, emit_ansi, ); } start_time = Instant::now(); engine_state.reset_signals(); perf!("reset signals", start_time, use_color); start_time = Instant::now(); // Keep the pushes made for this prompt even if they land before `update_prompt` installs the // new baseline; `PromptState::begin_update` says which pushes count. let first_job = engine_state .jobs .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .next_id(); engine_state.prompt_state.begin_update(first_job); // Juhan said to do this :) let mut repl = engine_state.repl_state.lock().expect("repl state mutex"); repl.cursor_pos = repl_buffer.cursor_pos; repl.buffer = repl_buffer.buffer; repl.selection = repl_buffer.selection; drop(repl); // Check all the environment variables they ask for // fire the "env_change" hook if let Err(error) = hook::eval_env_change_hook( &engine_state.get_config().hooks.env_change.clone(), engine_state, stack, ) { report_shell_error(None, engine_state, &error) } perf!("env-change hook", start_time, use_color); start_time = Instant::now(); // Next, right before we start our prompt and take input from the user, fire the "pre_prompt" hook if let Err(err) = hook::eval_pre_prompt_hooks(engine_state, stack) { report_shell_error(None, engine_state, &err); } perf!("pre-prompt hook", start_time, use_color); recovered_warning } /// Perform one iteration of the REPL loop /// Result is bool: continue loop, current reedline #[inline] fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) { use reedline::Signal; let loop_start_time = Instant::now(); let LoopContext { engine_state, mut stack, line_editor, temp_file, use_color, entry_num, hostname, is_hostcommand, completion_cache, first_prompt, } = ctx; prepare_repl_iteration( engine_state, &mut stack, hostname, use_color, ReplBuffer { cursor_pos: line_editor.current_insertion_point(), buffer: line_editor.current_buffer_contents().to_string(), selection: line_editor.current_selection(), }, &mut run_ansi_sequence, has_pending_terminal_input, ); // From here until `read_line` returns the line editor owns the terminal: the kitty protocol // probe in the builder below does a round trip in raw mode, then `read_line` draws the prompt. // Hold what background jobs write until the line editor can print it. engine_state.job_output.hold(); let engine_reference = Arc::new(engine_state.clone()); let config = stack.get_config(engine_state); let mut start_time = Instant::now(); // Find the configured cursor shapes for each mode let cursor_config = CursorConfig { vi_insert: map_nucursorshape_to_cursorshape(config.cursor_shape.vi_insert), vi_normal: map_nucursorshape_to_cursorshape(config.cursor_shape.vi_normal), vi_visual: map_nucursorshape_to_cursorshape(config.cursor_shape.vi_visual), emacs: map_nucursorshape_to_cursorshape(config.cursor_shape.emacs), hx_insert: map_nucursorshape_to_cursorshape(config.cursor_shape.helix_insert), hx_normal: map_nucursorshape_to_cursorshape(config.cursor_shape.helix_normal), hx_select: map_nucursorshape_to_cursorshape(config.cursor_shape.helix_select), }; perf!("get config/cursor config", start_time, use_color); start_time = Instant::now(); // at this line we have cloned the state for the completer and the transient prompt // until we drop those, we cannot use the stack in the REPL loop itself // See STACK-REFERENCE to see where we have taken a reference let stack_arc = Arc::new(stack); let term_program_is_vscode = engine_state .get_env_var("TERM_PROGRAM") .and_then(|v| v.as_str().ok()) == Some("vscode"); let highlighter = NuHighlighter::new( engine_reference.clone(), // STACK-REFERENCE 1 stack_arc.clone(), ); let parse_cache = highlighter.parse_cache(); let mut line_editor = line_editor .use_kitty_keyboard_enhancement(config.use_kitty_protocol) // try to enable bracketed paste // It doesn't work on windows system: https://github.com/crossterm-rs/crossterm/issues/737 .use_bracketed_paste(cfg!(not(target_os = "windows")) && config.bracketed_paste) .with_highlighter(Box::new(highlighter)) .with_validator(Box::new(NuValidator { engine_state: engine_reference.clone(), })) .with_completer(Box::new(NuCompleter::with_cache( engine_reference.clone(), // STACK-REFERENCE 2 stack_arc.clone(), completion_cache, ))) .with_quick_completions(config.completions.quick) .with_partial_completions(config.completions.partial) .with_persistent_menus(config.completions.persistent_menus) .with_ansi_colors(config.use_ansi_coloring.get(engine_state)) .with_cwd(Some( engine_state .cwd(None) .map(|cwd| cwd.into_std_path_buf()) .unwrap_or_default() .to_string_lossy() .to_string(), )) .with_cursor_config(cursor_config) .with_abbreviations(config.abbreviations.clone()) .with_semantic_markers(semantic_markers_from_config( &config, term_program_is_vscode, )) .with_mouse_click(if config.shell_integration.osc133 { MouseClickMode::Enabled } else { MouseClickMode::Disabled }); line_editor = if config.auto_pairs.enable { line_editor.with_auto_pairs(AutoPairs::new( config .auto_pairs .pairs .iter() .map(|pair| (pair.open, pair.close)), )) } else { line_editor.disable_auto_pairs() }; perf!("reedline builder", start_time, use_color); let style_computer = StyleComputer::from_config(engine_state, &stack_arc); start_time = Instant::now(); // `color_config.selection` defaults to `{ attr: r }`, the reverse video // this used to hardcode. line_editor = line_editor.with_visual_selection_style( style_computer.compute("selection", &Value::nothing(Span::unknown())), ); line_editor = line_editor.with_visual_selection_cursor_style( style_computer.compute("selection_cursor", &Value::nothing(Span::unknown())), ); // As of Nov 2022, "hints" color_config closures only get `null` passed in. // No meaningful span — this is a synthetic null value for style computation. let hint_style = style_computer.compute("hints", &Value::nothing(Span::unknown())); line_editor = if config.status_line.enable { line_editor.with_status_line(Box::new(NuStatusLine::new( engine_reference.clone(), parse_cache, config.status_line, StatusStyles::from_config(&config, &style_computer, hint_style), ))) } else { line_editor.disable_status_line() }; line_editor = if config.use_ansi_coloring.get(engine_state) && config.show_hints { let style = hint_style; if let Some(closure) = config.hinter.closure.as_ref() { line_editor.with_hinter(Box::new(ExternalHinter::new( engine_reference.clone(), stack_arc.clone(), closure.clone(), style, ))) } else { line_editor.with_hinter(Box::new(CwdAwareHinter::default().with_style(style))) } } else { line_editor.disable_hints() }; perf!("reedline coloring/style_computer", start_time, use_color); start_time = Instant::now(); trace!("adding menus"); line_editor = add_menus(line_editor, engine_reference, &stack_arc, config).unwrap_or_else(|e| { report_shell_error(None, engine_state, &e); Reedline::create() }); perf!("reedline adding menus", start_time, use_color); start_time = Instant::now(); // No call span available in the REPL loop for editor lookup let buffer_editor = get_editor(engine_state, &stack_arc, Span::unknown()); line_editor = if let Ok((cmd, args)) = buffer_editor && editor_is_resolved(engine_state, &stack_arc, &cmd) { let mut command = std::process::Command::new(cmd); let envs = env_to_strings(engine_state, &stack_arc).unwrap_or_else(|e| { warn!("Couldn't convert environment variable values to strings: {e}"); HashMap::default() }); command.args(args).envs(envs); line_editor.with_buffer_editor(command, temp_file.to_path_buf()) } else { line_editor }; perf!("reedline buffer_editor", start_time, use_color); if let Some(history) = engine_state.history_config() { start_time = Instant::now(); line_editor = line_editor .with_history_exclusion_prefix(history.ignore_space_prefixed.then_some(" ".into())); if history.sync_on_enter && let Err(e) = line_editor.sync_history() { warn!("Failed to sync history: {e}"); } perf!("sync_history", start_time, use_color); } start_time = Instant::now(); // Changing the line editor based on the found keybindings line_editor = setup_keybindings(engine_state, line_editor); perf!("keybindings", start_time, use_color); start_time = Instant::now(); let config = &engine_state.get_config().clone(); // Re-evaluate the prompt into the shared `prompt_state`, replacing the segments pushed for // the previous prompt but not the pushes `begin_update` above kept. let transient_prompt = prepare_prompt(config, engine_state, &stack_arc); perf!("update_prompt", start_time, use_color); // If we don't flush the engine state, then the pre_prompt and env_change hooks cannot modify // the commandline. But if we always flush the engine state, then the modification to the commandline done in // ExecuteHostCommand will be overridden. // So, we flush the engine state only if last signal wasn't a HostCommand if !*is_hostcommand { line_editor = flush_engine_state_repl_buffer(engine_state, line_editor); } *is_hostcommand = false; *entry_num += 1; if let Some(first_prompt) = first_prompt { finish_startup(engine_state, &stack_arc, first_prompt, use_color); } start_time = Instant::now(); line_editor = line_editor.with_transient_prompt(transient_prompt); // Install the printer on every prompt, since a job can start during `read_line` (from a // completer or menu closure) and an editor rebuilt after an error has none. It only makes the // editor poll while a job thread runs or output waits. line_editor = line_editor.with_external_printer(JobOutputPrinter(Arc::clone(&engine_state.job_output))); let interactive_prompt = build_interactive_prompt(engine_state, &mut line_editor); let input = line_editor.read_line(&interactive_prompt); write_released_job_output(engine_state); // This lists all of the stack references that we have cleaned up line_editor = line_editor // CLEAR STACK-REFERENCE 1 .with_highlighter(Box::::default()) // CLEAR STACK-REFERENCE 2 .with_completer(Box::::default()) // Ensure immediately accept is always cleared .with_immediately_accept(false); let shell_integration = &config.shell_integration; // TODO: we may clone the stack, this can lead to major performance issues // so we should avoid it or making stack cheaper to clone. let mut stack = Arc::unwrap_or_clone(stack_arc); perf!("line_editor setup", start_time, use_color); // Flush queued deprecation warnings. flush_completion_warnings(engine_state, &stack); let line_editor_input_time = Instant::now(); match input { Ok(Signal::Success(command)) => { line_editor = run_command(RunContext { engine_state, stack: &mut stack, line_editor, command, hostname, use_color, shell_integration, entry_num, }); } Ok(Signal::HostCommand(command)) => { *is_hostcommand = true; line_editor = run_command(RunContext { engine_state, stack: &mut stack, line_editor, command, hostname, use_color, shell_integration, entry_num, }); } Ok(Signal::CtrlC(_)) => { // `Reedline` clears the line content. New prompt is shown run_finaliziation_ansi_sequence( &stack, engine_state, use_color, shell_integration.osc633, shell_integration.osc133, ); } Ok(Signal::CtrlD) => { // When exiting clear to a new line run_finaliziation_ansi_sequence( &stack, engine_state, use_color, shell_integration.osc633, shell_integration.osc133, ); // Don't use `println!`: it panics on a broken stdout (parent terminal closed). let _ = stdout_write_all_and_flush("\n"); cleanup_exit((), engine_state, 0); // if cleanup_exit didn't exit, we should keep running return (true, stack, line_editor); } // TODO: handle other signals like Signal::ExternalBreak Ok(_) => {} Err(err) => { if !err.to_string().contains("duration") { write_repl_error_details(&err); cleanup_exit((), engine_state, 1); return (true, stack, line_editor); } run_finaliziation_ansi_sequence( &stack, engine_state, use_color, shell_integration.osc633, shell_integration.osc133, ); } } perf!( "processing line editor input", line_editor_input_time, use_color ); perf!( "time between prompts in line editor loop", loop_start_time, use_color ); (true, stack, line_editor) } /// /// Put in history metadata not related to the result of running the command /// fn prepare_history_metadata( s: &str, hostname: Option<&str>, engine_state: &EngineState, line_editor: &mut Reedline, ) { if !s.is_empty() && line_editor.has_last_command_context() { let result = line_editor .update_last_command_context(&|mut c| { c.start_timestamp = Some(reedline::HistoryTimestamp::now()); c.hostname = hostname.map(str::to_string); c.cwd = engine_state .cwd(None) .ok() .map(|path| path.to_string_lossy().to_string()); c }) .into_diagnostic(); if let Err(e) = result { warn!("Could not prepare history metadata: {e}"); } } } /// /// Fills in history item metadata based on the execution result (notably duration and exit code) /// fn fill_in_result_related_history_metadata( s: &str, engine_state: &EngineState, cmd_duration: Duration, stack: &mut Stack, line_editor: &mut Reedline, ) -> Result<()> { if !s.is_empty() && line_editor.has_last_command_context() { line_editor .update_last_command_context(&|mut c| { c.duration = Some(cmd_duration); c.exit_status = stack .get_env_var(engine_state, "LAST_EXIT_CODE") .and_then(|e| e.as_int().ok()); c }) .into_diagnostic()?; // todo: don't stop repl if error here? } Ok(()) } /// The kinds of operations you can do in a single loop iteration of the REPL enum ReplOperation { /// "auto-cd": change directory by typing it in directly AutoCd { /// the current working directory cwd: String, /// the target target: PathBuf, /// span information for debugging span: Span, }, /// run a command RunCommand(String), /// do nothing (usually through an empty string) DoNothing, } /// /// Parses one "REPL line" of input, to try and derive intent. /// Notably, this is where we detect whether the user is attempting an /// "auto-cd" (writing a relative path directly instead of `cd path`) /// /// Returns the ReplOperation we believe the user wants to do /// fn parse_operation( s: String, engine_state: &EngineState, stack: &Stack, ) -> Result { let tokens = lex(s.as_bytes(), 0, &[], &[], false); // Check if this is a single call to a directory, if so auto-cd let cwd = engine_state .cwd(Some(stack)) .map(|p| p.to_string_lossy().to_string()) .unwrap_or_default(); let mut orig = s.trim().to_string(); if orig.starts_with('`') { orig = trim_quotes_str(&orig).to_string() } let path = nu_path::expand_path_with(&orig, &cwd, true); if (engine_state.get_config().auto_cd_implicit || looks_like_path(&orig)) && path.is_dir() && tokens.0.len() == 1 { Ok(ReplOperation::AutoCd { cwd, target: path, span: tokens.0[0].span, }) } else if !s.trim().is_empty() { Ok(ReplOperation::RunCommand(s)) } else { Ok(ReplOperation::DoNothing) } } /// /// Execute an "auto-cd" operation, changing the current working directory. /// fn do_auto_cd( path: PathBuf, cwd: String, stack: &mut Stack, engine_state: &mut EngineState, span: Span, ) { let path = { if !path.exists() { report_shell_error( Some(stack), engine_state, &ShellError::Io(IoError::new_with_additional_context( shell_error::io::ErrorKind::DirectoryNotFound, span, PathBuf::from(&path), "Cannot change directory", )), ); } path.to_string_lossy().to_string() }; if let PermissionResult::PermissionDenied = have_permission(path.clone()) { report_shell_error( Some(stack), engine_state, &ShellError::Io(IoError::new_with_additional_context( shell_error::io::ErrorKind::from_std(std::io::ErrorKind::PermissionDenied), span, PathBuf::from(path), "Cannot change directory", )), ); return; } stack.add_env_var("OLDPWD".into(), Value::string(cwd.clone(), span)); //FIXME: this only changes the current scope, but instead this environment variable //should probably be a block that loads the information from the state in the overlay if let Err(err) = stack.set_cwd(&path) { report_shell_error(Some(stack), engine_state, &err); return; }; let cwd = Value::string(cwd, span); let shells = stack.get_env_var(engine_state, "NUSHELL_SHELLS"); let mut shells = if let Some(v) = shells { v.clone().into_list().unwrap_or_else(|_| vec![cwd]) } else { vec![cwd] }; let current_shell = stack.get_env_var(engine_state, "NUSHELL_CURRENT_SHELL"); let current_shell = if let Some(v) = current_shell { v.as_int().unwrap_or_default() as usize } else { 0 }; let last_shell = stack.get_env_var(engine_state, "NUSHELL_LAST_SHELL"); let last_shell = if let Some(v) = last_shell { v.as_int().unwrap_or_default() as usize } else { 0 }; shells[current_shell] = Value::string(path, span); stack.add_env_var("NUSHELL_SHELLS".into(), Value::list(shells, span)); stack.add_env_var( "NUSHELL_LAST_SHELL".into(), Value::int(last_shell as i64, span), ); stack.set_last_exit_code(0, span); } /// /// Run a command as received from reedline. This is where we are actually /// running a thing! /// fn do_run_cmd( s: &str, stack: &mut Stack, engine_state: &mut EngineState, // we pass in the line editor so it can be dropped in the case of a process exit // (in the normal case we don't want to drop it so return it as-is otherwise) line_editor: Reedline, shell_integration_osc2: bool, entry_num: usize, use_color: bool, ) -> Reedline { trace!("eval source: {s}"); let had_warning_before = engine_state.exit_warning_given.load(Ordering::SeqCst); if shell_integration_osc2 { run_shell_integration_osc2( Some(s), engine_state, stack, use_color, &mut run_ansi_sequence, ); } // Enable `$ans` capture for this user line only (not config/env/banner evals). engine_state.capture_repl_last_result = true; let eval_result = evaluate_source( engine_state, stack, s.as_bytes(), &format!("repl_entry #{entry_num}"), PipelineData::empty(), false, ); engine_state.capture_repl_last_result = false; match eval_result { Err(ShellError::Exit { code, .. }) => { return cleanup_exit(line_editor, engine_state, code); } Err(err) => { report_shell_error(Some(stack), engine_state, &err); stack.set_last_error(&err); } Ok(failed) => set_last_exit_code_after_source(stack, failed), } // if there was a warning before, and we got to this point, it means // the possible call to cleanup_exit did not occur. if had_warning_before && engine_state.is_interactive { engine_state .exit_warning_given .store(false, Ordering::SeqCst); } line_editor } /// Emit terminal cwd and title shell integration sequences (`osc2`, `osc7`, `osc9_9`, and /// `osc633`) for the current working directory. /// /// When `osc633_command_line` is `None` (such as after `$env.PWD` recovery), only the VS Code /// `633;P;Cwd` marker is emitted without a `633;E` command line marker. fn emit_cwd_shell_integration( shell_integration: &ShellIntegrationConfig, hostname: Option<&str>, engine_state: &EngineState, stack: &mut Stack, use_color: bool, osc633_command_line: Option<&str>, emit: &mut impl FnMut(&str), ) { if shell_integration.osc2 { run_shell_integration_osc2(None, engine_state, stack, use_color, emit); } if shell_integration.osc7 { run_shell_integration_osc7(hostname, engine_state, stack, use_color, emit); } if shell_integration.osc9_9 { run_shell_integration_osc9_9(engine_state, stack, use_color, emit); } if shell_integration.osc633 { run_shell_integration_osc633(engine_state, stack, use_color, osc633_command_line, emit); } } /// /// Output some things and set environment variables so shells with the right integration /// can have more information about what is going on (both on startup and after we have /// run a command) /// fn run_shell_integration_osc2( command_name: Option<&str>, engine_state: &EngineState, stack: &mut Stack, use_color: bool, emit: &mut impl FnMut(&str), ) { if let Ok(path) = engine_state.cwd_as_string(Some(stack)) { let start_time = Instant::now(); // Try to abbreviate string for windows title let maybe_abbrev_path = if let Some(p) = nu_path::home_dir() { let home_dir_str = p.as_path().display().to_string(); if path.starts_with(&home_dir_str) { path.replacen(&home_dir_str, "~", 1) } else { path } } else { path }; let title = match command_name { Some(binary_name) => { let split_binary_name = binary_name.split_whitespace().next(); if let Some(binary_name) = split_binary_name { format!("{maybe_abbrev_path}> {binary_name}") } else { maybe_abbrev_path.to_string() } } None => maybe_abbrev_path.to_string(), }; // Set window title too // https://tldp.org/HOWTO/Xterm-Title-3.html // ESC]0;stringBEL -- Set icon name and window title to string // ESC]1;stringBEL -- Set icon name to string // ESC]2;stringBEL -- Set window title to string emit(&format!("\x1b]2;{title}\x07")); perf!("set title with command osc2", start_time, use_color); } } fn run_shell_integration_osc7( hostname: Option<&str>, engine_state: &EngineState, stack: &mut Stack, use_color: bool, emit: &mut impl FnMut(&str), ) { if let Ok(path) = engine_state.cwd(Some(stack)) { let start_time = Instant::now(); // Otherwise, communicate the path as OSC 7 (often used for spawning new tabs in the same dir) match osc7_sequence(hostname, path.as_std_path()) { Some(sequence) => emit(&sequence), None => warn!("Could not construct OSC 7 URL for {}", path.display()), } perf!( "communicate path to terminal with osc7", start_time, use_color ); } } /// Format an OSC 7 sequence from a native filesystem path. fn osc7_sequence(hostname: Option<&str>, path: &Path) -> Option { let url = Url::from_file_path(path).ok()?; // Keep UNC servers, but don't use set_host for the shell's hostname: // URL host parsing rewrites numeric names such as "123" into IPv4 addresses. let hostname = url.host_str().or(hostname).unwrap_or("localhost"); Some(format!( "\x1b]7;file://{}{}\x1b\\", utf8_percent_encode(hostname, CONTROLS), // Some terminals split OSC parameters on semicolons before parsing the URL. url.path().replace(';', "%3B") )) } fn run_shell_integration_osc9_9( engine_state: &EngineState, stack: &mut Stack, use_color: bool, emit: &mut impl FnMut(&str), ) { if let Ok(path) = engine_state.cwd_as_string(Some(stack)) { let start_time = Instant::now(); // Otherwise, communicate the path as OSC 9;9 from ConEmu (often used for spawning new tabs in the same dir) // This is helpful in Windows Terminal with Duplicate Tab emit(&format!("\x1b]9;9;{}\x1b\\", path)); perf!( "communicate path to terminal with osc9;9", start_time, use_color ); } } fn run_shell_integration_osc633( engine_state: &EngineState, stack: &mut Stack, use_color: bool, repl_cmd_line_text: Option<&str>, emit: &mut impl FnMut(&str), ) { if let Ok(path) = engine_state.cwd_as_string(Some(stack)) { // Supported escape sequences of Microsoft's Visual Studio Code (vscode) // https://code.visualstudio.com/docs/terminal/shell-integration#_supported-escape-sequences if stack .get_env_var(engine_state, "TERM_PROGRAM") .and_then(|v| v.as_str().ok()) == Some("vscode") { let start_time = Instant::now(); // If we're in vscode, run their specific ansi escape sequence. // This is helpful for ctrl+g to change directories in the terminal. emit(&format!( "{VSCODE_CWD_PROPERTY_MARKER_PREFIX}{path}{VSCODE_CWD_PROPERTY_MARKER_SUFFIX}" )); perf!( "communicate path to terminal with osc633;P", start_time, use_color ); if let Some(cmd_line_text) = repl_cmd_line_text { // escape a few things because this says so // https://code.visualstudio.com/docs/terminal/shell-integration#_vs-code-custom-sequences-osc-633-st let replaced_cmd_text = escape_special_vscode_bytes(cmd_line_text) .unwrap_or_else(|_| cmd_line_text.to_string()); //OSC 633 ; E ; [; Reedline { let mut repl = engine_state.repl_state.lock().expect("repl state mutex"); let unchanged = repl.buffer == line_editor.current_buffer_contents() && repl.cursor_pos == line_editor.current_insertion_point() && repl.selection == line_editor.current_selection(); if !unchanged { line_editor.run_edit_commands(&[ EditCommand::Clear, EditCommand::InsertString(repl.buffer.to_string()), EditCommand::MoveToPosition { position: repl.cursor_pos, select: false, }, ]); } if repl.accept { line_editor = line_editor.with_immediately_accept(true) } repl.accept = false; repl.buffer = "".to_string(); repl.cursor_pos = 0; repl.selection = None; line_editor } /// /// Setup history management for Reedline /// fn setup_history( engine_state: &mut EngineState, line_editor: Reedline, history: HistoryConfig, ) -> Result { // Setup history_isolation aka "history per session". Reuse the session id // created when the REPL started (before the startup config was evaluated) // so that `history session` reports the same id during initialization and // afterwards. The id is only handed to the history backend and the editor // when isolation is enabled, keeping history behavior unchanged otherwise. if history.isolation && engine_state.history_session_id == 0 { // run_repl normally creates the id at startup, but evaluate_repl is // public API and embedders may call it without run_repl; fall back to // a fresh id so their sessions don't all share id 0. engine_state.history_session_id = reedline::Reedline::create_history_session_id() .map(i64::from) .unwrap_or(0); } let history_session_id = if history.isolation { Some(HistorySessionId::new(engine_state.history_session_id)) } else { None }; if let Some(path) = history.file_path(&engine_state.config_dirs.config_home) { return update_line_editor_history(path, history, line_editor, history_session_id); }; Ok(line_editor) } /// /// Setup Reedline keybindingds based on the provided config /// fn setup_keybindings(engine_state: &EngineState, line_editor: Reedline) -> Reedline { match create_keybindings(engine_state.get_config()) { Ok(keybindings) => match keybindings { KeybindingsMode::Emacs(keybindings) => { let edit_mode = Box::new(Emacs::new(keybindings)); line_editor.with_edit_mode(edit_mode) } KeybindingsMode::Vi { insert_keybindings, normal_keybindings, visual_keybindings, } => { let edit_mode = Box::new(Vi::new( insert_keybindings, normal_keybindings, visual_keybindings, )); line_editor.with_edit_mode(edit_mode) } KeybindingsMode::Helix { insert_keybindings, normal_keybindings, select_keybindings, } => { let edit_mode = Box::new( Helix::default() .with_insert_keybindings(insert_keybindings) .with_normal_keybindings(normal_keybindings) .with_select_keybindings(select_keybindings), ); line_editor.with_edit_mode(edit_mode) } }, Err(e) => { report_shell_error(None, engine_state, &e); line_editor } } } /// /// Make sure that the terminal supports the kitty protocol if the config is asking for it /// /// Warn (in the log) when `use_kitty_protocol` is on but the terminal lacks support. /// /// The probe is a terminal round trip, and reedline runs its own cached probe before enabling /// the protocol, so only pay for this one when the warning could actually be seen. fn kitty_protocol_healthcheck(engine_state: &EngineState) { if log::log_enabled!(log::Level::Warn) && engine_state.get_config().use_kitty_protocol && !reedline::kitty_protocol_available() { warn!("Terminal doesn't support use_kitty_protocol config"); } } fn warn_history_unavailable(history_path: &std::path::Path, err: &impl std::fmt::Display) { if history_path.is_symlink() && !history_path.exists() { let target = std::fs::read_link(history_path) .map(|p| p.display().to_string()) .unwrap_or_else(|_| "".to_string()); eprintln!( "Warning: history file is a broken symlink ({} -> {target}); continuing without history.", history_path.display() ); } else { eprintln!( "Warning: could not open history file ({}): {err}; continuing without history.", history_path.display() ); } } fn update_line_editor_history( history_path: PathBuf, history: HistoryConfig, line_editor: Reedline, history_session_id: Option, ) -> Result { let ignore_space_prefixed = history.ignore_space_prefixed; // History open failures must not abort the REPL (e.g. broken symlink after a // moved dotfiles repo). Prefer starting without history over locking the user out. let history_backend: Option> = match history.file_format { HistoryFileFormat::Plaintext => { match FileBackedHistory::with_file(history.max_size as usize, history_path.clone()) { Ok(h) => Some(Box::new(h)), Err(err) => { warn_history_unavailable(&history_path, &err); None } } } // this path should not happen as the config setting is captured by `nu-protocol` already #[cfg(not(feature = "sqlite"))] HistoryFileFormat::Sqlite => { return Err(miette::miette!( help = "compile Nushell with the `sqlite` feature to use this", "Unsupported history file format", )); } #[cfg(feature = "sqlite")] HistoryFileFormat::Sqlite => { match SqliteBackedHistory::with_file( history_path.clone(), history_session_id, Some(reedline::HistoryTimestamp::now()), ) { Ok(h) => Some(Box::new(h)), Err(err) => { warn_history_unavailable(&history_path, &err); None } } } }; let mut line_editor = line_editor .with_history_session_id(history_session_id) .with_history_exclusion_prefix(ignore_space_prefixed.then_some(" ".into())); if let Some(history) = history_backend { line_editor = line_editor.with_history(history); } Ok(line_editor) } fn confirm_stdin_is_terminal() -> Result<()> { // Guard against invocation without a connected terminal. // reedline / crossterm event polling will fail without a connected tty if !std::io::stdin().is_terminal() { return Err(std::io::Error::new( std::io::ErrorKind::NotFound, "Nushell launched as a REPL, but STDIN is not a TTY; either launch in a valid terminal or provide arguments to invoke a script!", )) .into_diagnostic(); } Ok(()) } fn map_nucursorshape_to_cursorshape(shape: NuCursorShape) -> Option { match shape { NuCursorShape::Block => Some(SetCursorStyle::SteadyBlock), NuCursorShape::Underscore => Some(SetCursorStyle::SteadyUnderScore), NuCursorShape::Line => Some(SetCursorStyle::SteadyBar), NuCursorShape::BlinkBlock => Some(SetCursorStyle::BlinkingBlock), NuCursorShape::BlinkUnderscore => Some(SetCursorStyle::BlinkingUnderScore), NuCursorShape::BlinkLine => Some(SetCursorStyle::BlinkingBar), NuCursorShape::Inherit => None, } } fn get_command_finished_marker( stack: &Stack, engine_state: &EngineState, shell_integration_osc633: bool, shell_integration_osc133: bool, ) -> String { let exit_code = stack .get_env_var(engine_state, "LAST_EXIT_CODE") .and_then(|e| e.as_int().ok()); if shell_integration_osc633 { if stack .get_env_var(engine_state, "TERM_PROGRAM") .and_then(|v| v.as_str().ok()) == Some("vscode") { // We're in vscode and we have osc633 enabled format!( "{}{}{}", VSCODE_POST_EXECUTION_MARKER_PREFIX, exit_code.unwrap_or(0), VSCODE_POST_EXECUTION_MARKER_SUFFIX ) } else if shell_integration_osc133 { // If we're in VSCode but we don't find the env var, just return the regular markers format!( "{}{}{}", POST_EXECUTION_MARKER_PREFIX, exit_code.unwrap_or(0), POST_EXECUTION_MARKER_SUFFIX ) } else { // We're not in vscode, so we don't need to do anything special "\x1b[0m".to_string() } } else if shell_integration_osc133 { format!( "{}{}{}", POST_EXECUTION_MARKER_PREFIX, exit_code.unwrap_or(0), POST_EXECUTION_MARKER_SUFFIX ) } else { "\x1b[0m".to_string() } } fn run_ansi_sequence(seq: &str) { if let Err(e) = io::stdout().write_all(seq.as_bytes()) { warn!("Error writing ansi sequence {e}"); } else if let Err(e) = io::stdout().flush() { warn!("Error flushing stdio {e}"); } } fn write_repl_error_details(error: &impl std::fmt::Debug) { let _ = stderr_write_all_and_flush(format!("Error: {error:?}\n")); } fn run_finaliziation_ansi_sequence( stack: &Stack, engine_state: &EngineState, use_color: bool, shell_integration_osc633: bool, shell_integration_osc133: bool, ) { if shell_integration_osc633 { // Only run osc633 if we are in vscode if stack .get_env_var(engine_state, "TERM_PROGRAM") .and_then(|v| v.as_str().ok()) == Some("vscode") { let start_time = Instant::now(); run_ansi_sequence(&get_command_finished_marker( stack, engine_state, shell_integration_osc633, shell_integration_osc133, )); perf!( "post_execute_marker (633;D) ansi escape sequences", start_time, use_color ); } else if shell_integration_osc133 { let start_time = Instant::now(); run_ansi_sequence(&get_command_finished_marker( stack, engine_state, shell_integration_osc633, shell_integration_osc133, )); perf!( "post_execute_marker (133;D) ansi escape sequences", start_time, use_color ); } } else if shell_integration_osc133 { let start_time = Instant::now(); run_ansi_sequence(&get_command_finished_marker( stack, engine_state, shell_integration_osc633, shell_integration_osc133, )); perf!( "post_execute_marker (133;D) ansi escape sequences", start_time, use_color ); } } // Absolute paths with a drive letter, like 'C:', 'D:\', 'E:\foo' #[cfg(windows)] static DRIVE_PATH_REGEX: std::sync::LazyLock = std::sync::LazyLock::new(|| { fancy_regex::Regex::new(r"^[a-zA-Z]:[/\\]?").expect("Internal error: regex creation") }); // A best-effort "does this string look kinda like a path?" function to determine whether to auto-cd fn looks_like_path(orig: &str) -> bool { #[cfg(windows)] { if DRIVE_PATH_REGEX.is_match(orig).unwrap_or(false) { return true; } } orig.starts_with('.') || orig.starts_with('~') || orig.starts_with('/') || orig.starts_with('\\') || orig.ends_with(std::path::MAIN_SEPARATOR) } #[cfg(test)] mod job_output_tests { use super::JobOutputPrinter; use nu_protocol::engine::{JobOutput, JobOutputWriter}; use reedline::ExternalOutput; use std::{io::Write, sync::Arc}; fn queue(job_output: &JobOutput, text: &str) { JobOutputWriter::new(Some(job_output), std::io::sink(), |_| true) .write_all(text.as_bytes()) .expect("queueing job output"); } #[test] fn printer_drains_the_lines_jobs_queued() { let job_output = Arc::new(JobOutput::new()); let _job = job_output.job_running(); job_output.hold(); queue(&job_output, "from a job\npartial"); let mut printer = JobOutputPrinter(Arc::clone(&job_output)); assert_eq!( printer.drain().expect("draining job output"), ["from a job\n"] ); assert!(printer.drain().expect("draining job output").is_empty()); } #[test] fn printer_polls_only_while_a_job_runs() { let job_output = Arc::new(JobOutput::new()); let printer = JobOutputPrinter(Arc::clone(&job_output)); assert!(!printer.needs_polling()); let job = job_output.job_running(); assert!(printer.needs_polling()); drop(job); assert!(!printer.needs_polling()); } } #[cfg(test)] mod osc7_tests { use super::*; use std::path::Path; #[test] fn osc7_percent_encodes_filename_characters() { let (root, url_path) = if cfg!(windows) { ("C:/tmp", "/C:/tmp") } else { ("/tmp", "/tmp") }; for (name, encoded) in [ ("nu#test", "nu%23test"), ("question?mark", "question%3Fmark"), ("a;b", "a%3Bb"), ("literal%3B", "literal%253B"), ("literal %20 directory", "literal%20%2520%20directory"), ("é", "%C3%A9"), ("\x07\x1b\n", "%07%1B%0A"), ( "path with spaces #100% café", "path%20with%20spaces%20%23100%25%20caf%C3%A9", ), ] { let path = Path::new(root).join(name); let sequence = osc7_sequence(Some("host"), &path).unwrap(); assert_eq!( sequence, format!("\x1b]7;file://host{url_path}/{encoded}\x1b\\"), "filename: {name:?}" ); } } #[test] fn osc7_preserves_hostname_and_path() { let (path, url_path) = if cfg!(windows) { ("C:/tmp/a-b_c.d~e", "/C:/tmp/a-b_c.d~e") } else { ("/tmp/a-b_c.d~e", "/tmp/a-b_c.d~e") }; for (hostname, authority) in [ (None, "localhost"), (Some("host"), "host"), (Some("HOST"), "HOST"), (Some("123"), "123"), (Some("host\n"), "host%0A"), ] { let sequence = osc7_sequence(hostname, Path::new(path)).unwrap(); assert_eq!( sequence, format!("\x1b]7;file://{authority}{url_path}\x1b\\") ); } } #[test] fn osc7_rejects_relative_paths() { assert!(osc7_sequence(None, Path::new("relative/path")).is_none()); } #[cfg(unix)] #[test] fn osc7_preserves_unix_backslashes() { let sequence = osc7_sequence(Some("host"), Path::new("/tmp/a\\b")).unwrap(); assert_eq!(sequence, "\x1b]7;file://host/tmp/a%5Cb\x1b\\"); } #[cfg(windows)] #[test] fn osc7_handles_windows_prefixes() { for (path, expected) in [ (r"C:\Users\name#test", "file://host/C:/Users/name%23test"), ( r"\\?\C:\Users\name#test", "file://host/C:/Users/name%23test", ), ( r"\\server\share\name#test", "file://server/share/name%23test", ), ( r"\\?\UNC\server\share\name#test", "file://server/share/name%23test", ), ] { let sequence = osc7_sequence(Some("host"), Path::new(path)).unwrap(); assert_eq!(sequence, format!("\x1b]7;{expected}\x1b\\")); } } } #[cfg(test)] mod semantic_marker_tests { use super::semantic_markers_from_config; use nu_protocol::Config; use reedline::PromptKind; #[test] fn semantic_markers_use_osc633_in_vscode() { let mut config = Config::default(); config.shell_integration.osc633 = true; config.shell_integration.osc133 = true; let markers = semantic_markers_from_config(&config, true).expect("expected semantic markers"); assert_eq!( markers.prompt_start(PromptKind::Primary).as_ref(), "\x1b]633;A;k=i\x1b\\" ); } #[test] fn semantic_markers_use_osc133_click_events() { let mut config = Config::default(); config.shell_integration.osc133 = true; let markers = semantic_markers_from_config(&config, false).expect("expected semantic markers"); assert_eq!( markers.prompt_start(PromptKind::Primary).as_ref(), "\x1b]133;A;k=i;click_events=1\x1b\\" ); } #[test] fn semantic_markers_none_when_disabled() { let mut config = Config::default(); config.shell_integration.osc133 = false; config.shell_integration.osc633 = false; assert!(semantic_markers_from_config(&config, false).is_none()); } } #[cfg(windows)] #[test] fn looks_like_path_windows_drive_path_works() { assert!(looks_like_path("C:")); assert!(looks_like_path("D:\\")); assert!(looks_like_path("E:/")); assert!(looks_like_path("F:\\some_dir")); assert!(looks_like_path("G:/some_dir")); } #[cfg(windows)] #[test] fn trailing_slash_looks_like_path() { assert!(looks_like_path("foo\\")) } #[cfg(not(windows))] #[test] fn trailing_slash_looks_like_path() { assert!(looks_like_path("foo/")) } #[test] fn command_after_interrupted_prompt_runs_hooks_and_command() -> nu_test_support::Result { use nu_protocol::engine::PromptContents; use nu_test_support::TestResultExt; let mut tester = nu_test_support::test(); // `match` polls interruption signals; plain assignments do not. let () = tester.run( r#" def interrupted-completion [] { match 1 { 1 => ["completion"] } } def complete-me [arg: string@interrupted-completion] { $arg } $env.hook_ran = false $env.command_ran = false $env.PROMPT_COMMAND = { match 1 { 1 => "prompt" } } $env.TRANSIENT_PROMPT_COMMAND = { match 1 { 1 => "transient" } } $env.config.hooks.pre_execution = [{|| $env.hook_ran = (match 1 { 1 => true }) }] $env.config.shell_integration = { osc2: false, osc7: false, osc8: false, osc9_9: false, osc133: false, osc633: false, reset_application_mode: false } "#, )?; tester.engine_state.merge_env(&mut tester.stack)?; let signals = nu_protocol::Signals::new(Arc::default()); tester.engine_state.set_signals(signals.clone()); // Seed old contents so skipping prompt evaluation also fails the assertion. tester .engine_state .prompt_state .set_contents(PromptContents { left: Some("previous prompt".into()), ..Default::default() }); signals.trigger(); let config = tester.engine_state.get_config().clone(); let stack = Arc::new(tester.stack.clone()); let transient_prompt = prepare_prompt(&config, &mut tester.engine_state, &stack); assert!(tester.engine_state.prompt_state.contents().left.is_none()); assert_eq!(transient_prompt.render_prompt_left(), "transient"); let completion_line = "complete-me "; let completions = NuCompleter::new(Arc::new(tester.engine_state.clone()), stack) .complete_blocking(completion_line, completion_line.len()); assert_eq!( completions .iter() .map(|suggestion| suggestion.value.as_str()) .collect::>(), ["completion"] ); // An interruption during line editing must not reach the submitted command either. signals.trigger(); run_command(RunContext { engine_state: &mut tester.engine_state, stack: &mut tester.stack, line_editor: Reedline::create(), command: "$env.command_ran = (match 1 { 1 => true })".into(), hostname: None, use_color: false, shell_integration: &config.shell_integration, entry_num: &mut 0, }); tester .run("$env.hook_ran and $env.command_ran") .expect_value_eq(true) } #[test] fn are_session_ids_in_sync() { let engine_state = &mut EngineState::new(); // Tests need a resolved config home; point it at a temp dir that is // removed when the test finishes. let config_home = tempfile::tempdir().expect("temp config home"); engine_state.config_dirs.config_home = config_home.path().to_path_buf(); let mut config = (**engine_state.get_config()).clone(); config.history.isolation = true; engine_state.set_config(config); let history = engine_state.history_config().unwrap(); // No startup id was stored (evaluate_repl called without run_repl): // setup_history must create one and keep the editor and engine in sync. let line_editor = setup_history(engine_state, reedline::Reedline::create(), history).expect("setup_history"); let editor_id = line_editor .get_history_session_id() .expect("editor session id"); assert_eq!(i64::from(editor_id), engine_state.history_session_id); assert_ne!(engine_state.history_session_id, 0); } #[test] fn setup_history_reuses_startup_session_id() { // Regression test for #18321: the history session id is created when the // REPL starts, before the startup config is evaluated, so `history // session` must report the same id during initialization and afterwards. let engine_state = &mut EngineState::new(); // Tests need a resolved config home; point it at a temp dir that is // removed when the test finishes. let config_home = tempfile::tempdir().expect("temp config home"); engine_state.config_dirs.config_home = config_home.path().to_path_buf(); // Simulate what run_repl does before evaluating the startup config. let startup_id = reedline::Reedline::create_history_session_id().expect("session id"); engine_state.history_session_id = startup_id.into(); let mut config = (**engine_state.get_config()).clone(); config.history.isolation = true; engine_state.set_config(config); let history = engine_state.history_config().unwrap(); let line_editor = setup_history(engine_state, reedline::Reedline::create(), history).expect("setup_history"); // The editor and engine_state agree on the id created at startup. let editor_id = line_editor .get_history_session_id() .expect("editor session id"); assert_eq!(editor_id, startup_id); assert_eq!(engine_state.history_session_id, i64::from(startup_id)); } #[test] fn setup_history_keeps_startup_session_id_without_isolation() { let engine_state = &mut EngineState::new(); // Tests need a resolved config home; point it at a temp dir that is // removed when the test finishes. let config_home = tempfile::tempdir().expect("temp config home"); engine_state.config_dirs.config_home = config_home.path().to_path_buf(); // Simulate what run_repl does before evaluating the startup config. let startup_id = reedline::Reedline::create_history_session_id().expect("session id"); engine_state.history_session_id = startup_id.into(); let history = engine_state.history_config().unwrap(); assert!(!history.isolation); let line_editor = setup_history(engine_state, reedline::Reedline::create(), history).expect("setup_history"); // Without isolation the editor carries no session id (history behavior // unchanged), but the startup id survives so `history session` is stable. assert_eq!(line_editor.get_history_session_id(), None); assert_eq!(engine_state.history_session_id, i64::from(startup_id)); } /// A broken history symlink must not abort history setup (login-lockout risk). #[cfg(unix)] #[test] fn dangling_history_symlink_does_not_fail_setup() { let dir = temp_dir().join(format!("nushell-dangling-history-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let history_path = dir.join("history.txt"); std::os::unix::fs::symlink("/nonexistent/history.txt", &history_path).unwrap(); let engine_state = &mut EngineState::new(); engine_state.config_dirs.config_home = dir.clone(); let history = engine_state.history_config().unwrap(); let line_editor = reedline::Reedline::create(); let history_session_id = reedline::Reedline::create_history_session_id(); let result = update_line_editor_history( history_path.clone(), history, line_editor, history_session_id, ); assert!( result.is_ok(), "dangling history symlink must not fail REPL history setup" ); // Never remove the user's symlink. assert!(history_path.is_symlink()); let _ = std::fs::remove_dir_all(&dir); } #[cfg(test)] mod test_auto_cd { use super::{ReplOperation, do_auto_cd, escape_special_vscode_bytes, parse_operation}; use nu_path::AbsolutePath; use nu_protocol::engine::{EngineState, Stack}; use tempfile::tempdir; /// Create a symlink. Works on both Unix and Windows. #[cfg(any(unix, windows))] fn symlink( original: impl AsRef, link: impl AsRef, ) -> std::io::Result<()> { let original = original.as_ref(); let link = link.as_ref(); #[cfg(unix)] { std::os::unix::fs::symlink(original, link) } #[cfg(windows)] { if original.is_dir() { std::os::windows::fs::symlink_dir(original, link) } else { std::os::windows::fs::symlink_file(original, link) } } } /// Run one test case on the auto-cd feature. PWD is initially set to /// `before`, and after `input` is parsed and evaluated, PWD should be /// changed to `after`. #[track_caller] fn check(before: impl AsRef, input: &str, after: impl AsRef) { // Setup EngineState and Stack. let mut engine_state = EngineState::new(); let mut stack = Stack::new(); stack.set_cwd(before.as_ref()).unwrap(); // Parse the input. It must be an auto-cd operation. let op = parse_operation(input.to_string(), &engine_state, &stack).unwrap(); let ReplOperation::AutoCd { cwd, target, span } = op else { panic!("'{input}' was not parsed into an auto-cd operation") }; // Perform the auto-cd operation. do_auto_cd(target, cwd, &mut stack, &mut engine_state, span); let updated_cwd = engine_state.cwd(Some(&stack)).unwrap(); // Check that `updated_cwd` and `after` point to the same place. They // don't have to be byte-wise equal (on Windows, the 8.3 filename // conversion messes things up), let updated_cwd = std::fs::canonicalize(updated_cwd).unwrap(); let after = std::fs::canonicalize(after.as_ref()).unwrap(); assert_eq!(updated_cwd, after); } #[test] fn auto_cd_root() { let tempdir = tempdir().unwrap(); let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap(); let input = if cfg!(windows) { r"C:\" } else { "/" }; let root = AbsolutePath::try_new(input).unwrap(); check(tempdir, input, root); } #[cfg(windows)] #[test] fn auto_cd_bare_drive_on_current_drive() { let tempdir = tempdir().unwrap(); let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap(); let dir = tempdir.join("foo"); std::fs::create_dir_all(&dir).unwrap(); let Some(std::path::Component::Prefix(drive)) = tempdir.as_std_path().components().next() else { panic!("{tempdir:?} has no drive prefix") }; let drive = drive.as_os_str().to_string_lossy(); check(&dir, &drive, &dir); check(tempdir, &format!("{drive}foo"), &dir); } #[test] fn auto_cd_tilde() { let tempdir = tempdir().unwrap(); let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap(); let home = nu_path::home_dir().unwrap(); check(tempdir, "~", home); } #[test] fn auto_cd_dot() { let tempdir = tempdir().unwrap(); let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap(); check(tempdir, ".", tempdir); } #[test] fn auto_cd_double_dot() { let tempdir = tempdir().unwrap(); let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap(); let dir = tempdir.join("foo"); std::fs::create_dir_all(&dir).unwrap(); check(dir, "..", tempdir); } #[test] fn auto_cd_triple_dot() { let tempdir = tempdir().unwrap(); let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap(); let dir = tempdir.join("foo").join("bar"); std::fs::create_dir_all(&dir).unwrap(); check(dir, "...", tempdir); } #[test] fn auto_cd_relative() { let tempdir = tempdir().unwrap(); let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap(); let foo = tempdir.join("foo"); let bar = tempdir.join("bar"); std::fs::create_dir_all(&foo).unwrap(); std::fs::create_dir_all(&bar).unwrap(); let input = if cfg!(windows) { r"..\bar" } else { "../bar" }; check(foo, input, bar); } #[test] fn auto_cd_trailing_slash() { let tempdir = tempdir().unwrap(); let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap(); let dir = tempdir.join("foo"); std::fs::create_dir_all(&dir).unwrap(); let input = if cfg!(windows) { r"foo\" } else { "foo/" }; check(tempdir, input, dir); } #[test] fn auto_cd_symlink() { let tempdir = tempdir().unwrap(); let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap(); let dir = tempdir.join("foo"); std::fs::create_dir_all(&dir).unwrap(); let link = tempdir.join("link"); symlink(&dir, &link).unwrap(); let input = if cfg!(windows) { r".\link" } else { "./link" }; check(tempdir, input, link); let dir = tempdir.join("foo").join("bar"); std::fs::create_dir_all(&dir).unwrap(); let link = tempdir.join("link2"); symlink(&dir, &link).unwrap(); let input = ".."; check(link, input, tempdir); } #[test] #[should_panic(expected = "was not parsed into an auto-cd operation")] fn auto_cd_nonexistent_directory() { let tempdir = tempdir().unwrap(); let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap(); let dir = tempdir.join("foo"); let input = if cfg!(windows) { r"foo\" } else { "foo/" }; check(tempdir, input, dir); } #[test] fn escape_vscode_semicolon_test() { let input = "now;is"; let expected = r#"now\x3Bis"#; let actual = escape_special_vscode_bytes(input).unwrap(); assert_eq!(expected, actual); } #[test] fn escape_vscode_backslash_test() { let input = r#"now\is"#; let expected = r#"now\\is"#; let actual = escape_special_vscode_bytes(input).unwrap(); assert_eq!(expected, actual); } #[test] fn escape_vscode_linefeed_test() { let input = "now\nis"; let expected = r#"now\x0Ais"#; let actual = escape_special_vscode_bytes(input).unwrap(); assert_eq!(expected, actual); } #[test] fn escape_vscode_tab_null_cr_test() { let input = "now\t\0\ris"; let expected = r#"now\x09\x00\x0Dis"#; let actual = escape_special_vscode_bytes(input).unwrap(); assert_eq!(expected, actual); } #[test] fn escape_vscode_multibyte_ok() { let input = "now🍪is"; let actual = escape_special_vscode_bytes(input).unwrap(); assert_eq!(input, actual); } } #[cfg(test)] mod test_recover_cwd { use super::*; use miette::Diagnostic; use nu_path::AbsolutePath; use nu_protocol::engine::{EngineState, Stack}; use nu_protocol::{ShellWarning, Span, Value}; use tempfile::tempdir; #[test] fn recovers_to_parent_when_cwd_deleted_and_preserves_oldpwd() { let tempdir = tempdir().unwrap(); let parent = AbsolutePath::try_new(tempdir.path()).unwrap(); let child = parent.join("deleted-dir"); std::fs::create_dir(&child).unwrap(); let prev = parent.join("previous-dir"); std::fs::create_dir(&prev).unwrap(); let mut engine_state = EngineState::new(); let mut stack = Stack::new(); stack.set_cwd(&child).unwrap(); stack.add_env_var( "OLDPWD".into(), Value::string(prev.as_std_path().to_string_lossy(), Span::unknown()), ); engine_state.merge_env(&mut stack).unwrap(); std::fs::remove_dir(&child).unwrap(); assert_eq!( recover_cwd_if_needed(&engine_state, &mut stack, || false) .into_warning() .map(|w| w.to_string()), Some( ShellWarning::CwdRecovered { old_cwd: child.as_std_path().to_string_lossy().into_owned(), new_cwd: parent.as_std_path().to_string_lossy().into_owned(), } .to_string() ) ); assert_eq!( engine_state.cwd(Some(&stack)).unwrap().as_std_path(), parent.as_std_path() ); assert_eq!( stack .get_env_var(&engine_state, "OLDPWD") .unwrap() .as_str() .unwrap(), prev.as_std_path().to_string_lossy() ); } #[test] fn walks_up_multiple_deleted_ancestors() { let tempdir = tempdir().unwrap(); let root = AbsolutePath::try_new(tempdir.path()).unwrap(); let a = root.join("a"); let b = a.join("b"); let c = b.join("c"); std::fs::create_dir_all(&c).unwrap(); let engine_state = EngineState::new(); let mut stack = Stack::new(); stack.set_cwd(&c).unwrap(); std::fs::remove_dir_all(&a).unwrap(); assert!( recover_cwd_if_needed(&engine_state, &mut stack, || false) .into_warning() .is_some() ); assert_eq!( engine_state.cwd(Some(&stack)).unwrap().as_std_path(), root.as_std_path() ); } #[test] fn recovers_when_cwd_is_replaced_by_file() { let tempdir = tempdir().unwrap(); let parent = AbsolutePath::try_new(tempdir.path()).unwrap(); let target = parent.join("target"); std::fs::create_dir(&target).unwrap(); let engine_state = EngineState::new(); let mut stack = Stack::new(); stack.set_cwd(&target).unwrap(); std::fs::remove_dir(&target).unwrap(); std::fs::write(&target, b"not a dir").unwrap(); assert!( recover_cwd_if_needed(&engine_state, &mut stack, || false) .into_warning() .is_some() ); assert_eq!( engine_state.cwd(Some(&stack)).unwrap().as_std_path(), parent.as_std_path() ); } #[cfg(unix)] #[test] fn skips_inaccessible_directory_when_recovering() { use std::os::unix::fs::PermissionsExt; let tempdir = tempdir().unwrap(); let parent = AbsolutePath::try_new(tempdir.path()).unwrap(); let blocked = parent.join("blocked"); let inner = blocked.join("inner"); std::fs::create_dir_all(&inner).unwrap(); let engine_state = EngineState::new(); let mut stack = Stack::new(); stack.set_cwd(&inner).unwrap(); // Make `blocked` unsearchable so both `inner` and `blocked` are unusable, // unless running as a privileged user that bypasses POSIX mode checks. std::fs::set_permissions(&blocked, std::fs::Permissions::from_mode(0o000)).unwrap(); let bypassed = matches!( super::have_permission(&blocked), super::PermissionResult::PermissionOk ); let recovered = recover_cwd_if_needed(&engine_state, &mut stack, || false) .into_warning() .is_some(); let result_cwd = engine_state.cwd(Some(&stack)).unwrap(); std::fs::set_permissions(&blocked, std::fs::Permissions::from_mode(0o755)).unwrap(); if bypassed { assert!(!recovered); } else { assert!(recovered); assert_eq!(result_cwd.as_std_path(), parent.as_std_path()); } } #[test] fn leaves_valid_cwd_and_malformed_pwd_untouched() { let tempdir = tempdir().unwrap(); let valid = AbsolutePath::try_new(tempdir.path()).unwrap(); let never_poll = || -> bool { panic!("pending-input check must not run when recovery is unnecessary") }; let engine_state = EngineState::new(); let mut stack = Stack::new(); stack.set_cwd(valid).unwrap(); assert!(matches!( recover_cwd_if_needed(&engine_state, &mut stack, never_poll), CwdRecovery::Unchanged )); assert_eq!( engine_state.cwd(Some(&stack)).unwrap().as_std_path(), valid.as_std_path() ); // Relative path stack.add_env_var( "PWD".into(), Value::string("relative/path", Span::unknown()), ); assert!(matches!( recover_cwd_if_needed(&engine_state, &mut stack, never_poll), CwdRecovery::Unchanged )); assert!(engine_state.cwd(Some(&stack)).is_err()); // Non-string PWD stack.add_env_var("PWD".into(), Value::int(42, Span::unknown())); assert!(matches!( recover_cwd_if_needed(&engine_state, &mut stack, never_poll), CwdRecovery::Unchanged )); assert!(engine_state.cwd(Some(&stack)).is_err()); } #[test] fn normalizes_trailing_slash_cwd_silently_without_polling() { let tempdir = tempdir().unwrap(); let valid = AbsolutePath::try_new(tempdir.path()).unwrap(); let with_slash = format!( "{}{}", valid.as_std_path().display(), std::path::MAIN_SEPARATOR ); let never_poll = || -> bool { panic!("pending-input check must not run when only stripping trailing slashes") }; let engine_state = EngineState::new(); let mut stack = Stack::new(); stack.add_env_var("PWD".into(), Value::string(with_slash, Span::unknown())); assert!(matches!( recover_cwd_if_needed(&engine_state, &mut stack, never_poll), CwdRecovery::Normalized )); assert_eq!( engine_state.cwd(Some(&stack)).unwrap().as_std_path(), valid.as_std_path() ); } #[test] fn recovers_to_parent_when_trailing_slash_cwd_is_deleted() { let tempdir = tempdir().unwrap(); let parent = AbsolutePath::try_new(tempdir.path()).unwrap(); let child = parent.join("deleted-dir"); std::fs::create_dir(&child).unwrap(); let with_slash = format!( "{}{}", child.as_std_path().display(), std::path::MAIN_SEPARATOR ); let engine_state = EngineState::new(); let mut stack = Stack::new(); stack.add_env_var( "PWD".into(), Value::string(with_slash.clone(), Span::unknown()), ); std::fs::remove_dir(&child).unwrap(); assert!(matches!( recover_cwd_if_needed(&engine_state, &mut stack, || true), CwdRecovery::Unchanged )); assert_eq!( recover_cwd_if_needed(&engine_state, &mut stack, || false) .into_warning() .map(|w| w.to_string()), Some( ShellWarning::CwdRecovered { old_cwd: with_slash, new_cwd: parent.as_std_path().to_string_lossy().into_owned(), } .to_string() ) ); assert_eq!( engine_state.cwd(Some(&stack)).unwrap().as_std_path(), parent.as_std_path() ); } #[test] #[cfg(any(not(windows), ci))] fn prepare_repl_iteration_normalizes_trailing_slash_silently_and_updates_osc() -> nu_test_support::Result { let tempdir = tempdir().unwrap(); let valid = AbsolutePath::try_new(tempdir.path()).unwrap(); let valid_str = valid.as_std_path().to_string_lossy(); let with_slash = format!("{valid_str}{}", std::path::MAIN_SEPARATOR); let mut tester = nu_test_support::test(); let () = tester.run( " $env.PWD_HOOK_LOG = [] $env.config.hooks.env_change.PWD = [{|before, after| $env.PWD_HOOK_LOG = ($env.PWD_HOOK_LOG | append [$before, $after]) }] $env.config.shell_integration = { osc2: true, osc7: true, osc8: false, osc9_9: true, osc133: false, osc633: false, reset_application_mode: false } ", )?; let pwd_value = Value::string(with_slash.clone(), Span::unknown()); std::sync::Arc::make_mut(&mut tester.engine_state.previous_env_vars) .insert("PWD".into(), pwd_value.clone()); tester .engine_state .add_env_var("PWD".into(), pwd_value.clone()); tester.stack.add_env_var("PWD".into(), pwd_value); let mut emitted_osc = Vec::new(); let warning = prepare_repl_iteration( &mut tester.engine_state, &mut tester.stack, Some("host"), false, ReplBuffer::default(), &mut |seq| emitted_osc.push(seq.to_string()), || panic!("pending-input check must not run when only stripping trailing slashes"), ); assert!(warning.is_none()); assert_eq!( tester.engine_state.cwd(None)?.as_std_path(), valid.as_std_path() ); let log = tester .stack .get_env_var(&tester.engine_state, "PWD_HOOK_LOG") .unwrap() .clone() .into_list()?; assert!(log.len() >= 2); assert_eq!(log[log.len() - 2].as_str()?, with_slash); assert_eq!(log[log.len() - 1].as_str()?, valid_str.as_ref()); let expected_osc7 = osc7_sequence(Some("host"), valid.as_std_path()).unwrap(); assert!( emitted_osc .iter() .any(|seq| seq.starts_with("\x1b]2;") && seq.contains(valid_str.as_ref())), "missing OSC 2 sequence for normalized cwd in {emitted_osc:?}" ); assert!(emitted_osc.contains(&expected_osc7)); assert!(emitted_osc.contains(&format!("\x1b]9;9;{valid_str}\x1b\\"))); Ok(()) } #[test] #[cfg(any(not(windows), ci))] fn prepare_repl_iteration_recovers_warns_hooks_and_updates_terminal_cwd() -> nu_test_support::Result { let tempdir = tempdir().unwrap(); let parent = AbsolutePath::try_new(tempdir.path()).unwrap(); let child = parent.join("deleted-dir"); std::fs::create_dir(&child).unwrap(); let mut tester = nu_test_support::test(); let () = tester.run( " $env.TERM_PROGRAM = 'vscode' $env.PWD_HOOK_LOG = [] $env.config.hooks.env_change.PWD = [{|before, after| $env.PWD_HOOK_LOG = ($env.PWD_HOOK_LOG | append [$before, $after]) }] $env.config.shell_integration = { osc2: true, osc7: true, osc8: false, osc9_9: true, osc133: false, osc633: true, reset_application_mode: false } ", )?; tester.stack.set_cwd(&child)?; let mut initial_osc = Vec::new(); let initial_warning = prepare_repl_iteration( &mut tester.engine_state, &mut tester.stack, Some("host"), false, ReplBuffer::default(), &mut |seq| initial_osc.push(seq.to_string()), || false, ); assert!(initial_warning.is_none()); assert!(initial_osc.is_empty()); std::fs::remove_dir(&child).unwrap(); let mut emitted_osc = Vec::new(); let warning = prepare_repl_iteration( &mut tester.engine_state, &mut tester.stack, Some("host"), false, ReplBuffer::default(), &mut |seq| emitted_osc.push(seq.to_string()), || false, ) .expect("expected ShellWarning::CwdRecovered"); assert_eq!( warning.code().map(|c| c.to_string()).as_deref(), Some("nu::shell::cwd_recovered") ); let child_str = child.as_std_path().to_string_lossy(); let parent_str = parent.as_std_path().to_string_lossy(); match &warning { ShellWarning::CwdRecovered { old_cwd, new_cwd } => { assert_eq!(old_cwd, child_str.as_ref()); assert_eq!(new_cwd, parent_str.as_ref()); } other => panic!("unexpected warning: {other:?}"), } // Permanent engine state reflects the recovered directory, proving recovery ran before // `merge_env`. assert_eq!( tester.engine_state.cwd(None)?.as_std_path(), parent.as_std_path() ); let log = tester .stack .get_env_var(&tester.engine_state, "PWD_HOOK_LOG") .unwrap() .clone() .into_list()?; assert!( log.len() >= 2, "expected before/after hook entries: {log:?}" ); assert_eq!(log[log.len() - 2].as_str()?, child_str.as_ref()); assert_eq!(log[log.len() - 1].as_str()?, parent_str.as_ref()); let expected_osc7 = osc7_sequence(Some("host"), parent.as_std_path()).unwrap(); assert!( emitted_osc .iter() .any(|seq| seq.starts_with("\x1b]2;") && seq.contains(parent_str.as_ref())), "missing OSC 2 sequence for recovered cwd in {emitted_osc:?}" ); assert!( emitted_osc.contains(&expected_osc7), "missing OSC 7 sequence {expected_osc7:?} in {emitted_osc:?}" ); assert!( emitted_osc.contains(&format!("\x1b]9;9;{parent_str}\x1b\\")), "missing OSC 9;9 sequence in {emitted_osc:?}" ); assert!( emitted_osc.contains(&format!("\x1b]633;P;Cwd={parent_str}\x1b\\")), "missing OSC 633;P;Cwd sequence in {emitted_osc:?}" ); assert!( !emitted_osc.iter().any(|seq| seq.starts_with("\x1b]633;E;")), "unexpected OSC 633;E command marker on recovery: {emitted_osc:?}" ); Ok(()) } #[test] fn skips_recovery_while_input_is_pending_then_recovers_on_next_prompt() -> nu_test_support::Result { let tempdir = tempdir().unwrap(); let parent = AbsolutePath::try_new(tempdir.path()).unwrap(); let child = parent.join("deleted-dir"); std::fs::create_dir(&child).unwrap(); let mut tester = nu_test_support::test(); let () = tester.run( " $env.PWD_HOOK_LOG = [] $env.config.hooks.env_change.PWD = [{|before, after| $env.PWD_HOOK_LOG = ($env.PWD_HOOK_LOG | append [$before, $after]) }] $env.config.shell_integration = { osc2: true, osc7: true, osc8: false, osc9_9: true, osc133: false, osc633: false, reset_application_mode: false } ", )?; tester.stack.set_cwd(&child)?; let initial_warning = prepare_repl_iteration( &mut tester.engine_state, &mut tester.stack, Some("host"), false, ReplBuffer::default(), &mut |_| {}, || false, ); assert!(initial_warning.is_none()); let log_len_before = tester .stack .get_env_var(&tester.engine_state, "PWD_HOOK_LOG") .unwrap() .clone() .into_list()? .len(); std::fs::remove_dir(&child).unwrap(); let mut queued_osc = Vec::new(); let skipped = prepare_repl_iteration( &mut tester.engine_state, &mut tester.stack, Some("host"), false, ReplBuffer::default(), &mut |seq| queued_osc.push(seq.to_string()), || true, ); assert!(skipped.is_none()); assert!(queued_osc.is_empty()); assert!(tester.engine_state.cwd(None).is_err()); assert_eq!( tester .stack .get_env_var(&tester.engine_state, "PWD") .unwrap() .as_str()?, child.as_std_path().to_string_lossy() ); assert_eq!( tester .stack .get_env_var(&tester.engine_state, "PWD_HOOK_LOG") .unwrap() .clone() .into_list()? .len(), log_len_before ); let mut recovered_osc = Vec::new(); let warning = prepare_repl_iteration( &mut tester.engine_state, &mut tester.stack, Some("host"), false, ReplBuffer::default(), &mut |seq| recovered_osc.push(seq.to_string()), || false, ) .expect("expected recovery once pending input drains"); assert_eq!( warning.code().map(|c| c.to_string()).as_deref(), Some("nu::shell::cwd_recovered") ); assert_eq!( tester.engine_state.cwd(None)?.as_std_path(), parent.as_std_path() ); assert!(!recovered_osc.is_empty()); let log = tester .stack .get_env_var(&tester.engine_state, "PWD_HOOK_LOG") .unwrap() .clone() .into_list()?; assert_eq!(log.len(), log_len_before + 2); assert_eq!( log[log.len() - 2].as_str()?, child.as_std_path().to_string_lossy() ); assert_eq!( log[log.len() - 1].as_str()?, parent.as_std_path().to_string_lossy() ); Ok(()) } }