#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Notice {
Osc777,
Osc9,
Osc99,
}
const WITH_777: [&str; 6] = ["ghostty", "wezterm", "foot", "rxvt", "konsole", "contour"];
impl Notice {
pub fn for_terminal(names: &str) -> Self {
let names = names.to_lowercase();
if names.contains("kitty") {
Self::Osc99
} else if WITH_777.iter().any(|t| names.contains(t)) {
Self::Osc777
} else {
Self::Osc9
}
}
}
pub fn terminal_names(var: impl Fn(&str) -> Option<String>) -> String {
let mut names: Vec<String> = ["TERM", "TERM_PROGRAM", "LC_TERMINAL"]
.iter()
.filter_map(|name| var(name))
.collect();
if var("TMUX").is_some_and(|v| !v.is_empty()) {
let asked = std::process::Command::new("tmux")
.args(["display", "-p", "#{client_termname} #{client_termtype}"])
.output();
if let Ok(output) = asked
&& output.status.success()
{
names.push(String::from_utf8_lossy(&output.stdout).trim().to_string());
}
}
names.join(" ")
}
fn clean(text: &str) -> String {
let flat: String = text
.chars()
.map(|c| if c.is_control() { ' ' } else { c })
.collect();
flat.split_whitespace().collect::<Vec<_>>().join(" ")
}
pub fn sequence(notice: Notice, title: &str, body: &str, tmux: bool) -> String {
let (title, body) = (clean(title), clean(body));
let inner = match notice {
Notice::Osc777 => format!("\x1b]777;notify;{};{body}\x1b\\", title.replace(';', ",")),
Notice::Osc9 => format!("\x1b]9;{title}: {body}\x1b\\"),
Notice::Osc99 => {
format!(
"\x1b]99;i=cellix:d=0:p=title;{title}\x1b\\\x1b]99;i=cellix:d=1:p=body;{body}\x1b\\"
)
}
};
if tmux {
format!("\x1bPtmux;{}\x1b\\", inner.replace('\x1b', "\x1b\x1b"))
} else {
inner
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_terminal_gets_the_sequence_it_reads() {
assert_eq!(
Notice::for_terminal("xterm-ghostty ghostty"),
Notice::Osc777
);
assert_eq!(
Notice::for_terminal("xterm-256color WezTerm"),
Notice::Osc777
);
assert_eq!(Notice::for_terminal("xterm-kitty"), Notice::Osc99);
assert_eq!(
Notice::for_terminal("xterm-256color iTerm.app iTerm2"),
Notice::Osc9
);
assert_eq!(Notice::for_terminal(""), Notice::Osc9);
assert_eq!(
Notice::for_terminal("tmux-256color tmux xterm-ghostty"),
Notice::Osc777
);
}
#[test]
fn a_notification_is_one_clean_sequence() {
assert_eq!(
sequence(Notice::Osc777, "Cellix · api", "Allow Bash?", false),
"\x1b]777;notify;Cellix · api;Allow Bash?\x1b\\"
);
assert_eq!(
sequence(Notice::Osc9, "Cellix · api", "Plan ready", false),
"\x1b]9;Cellix · api: Plan ready\x1b\\"
);
assert_eq!(
sequence(Notice::Osc777, "a;b", "run\x1b]0;x\x07 now\nplease", false),
"\x1b]777;notify;a,b;run ]0;x now please\x1b\\"
);
let kitty = sequence(Notice::Osc99, "Cellix", "Done", false);
assert!(kitty.contains("p=title;Cellix\x1b\\") && kitty.contains("p=body;Done\x1b\\"));
}
#[test]
fn inside_tmux_it_goes_past_tmux() {
assert_eq!(
sequence(Notice::Osc9, "Cellix", "Done", true),
"\x1bPtmux;\x1b\x1b]9;Cellix: Done\x1b\x1b\\\x1b\\"
);
}
}