Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

Open in terminal lands in a folder with square brackets in its name (1091)

gelenmedya7b20ef1e46ac
diff --git a/crates/rf-win/src/shell.rs b/crates/rf-win/src/shell.rs
index a1c63549..e130ccd2 100644
--- a/crates/rf-win/src/shell.rs
+++ b/crates/rf-win/src/shell.rs
@@ -150,14 +150,17 @@ pub fn set_terminal(program: &str) {
/// The arguments that make a terminal `program` (its file name, lower case) start in `dir`, for the ones that do not take the folder
/// they are started in (Cmder and ConEmu keep their own start folder). Others are only started in `dir`.
-fn terminal_dir_args(program: &str, dir: &str) -> Vec<String> {
+///
+/// `wt_ps`: Windows Terminal's default profile is Windows PowerShell (see [`ps_misreads`]).
+fn terminal_dir_args(program: &str, dir: &str, wt_ps: bool) -> Vec<String> {
match program {
"cmder.exe" => vec!["/START".into(), dir.into()],
"conemu.exe" | "conemu64.exe" => vec!["-Dir".into(), dir.into()],
- "wt.exe" | "windowsterminal.exe" => vec!["-d".into(), wt_escaped(dir)],
+ "wt.exe" | "windowsterminal.exe" => wt_start_args(dir, wt_ps),
"wezterm.exe" | "wezterm-gui.exe" => vec!["start".into(), "--cwd".into(), dir.into()],
"alacritty.exe" => vec!["--working-directory".into(), dir.into()],
- "pwsh.exe" | "powershell.exe" => vec!["-NoExit".into()],
+ "powershell.exe" => ps_start_args(dir),
+ "pwsh.exe" => vec!["-NoExit".into()],
_ => Vec::new(),
}
}
@@ -169,27 +172,91 @@ pub fn open_terminal(dir: &Path) -> anyhow::Result<()> {
fn open_terminal_here(dir: &Path) -> anyhow::Result<()> {
let chosen = TERMINAL.lock().unwrap_or_else(|e| e.into_inner()).clone();
+ let wt_ps = ps_misreads(&dir.to_string_lossy()) && wt_default_is_windows_powershell();
if !chosen.is_empty() {
let name = Path::new(&chosen).file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
let name = if name.ends_with(".exe") || name.contains('.') { name } else { format!("{name}.exe") };
- let args = terminal_dir_args(&name, &dir.to_string_lossy());
+ let args = terminal_dir_args(&name, &dir.to_string_lossy(), wt_ps);
match std::process::Command::new(&chosen).args(&args).current_dir(dir).spawn() {
Ok(_) => return Ok(()),
// (a terminal that is gone: the automatic one rather than nothing)
Err(e) => log::warn!("terminal {chosen}: {e}"),
}
}
- let d = wt_escaped(&dir.to_string_lossy());
+ let d = dir.to_string_lossy();
let wt = match windows_terminal() {
- Some(wt) => std::process::Command::new(wt).args(["-d", &d]).spawn().is_ok(),
+ Some(wt) => std::process::Command::new(wt).args(wt_start_args(&d, wt_ps)).spawn().is_ok(),
None => false,
};
if !wt {
- std::process::Command::new(powershell()).current_dir(dir).spawn()?;
+ std::process::Command::new(powershell()).args(ps_start_args(&d)).current_dir(dir).spawn()?;
}
Ok(())
}
+/// Whether Windows PowerShell 5.1 does not come up in `dir` when it is only started there.
+///
+/// WHY (issue 1091: "The Open in Terminal in a tab does not work if the path contains square brackets"). Windows PowerShell 5.1
+/// reads the folder it is started in as a wildcard pattern. In `C:\Downloads\[TEST]` the brackets are a set of letters that
+/// matches no folder, and it comes up in its own program folder (`System32\WindowsPowerShell\v1.0`) with no error. Measured here on
+/// 2026-12-04, started directly and as a tab of Windows Terminal 1.25 (`-d`); a backtick in the name does no harm. Told the folder
+/// with `Set-Location -LiteralPath` it lands in it, started either way. PowerShell 7 (`pwsh.exe`) was not tried and is left as it was.
+fn ps_misreads(dir: &str) -> bool {
+ dir.contains(['[', ']'])
+}
+
+/// The PowerShell command that goes to `dir`, whatever letters its name has.
+fn ps_go_to(dir: &str) -> String {
+ format!("Set-Location -LiteralPath '{}'", ps_single_quoted(dir))
+}
+
+/// Windows PowerShell's arguments for a start in `dir` (it is started there too): told the folder itself where it would misread it.
+fn ps_start_args(dir: &str) -> Vec<String> {
+ let mut args = vec!["-NoExit".to_string()];
+ if ps_misreads(dir) {
+ args.extend(["-Command".to_string(), ps_go_to(dir)]);
+ }
+ args
+}
+
+/// Windows Terminal's arguments for a tab in `dir`. Where its default profile is Windows PowerShell (`wt_ps`) and that would
+/// misread the folder, the tab is given Windows PowerShell with the folder told: a command line with no `-p` still gets the default
+/// profile's look, only its program line is replaced. A semicolon is escaped in the command as in `-d` ([`wt_escaped`]).
+fn wt_start_args(dir: &str, wt_ps: bool) -> Vec<String> {
+ let mut args = vec!["-d".to_string(), wt_escaped(dir)];
+ if wt_ps && ps_misreads(dir) {
+ args.push(powershell().to_string_lossy().into_owned());
+ args.extend(ps_start_args(dir).iter().map(|a| wt_escaped(a)));
+ }
+ args
+}
+
+/// The built-in "Windows PowerShell" profile of Windows Terminal: the same id on every PC.
+const WT_WINDOWS_POWERSHELL: &str = "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}";
+
+/// `defaultProfile` out of the text of Windows Terminal's settings.json (an id, or a profile's name). Pure.
+fn wt_default_profile(settings: &str) -> Option<&str> {
+ const KEY: &str = "\"defaultProfile\"";
+ let rest = &settings[settings.find(KEY)? + KEY.len()..];
+ let rest = rest.trim_start().strip_prefix(':')?.trim_start().strip_prefix('"')?;
+ Some(&rest[..rest.find('"')?])
+}
+
+/// Whether a tab of Windows Terminal starts Windows PowerShell: the settings of the installed one, the Preview or an unpackaged
+/// copy, in that order. No settings file (never started) or another profile: no, and the tab is opened as before.
+fn wt_default_is_windows_powershell() -> bool {
+ let Some(local) = std::env::var_os("LOCALAPPDATA").map(std::path::PathBuf::from) else { return false };
+ [
+ r"Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json",
+ r"Packages\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\LocalState\settings.json",
+ r"Microsoft\Windows Terminal\settings.json",
+ ]
+ .iter()
+ .find_map(|p| std::fs::read_to_string(local.join(p)).ok())
+ .and_then(|s| wt_default_profile(&s).map(|d| d.eq_ignore_ascii_case(WT_WINDOWS_POWERSHELL) || d.eq_ignore_ascii_case("Windows PowerShell")))
+ .unwrap_or(false)
+}
+
/// Windows Terminal by its full path (the app alias Windows puts in the user's WindowsApps folder), `None` when it is not installed.
///
/// The programs are named by their full paths: a bare name is looked for in more places than Windows' own (issue 422).
@@ -250,7 +317,7 @@ fn open_terminal_admin_here(dir: &Path) -> anyhow::Result<()> {
let declined = |e: &windows::core::Error| e.code().0 as u32 == 0x8007_04C7;
// (both by their full paths: see `windows_terminal`)
let first = match windows_terminal() {
- Some(wt) => run(&wt.to_string_lossy(), &terminal_args(dir)),
+ Some(wt) => run(&wt.to_string_lossy(), &terminal_args(dir, ps_misreads(&dir.to_string_lossy()) && wt_default_is_windows_powershell())),
None => Err(windows::core::Error::from(windows::Win32::Foundation::ERROR_FILE_NOT_FOUND.to_hresult())),
};
match first {
@@ -265,17 +332,19 @@ fn open_terminal_admin_here(dir: &Path) -> anyhow::Result<()> {
}
/// `-d "C:\some dir"` for Windows Terminal. A trailing backslash would escape the closing
-/// quote (`"C:\"`), so it is doubled.
-fn terminal_args(dir: &Path) -> String {
+/// quote (`"C:\"`), so it is doubled. With `wt_ps`, for a folder Windows PowerShell would misread, the tab is given Windows
+/// PowerShell with the folder told, as in [`wt_start_args`] (issue 1091; this line was tried without the elevation only).
+fn terminal_args(dir: &Path, wt_ps: bool) -> String {
let d = wt_escaped(&dir.to_string_lossy());
let tail = if d.ends_with('\\') { "\\" } else { "" };
- format!("-d \"{d}{tail}\"")
+ let ps = if wt_ps && ps_misreads(&d) { format!(" \"{}\" {}", powershell().display(), wt_escaped(&powershell_args(dir))) } else { String::new() };
+ format!("-d \"{d}{tail}\"{ps}")
}
/// An elevated process starts in System32 whatever directory is asked for: PowerShell is told
/// to go to the folder itself (single quotes doubled, as PowerShell escapes them).
fn powershell_args(dir: &Path) -> String {
- format!("-NoExit -Command \"Set-Location -LiteralPath '{}'\"", ps_single_quoted(&dir.to_string_lossy()))
+ format!("-NoExit -Command \"{}\"", ps_go_to(&dir.to_string_lossy()))
}
/// `shell:Downloads`, `shell:startup`, `shell:sendto`… → file-system path (None for virtual
@@ -350,9 +419,9 @@ mod tests {
#[test]
fn elevated_terminal_arguments() {
- assert_eq!(super::terminal_args(Path::new(r"C:\Users\a b")), r#"-d "C:\Users\a b""#);
+ assert_eq!(super::terminal_args(Path::new(r"C:\Users\a b"), false), r#"-d "C:\Users\a b""#);
// a drive root: the backslash must not escape the closing quote
- assert_eq!(super::terminal_args(Path::new(r"D:\")), r#"-d "D:\\""#);
+ assert_eq!(super::terminal_args(Path::new(r"D:\"), false), r#"-d "D:\\""#);
assert_eq!(super::powershell_args(Path::new(r"C:\it's")), r#"-NoExit -Command "Set-Location -LiteralPath 'C:\it''s'""#);
}
@@ -366,7 +435,7 @@ mod tests {
assert_eq!(super::ps_single_quoted(&q.to_string()), format!("{q}{q}"));
}
// Windows Terminal's separator is escaped
- assert_eq!(super::terminal_args(Path::new(r"C:\a;b")), r#"-d "C:\a\;b""#);
+ assert_eq!(super::terminal_args(Path::new(r"C:\a;b"), false), r#"-d "C:\a\;b""#);
// and the programs are named by their full paths
assert!(super::powershell().is_absolute());
assert!(super::powershell().ends_with(r"WindowsPowerShell\v1.0\powershell.exe"));
@@ -379,10 +448,44 @@ mod terminal_tests {
#[test]
fn terminals_that_keep_their_own_start_folder_are_told_the_folder() {
- assert_eq!(terminal_dir_args("cmder.exe", r"C:\work"), ["/START", r"C:\work"]);
- assert_eq!(terminal_dir_args("conemu64.exe", r"C:\work"), ["-Dir", r"C:\work"]);
- assert_eq!(terminal_dir_args("wt.exe", r"C:\work"), ["-d", r"C:\work"]);
- assert!(terminal_dir_args("cmd.exe", r"C:\work").is_empty());
+ assert_eq!(terminal_dir_args("cmder.exe", r"C:\work", false), ["/START", r"C:\work"]);
+ assert_eq!(terminal_dir_args("conemu64.exe", r"C:\work", false), ["-Dir", r"C:\work"]);
+ assert_eq!(terminal_dir_args("wt.exe", r"C:\work", false), ["-d", r"C:\work"]);
+ assert!(terminal_dir_args("cmd.exe", r"C:\work", false).is_empty());
+ }
+
+ /// Issue 1091: Windows PowerShell 5.1 comes up in its own folder when it is only started in `C:\dl\[TEST]`.
+ #[test]
+ fn windows_powershell_is_told_a_folder_with_square_brackets_itself() {
+ let go = r"Set-Location -LiteralPath 'C:\dl\[TEST]'";
+ assert_eq!(terminal_dir_args("powershell.exe", r"C:\dl\[TEST]", false), ["-NoExit", "-Command", go]);
+ // any other folder: started there and nothing more, as before
+ assert_eq!(terminal_dir_args("powershell.exe", r"C:\dl\a`b", false), ["-NoExit"]);
+ assert_eq!(terminal_dir_args("pwsh.exe", r"C:\dl\[TEST]", false), ["-NoExit"]);
+ // Windows Terminal: only where its tab is Windows PowerShell
+ let ps = super::powershell().to_string_lossy().into_owned();
+ assert_eq!(terminal_dir_args("wt.exe", r"C:\dl\[TEST]", true), ["-d", r"C:\dl\[TEST]", ps.as_str(), "-NoExit", "-Command", go]);
+ assert_eq!(terminal_dir_args("wt.exe", r"C:\dl\[TEST]", false), ["-d", r"C:\dl\[TEST]"]);
+ assert_eq!(terminal_dir_args("wt.exe", r"C:\work", true), ["-d", r"C:\work"]);
+ // its separator is escaped in the command as in the folder, and a quote is doubled for PowerShell
+ let args = terminal_dir_args("wt.exe", r"C:\it's [a;b]", true);
+ assert_eq!(args[1], r"C:\it's [a\;b]");
+ assert_eq!(args[5], r"Set-Location -LiteralPath 'C:\it''s [a\;b]'");
+ // the elevated line
+ assert_eq!(
+ super::terminal_args(std::path::Path::new(r"C:\dl\[TEST]"), true),
+ format!(r#"-d "C:\dl\[TEST]" "{ps}" -NoExit -Command "{go}""#)
+ );
+ assert_eq!(super::terminal_args(std::path::Path::new(r"C:\work"), true), r#"-d "C:\work""#);
+ }
+
+ #[test]
+ fn the_default_profile_is_read_out_of_windows_terminals_settings() {
+ let text = "{\n \"$help\": \"x\",\n \"defaultProfile\": \"{61C54BBD-c2c6-5271-96e7-009a87ff44bf}\",\n \"profiles\": {}\n}";
+ assert!(super::wt_default_profile(text).is_some_and(|d| d.eq_ignore_ascii_case(super::WT_WINDOWS_POWERSHELL)));
+ assert_eq!(super::wt_default_profile("{ \"defaultProfile\" : \"Ubuntu\" }"), Some("Ubuntu"));
+ assert_eq!(super::wt_default_profile("{ \"profiles\": {} }"), None);
+ assert_eq!(super::wt_default_profile("{ \"defaultProfile\": 3 }"), None);
}
}