use super::*;
pub(super) fn apply_shell_integration_env(
cmd: &mut CommandBuilder,
shell_path: &str,
config_dir: &std::path::Path,
args: Vec<String>,
) -> Vec<String> {
if std::env::var("CROFT_SHELL_INTEGRATION").as_deref() == Ok("0") {
return args;
}
let base = std::path::Path::new(shell_path)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("");
match base {
"zsh" => {
let Ok(shim) = crate::shell_integration::ensure_zsh_shim(config_dir) else {
return args;
};
let inherited = std::env::var_os("ZDOTDIR").map(std::path::PathBuf::from);
let home = std::env::var_os("HOME")
.map(std::path::PathBuf::from)
.unwrap_or_default();
if home.as_os_str().is_empty() {
return args;
}
let user_zdotdir = crate::shell_integration::resolve_user_zdotdir(
inherited.as_deref(),
&config_dir.join("shell-integration"),
&home,
);
cmd.env("CROFT_USER_ZDOTDIR", user_zdotdir);
cmd.env("ZDOTDIR", &shim);
args
}
"bash" => {
let Ok(shim) = crate::shell_integration::ensure_bash_shim(config_dir) else {
return args;
};
if let Ok(env) = std::env::var("ENV") {
cmd.env("CROFT_BASH_ENV", env);
}
cmd.env("CROFT_BASH_INJECT", "1");
if !bash_env_injection_supported(shell_path) {
if args.iter().any(|a| a == "-l" || a == "--login") {
cmd.env("CROFT_BASH_LOGIN", "1");
}
return vec!["--rcfile".to_string(), shim.display().to_string()];
}
cmd.env("ENV", &shim);
if std::env::var_os("HISTFILE").is_none()
&& let Some(home) = std::env::var_os("HOME")
{
cmd.env(
"HISTFILE",
std::path::Path::new(&home).join(".bash_history"),
);
cmd.env("CROFT_BASH_UNEXPORT_HISTFILE", "1");
}
std::iter::once("--posix".to_string()).chain(args).collect()
}
"fish" => {
let Ok(dir) = crate::shell_integration::ensure_fish_integration(config_dir) else {
return args;
};
let inherited = std::env::var("XDG_DATA_DIRS").ok();
cmd.env(
"XDG_DATA_DIRS",
crate::shell_integration::fish_xdg_data_dirs(&dir, inherited.as_deref()),
);
cmd.env("CROFT_FISH_XDG_DATA_DIR", &dir);
args
}
_ => args,
}
}
pub(super) fn interactive_shell_command(
shell_path: &str,
config_dir: &std::path::Path,
) -> CommandBuilder {
let (program, args) = interactive_shell_invocation(shell_path);
let mut cmd = CommandBuilder::new(&program);
for a in apply_shell_integration_env(&mut cmd, shell_path, config_dir, args) {
cmd.arg(a);
}
cmd
}
pub(super) fn bash_env_injection_supported(shell_path: &str) -> bool {
let Ok(out) = std::process::Command::new(shell_path)
.args(["-c", "echo \"${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}\""])
.output()
else {
return false;
};
parse_bash_version_supported(&String::from_utf8_lossy(&out.stdout))
}
pub(super) fn parse_bash_version_supported(s: &str) -> bool {
let mut it = s.trim().split('.');
let (Some(maj), Some(min)) = (
it.next().and_then(|v| v.parse::<u32>().ok()),
it.next().and_then(|v| v.parse::<u32>().ok()),
) else {
return false;
};
maj > 4 || (maj == 4 && min >= 4)
}
pub fn interactive_shell_invocation(shell_path: &str) -> (String, Vec<String>) {
let basename = std::path::Path::new(shell_path)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(shell_path);
let supports_login_flag = matches!(
basename,
"zsh" | "bash" | "fish" | "ksh" | "mksh" | "dash" | "tcsh" | "sh"
);
let args = if supports_login_flag {
vec!["-l".to_string()]
} else {
Vec::new()
};
(shell_path.to_string(), args)
}
pub fn parse_shells(contents: &str) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = Vec::new();
for line in contents.lines() {
let line = line.trim();
if line.is_empty() || !line.starts_with('/') {
continue;
}
let base = std::path::Path::new(line)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(line)
.to_string();
if out.iter().any(|(_, b)| *b == base) {
continue;
}
out.push((line.to_string(), base));
}
out
}
pub(crate) fn apply_pane_env(cmd: &mut CommandBuilder, view_sock: Option<&std::path::Path>) {
cmd.env("TERM", "xterm-256color");
cmd.env("COLORTERM", "truecolor");
cmd.env("TERM_PROGRAM", crate::iterm2_inline::CROFT_TERM_PROGRAM);
cmd.env("TERM_PROGRAM_VERSION", env!("CARGO_PKG_VERSION"));
for host_only in HOST_TERMINAL_VARS {
cmd.env_remove(host_only);
}
cmd.env(
crate::iterm2_inline::CROFT_INLINE_IMAGES_ENV,
if pane_images_shown() { "1" } else { "0" },
);
if cfg!(target_os = "linux") {
let var = |k: &str| std::env::var(k).ok();
if let Some((key, value)) = utf8_ctype_fix(var("LC_ALL"), var("LC_CTYPE"), var("LANG")) {
cmd.env(key, value);
}
}
if view_sock.is_some()
&& std::env::var_os("GIT_SEQUENCE_EDITOR").is_none()
&& let Some(exe) = std::env::current_exe().ok().and_then(live_exe)
{
cmd.env("GIT_SEQUENCE_EDITOR", sequence_editor_command(&exe));
}
match view_sock {
Some(path) => cmd.env(crate::view_ipc::SOCK_ENV, path),
None => cmd.env_remove(crate::view_ipc::SOCK_ENV),
}
}
pub(super) const HOST_TERMINAL_VARS: &[&str] = &[
"KITTY_WINDOW_ID",
"KITTY_PID",
"GHOSTTY_RESOURCES_DIR",
"GHOSTTY_BIN_DIR",
"ITERM_SESSION_ID",
"LC_TERMINAL",
"LC_TERMINAL_VERSION",
"WEZTERM_PANE",
"WEZTERM_EXECUTABLE",
"VTE_VERSION",
];
pub(super) fn utf8_ctype_fix(
lc_all: Option<String>,
lc_ctype: Option<String>,
lang: Option<String>,
) -> Option<(&'static str, &'static str)> {
let is_utf8 = |v: &str| {
let codeset = v
.split('@')
.next()
.unwrap_or(v)
.rsplit('.')
.next()
.unwrap_or("");
v.contains('.') && matches!(codeset.to_ascii_lowercase().as_str(), "utf-8" | "utf8")
};
let bare = |v: &str| v.eq_ignore_ascii_case("utf-8") || v.eq_ignore_ascii_case("utf8");
match lc_all.filter(|v| !v.is_empty()) {
Some(v) if bare(&v) => return Some(("LC_ALL", "C.UTF-8")),
Some(_) => return None,
None => {}
}
let effective = lc_ctype
.filter(|v| !v.is_empty())
.or(lang.filter(|v| !v.is_empty()));
match effective {
Some(v) if is_utf8(&v) => None,
_ => Some(("LC_CTYPE", "C.UTF-8")),
}
}
pub(super) fn live_exe(exe: std::path::PathBuf) -> Option<std::path::PathBuf> {
if exe.exists() {
return Some(exe);
}
let replaced = std::path::PathBuf::from(exe.to_str()?.strip_suffix(" (deleted)")?);
replaced.exists().then_some(replaced)
}
pub(crate) fn sequence_editor_command(exe: &std::path::Path) -> String {
let quoted = exe.to_string_lossy().replace('\'', r"'\''");
format!("'{quoted}' edit --wait --sequence-editor")
}
pub(crate) fn apply_pane_bin(cmd: &mut CommandBuilder, bin: Option<&std::path::Path>) {
use crate::shell_integration::PANE_BIN_ENV;
let inherited = cmd.get_env(PANE_BIN_ENV).map(std::path::PathBuf::from);
let path = cmd.get_env("PATH").and_then(|path| {
let rest = std::env::split_paths(path)
.filter(|d| Some(d.as_path()) != bin && Some(d) != inherited.as_ref());
std::env::join_paths(
bin.map(std::path::Path::to_path_buf)
.into_iter()
.chain(rest),
)
.ok()
});
if let Some(path) = path {
cmd.env("PATH", path);
}
match bin {
Some(bin) => cmd.env(PANE_BIN_ENV, bin),
None => cmd.env_remove(PANE_BIN_ENV),
}
}
pub(super) fn pane_bin_dir() -> Option<std::path::PathBuf> {
let exe = live_exe(std::env::current_exe().ok()?)?;
crate::shell_integration::ensure_pane_bin(&crate::paths::croft_cache_dir(), &exe).ok()
}