chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
commit
7e7d249099
1134 files changed
+433629
No files matched your search
@@ -0,0 +1,420 @@
|
||||
#!/bin/bash
|
||||
|
||||
if [[ "$-" != *i* ]] ; then builtin return; fi # check in interactive mode
|
||||
if [[ -z "$KITTY_SHELL_INTEGRATION" ]]; then builtin return; fi
|
||||
|
||||
# Load the normal bash startup files
|
||||
if [[ -n "$KITTY_BASH_INJECT" ]]; then
|
||||
builtin declare kitty_bash_inject="$KITTY_BASH_INJECT"
|
||||
builtin declare ksi_val="$KITTY_SHELL_INTEGRATION"
|
||||
builtin unset KITTY_SHELL_INTEGRATION # ensure manual sourcing of this file in bashrc does not have any effect
|
||||
builtin unset KITTY_BASH_INJECT ENV
|
||||
if [[ -z "$HOME" ]]; then HOME=~; fi
|
||||
if [[ -z "$KITTY_BASH_ETC_LOCATION" ]]; then KITTY_BASH_ETC_LOCATION="/etc"; fi
|
||||
|
||||
_ksi_sourceable() {
|
||||
[[ -f "$1" && -r "$1" ]] && builtin return 0; builtin return 1;
|
||||
}
|
||||
|
||||
if [[ -n "$ksi_val" && "$ksi_val" != *no-sudo* && -n "$TERMINFO" && ! ( -r "/usr/share/terminfo/x/xterm-kitty" || -r "/usr/share/terminfo/78/xterm-kitty" ) ]]; then
|
||||
# this must be done before sourcing user bashrc otherwise aliasing of sudo does not work
|
||||
sudo() {
|
||||
# Ensure terminfo is available in sudo
|
||||
builtin local cannot_set_env_var="n"
|
||||
builtin local ignore_arg="n"
|
||||
for arg; do
|
||||
if [[ "$ignore_arg" == "y" ]]; then ignore_arg="n"; builtin continue; fi
|
||||
case "$arg" in
|
||||
--) builtin break ;; # end of options
|
||||
# sudo -e disallows setting env vars
|
||||
--edit | -e* | -[!-]*e*) cannot_set_env_var="y"; builtin break ;;
|
||||
# sudo-rs -v disallows setting env vars
|
||||
--validate | -v* | -[!-]*v*) cannot_set_env_var="y"; builtin break ;;
|
||||
# flags that require a following argument
|
||||
--user|--group|--host|--chdir|--chroot|--role|--type|--command-timeout|--auth-type|--login-class|--prompt|--close-from|--other-user) ignore_arg="y" ;;
|
||||
--*) ;; # misc long opt
|
||||
-*a|-*C|-*c|-*D|-*g|-*h|-*p|-*R|-*r|-*t|-*T|-*u) ignore_arg="y" ;;
|
||||
# flag or env var setting
|
||||
-* | *=*) ;;
|
||||
*) builtin break ;; # command found
|
||||
esac
|
||||
done
|
||||
if [[ "$cannot_set_env_var" == "y" ]]; then
|
||||
builtin command sudo "$@";
|
||||
else
|
||||
builtin command sudo TERMINFO="$TERMINFO" "$@";
|
||||
fi
|
||||
}
|
||||
if builtin type -P run0 >/dev/null 2>&1; then
|
||||
run0() {
|
||||
# Ensure terminfo is available in run0, --setenv=NAME copies NAME from the current env
|
||||
builtin command run0 --setenv=TERMINFO "$@";
|
||||
}
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ "$kitty_bash_inject" == *"posix"* ]]; then
|
||||
_ksi_sourceable "$KITTY_BASH_POSIX_ENV" && {
|
||||
builtin source "$KITTY_BASH_POSIX_ENV"
|
||||
builtin export ENV="$KITTY_BASH_POSIX_ENV"
|
||||
}
|
||||
else
|
||||
builtin set +o posix
|
||||
builtin shopt -u inherit_errexit 2>/dev/null # resetting posix does not clear this
|
||||
if [[ -n "$KITTY_BASH_UNEXPORT_HISTFILE" ]]; then
|
||||
builtin export -n HISTFILE
|
||||
builtin unset KITTY_BASH_UNEXPORT_HISTFILE
|
||||
fi
|
||||
|
||||
# See run_startup_files() in shell.c in the Bash source code
|
||||
if builtin shopt -q login_shell; then
|
||||
if [[ "$kitty_bash_inject" != *"no-profile"* ]]; then
|
||||
_ksi_sourceable "$KITTY_BASH_ETC_LOCATION/profile" && builtin source "$KITTY_BASH_ETC_LOCATION/profile"
|
||||
for _ksi_i in "$HOME/.bash_profile" "$HOME/.bash_login" "$HOME/.profile"; do
|
||||
_ksi_sourceable "$_ksi_i" && { builtin source "$_ksi_i"; break; }
|
||||
done
|
||||
fi
|
||||
else
|
||||
if [[ "$kitty_bash_inject" != *"no-rc"* ]]; then
|
||||
# Linux distros build bash with -DSYS_BASHRC. Unfortunately, there is
|
||||
# no way to probe bash for it and different distros use different files
|
||||
# Arch, Debian, Ubuntu use /etc/bash.bashrc
|
||||
# Fedora uses /etc/bashrc sourced from ~/.bashrc instead of SYS_BASHRC
|
||||
# Void Linux uses /etc/bash/bashrc
|
||||
for _ksi_i in "$KITTY_BASH_ETC_LOCATION/bash.bashrc" "$KITTY_BASH_ETC_LOCATION/bash/bashrc" ; do
|
||||
_ksi_sourceable "$_ksi_i" && { builtin source "$_ksi_i"; break; }
|
||||
done
|
||||
if [[ -z "$KITTY_BASH_RCFILE" ]]; then KITTY_BASH_RCFILE="$HOME/.bashrc"; fi
|
||||
_ksi_sourceable "$KITTY_BASH_RCFILE" && builtin source "$KITTY_BASH_RCFILE"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
builtin unset KITTY_BASH_RCFILE KITTY_BASH_POSIX_ENV KITTY_BASH_ETC_LOCATION
|
||||
builtin unset -f _ksi_sourceable
|
||||
builtin export KITTY_SHELL_INTEGRATION="$ksi_val"
|
||||
builtin unset _ksi_i ksi_val kitty_bash_inject
|
||||
fi
|
||||
|
||||
|
||||
if [ "${BASH_VERSINFO:-0}" -lt 4 ]; then
|
||||
builtin unset KITTY_SHELL_INTEGRATION
|
||||
builtin printf "%s\n" "Bash version ${BASH_VERSION} too old, kitty shell integration disabled" > /dev/stderr
|
||||
builtin return
|
||||
fi
|
||||
|
||||
if [ -v "_ksi_prompt[sourced]" ]; then
|
||||
# we have already run
|
||||
builtin unset KITTY_SHELL_INTEGRATION
|
||||
builtin return
|
||||
fi
|
||||
|
||||
# this is defined outside _ksi_main to make it global without using declare -g
|
||||
# which is not available on older bash
|
||||
builtin declare -A _ksi_prompt
|
||||
_ksi_prompt=(
|
||||
[cursor]='y' [title]='y' [mark]='y' [complete]='y' [cwd]='y' [sudo]='y' [ps0]='' [ps0_suffix]='' [ps1]='' [ps1_suffix]='' [ps2]=''
|
||||
[hostname_prefix]='' [sourced]='y' [last_reported_cwd]=''
|
||||
)
|
||||
|
||||
_ksi_main() {
|
||||
builtin local ifs="$IFS" i
|
||||
IFS=" "
|
||||
for i in ${KITTY_SHELL_INTEGRATION[@]}; do
|
||||
case "$i" in
|
||||
"no-cursor") _ksi_prompt[cursor]='n';;
|
||||
"no-title") _ksi_prompt[title]='n';;
|
||||
"no-prompt-mark") _ksi_prompt[mark]='n';;
|
||||
"no-complete") _ksi_prompt[complete]='n';;
|
||||
"no-cwd") _ksi_prompt[cwd]='n';;
|
||||
"no-sudo") _ksi_prompt[sudo]='n';;
|
||||
esac
|
||||
done
|
||||
IFS="$ifs"
|
||||
|
||||
builtin unset KITTY_SHELL_INTEGRATION
|
||||
if [[ -n "$SSH_KITTEN_KITTY_DIR" ]]; then
|
||||
if [[ ! "$PATH" =~ (^|:)${SSH_KITTEN_KITTY_DIR}(:|$) ]] && [[ -z "$(builtin command -v kitten)" ]]; then
|
||||
builtin export PATH="${PATH}:${SSH_KITTEN_KITTY_DIR}"
|
||||
fi
|
||||
builtin unset SSH_KITTEN_KITTY_DIR
|
||||
fi
|
||||
builtin local krcs="$KITTY_SI_RUN_COMMAND_AT_STARTUP"
|
||||
builtin unset KITTY_SI_RUN_COMMAND_AT_STARTUP
|
||||
|
||||
_ksi_debug_print() {
|
||||
# print a line to STDERR of parent kitty process
|
||||
builtin local b
|
||||
b=$(builtin command base64 <<< "${@}")
|
||||
builtin printf "\eP@kitty-print|%s\e\\" "${b//[[:space:]]}}"
|
||||
}
|
||||
|
||||
_ksi_set_mark() {
|
||||
_ksi_prompt["${1}_mark"]="\[\e]133;k;${1}_kitty\a\]"
|
||||
}
|
||||
|
||||
_ksi_set_mark start
|
||||
_ksi_set_mark end
|
||||
_ksi_set_mark start_secondary
|
||||
_ksi_set_mark end_secondary
|
||||
_ksi_set_mark start_suffix
|
||||
_ksi_set_mark end_suffix
|
||||
builtin unset -f _ksi_set_mark
|
||||
_ksi_prompt[secondary_prompt]="\n${_ksi_prompt[start_secondary_mark]}\[\e]133;A;k=s\a\]${_ksi_prompt[end_secondary_mark]}"
|
||||
|
||||
_ksi_prompt_command() {
|
||||
# we first remove any previously added kitty code from the prompt variables and then add
|
||||
# it back, to ensure we have only a single instance
|
||||
if [[ -n "${_ksi_prompt[ps0]}" ]]; then
|
||||
PS0=${PS0//\\\[\\e\]133;k;start_kitty\\a\\\]*end_kitty\\a\\\]}
|
||||
PS0="${_ksi_prompt[ps0]}$PS0"
|
||||
fi
|
||||
if [[ -n "${_ksi_prompt[ps0_suffix]}" ]]; then
|
||||
PS0=${PS0//\\\[\\e\]133;k;start_suffix_kitty\\a\\\]*end_suffix_kitty\\a\\\]}
|
||||
PS0="${PS0}${_ksi_prompt[ps0_suffix]}"
|
||||
fi
|
||||
# restore PS1 to its pristine state without our additions
|
||||
if [[ -n "${_ksi_prompt[ps1]}" ]]; then
|
||||
PS1=${PS1//\\\[\\e\]133;k;start_kitty\\a\\\]*end_kitty\\a\\\]}
|
||||
PS1=${PS1//\\\[\\e\]133;k;start_secondary_kitty\\a\\\]*end_secondary_kitty\\a\\\]}
|
||||
fi
|
||||
if [[ -n "${_ksi_prompt[ps1_suffix]}" ]]; then
|
||||
PS1=${PS1//\\\[\\e\]133;k;start_suffix_kitty\\a\\\]*end_suffix_kitty\\a\\\]}
|
||||
fi
|
||||
if [[ -n "${_ksi_prompt[ps1]}" ]]; then
|
||||
if [[ "${_ksi_prompt[mark]}" == "y" && ( "${PS1}" == *"\n"* || "${PS1}" == *$'\n'* ) ]]; then
|
||||
builtin local oldval
|
||||
oldval=$(builtin shopt -p extglob)
|
||||
builtin shopt -s extglob
|
||||
# bash does not redraw the leading lines in a multiline prompt so
|
||||
# mark the last line as a secondary prompt. Otherwise on resize the
|
||||
# lines before the last line will be erased by kitty.
|
||||
# the first part removes everything from the last \n onwards
|
||||
# the second part appends a newline with the secondary marking
|
||||
# the third part appends everything after the last newline
|
||||
PS1=${PS1%@('\n'|$'\n')*}${_ksi_prompt[secondary_prompt]}${PS1##*@('\n'|$'\n')}
|
||||
builtin eval "$oldval"
|
||||
fi
|
||||
PS1="${_ksi_prompt[ps1]}$PS1"
|
||||
fi
|
||||
if [[ -n "${_ksi_prompt[ps1_suffix]}" ]]; then
|
||||
PS1="${PS1}${_ksi_prompt[ps1_suffix]}"
|
||||
fi
|
||||
if [[ -n "${_ksi_prompt[ps2]}" ]]; then
|
||||
PS2=${PS2//\\\[\\e\]133;k;start_kitty\\a\\\]*end_kitty\\a\\\]}
|
||||
PS2="${_ksi_prompt[ps2]}$PS2"
|
||||
fi
|
||||
|
||||
if [[ "${_ksi_prompt[cwd]}" == "y" ]]; then
|
||||
# unfortunately bash provides no hooks to detect cwd changes
|
||||
# in particular this means cwd reporting will not happen for a
|
||||
# command like cd /test && cat. PS0 is evaluated before cd is run.
|
||||
if [[ "${_ksi_prompt[last_reported_cwd]}" != "$PWD" ]]; then
|
||||
_ksi_prompt[last_reported_cwd]="$PWD"
|
||||
builtin printf "\e]7;kitty-shell-cwd://%s%s\a" "$HOSTNAME" "$PWD"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
if [[ "${_ksi_prompt[cursor]}" == "y" ]]; then
|
||||
_ksi_prompt[ps1_suffix]+="\[\e[5 q\]" # blinking bar cursor
|
||||
_ksi_prompt[ps0_suffix]+="\[\e[0 q\]" # blinking default cursor
|
||||
fi
|
||||
|
||||
if [[ "${_ksi_prompt[title]}" == "y" || "${_ksi_prompt[mark]}" == "y" ]]; then
|
||||
_ksi_get_current_command() {
|
||||
builtin local last_cmd
|
||||
last_cmd=$(HISTTIMEFORMAT= builtin history 1)
|
||||
last_cmd="${last_cmd#*[[:digit:]]*[[:space:]]}" # remove leading history number
|
||||
last_cmd="${last_cmd#"${last_cmd%%[![:space:]]*}"}" # remove remaining leading whitespace
|
||||
if [[ "${_ksi_prompt[title]}" == "y" ]]; then
|
||||
builtin printf "\e]2;%s%s\a" "${_ksi_prompt[hostname_prefix]@P}" "${last_cmd//[[:cntrl:]]}" # removes any control characters
|
||||
fi
|
||||
if [[ "${_ksi_prompt[mark]}" == "y" ]]; then
|
||||
builtin printf "\e]133;C;cmdline=%q\a" "$last_cmd"
|
||||
fi
|
||||
}
|
||||
_ksi_prompt[ps0]+='$(_ksi_get_current_command > /dev/tty)';
|
||||
fi
|
||||
|
||||
if [[ "${_ksi_prompt[title]}" == "y" ]]; then
|
||||
if [[ -z "$KITTY_PID" ]]; then
|
||||
if [[ -n "$SSH_TTY" || -n "$SSH2_TTY$KITTY_WINDOW_ID" ]]; then
|
||||
# connected to most SSH servers
|
||||
# or use ssh kitten to connected to some SSH servers that do not set SSH_TTY
|
||||
_ksi_prompt[hostname_prefix]="\h: "
|
||||
elif [[ -n "$(builtin command -v who)" && "$(builtin command who -m 2> /dev/null)" =~ \([a-fA-F.:0-9]+\)$ ]]; then
|
||||
# the shell integration script is installed manually on the remote system
|
||||
# the environment variables are cleared after sudo
|
||||
# OpenSSH's sshd creates entries in utmp for every login so use those
|
||||
_ksi_prompt[hostname_prefix]="\h: "
|
||||
fi
|
||||
fi
|
||||
# see https://www.gnu.org/software/bash/manual/html_node/Controlling-the-Prompt.html#Controlling-the-Prompt
|
||||
# we use suffix here because some distros add title setting to their bashrc files by default
|
||||
_ksi_prompt[ps1_suffix]+="\[\e]2;${_ksi_prompt[hostname_prefix]}\w\a\]"
|
||||
if [[ "$HISTCONTROL" == *"ignoreboth"* ]] || [[ "$HISTCONTROL" == *"ignorespace"* ]]; then
|
||||
_ksi_debug_print "ignoreboth or ignorespace present in bash HISTCONTROL setting, showing running command will not be robust"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ "${_ksi_prompt[mark]}" == "y" ]]; then
|
||||
# this can result in multiple D prompt marks or ones that dont
|
||||
# correspond to a cmd but kitty handles this gracefully, only
|
||||
# taking into account the first D after a C.
|
||||
_ksi_prompt[ps1]+="\[\e]133;D;\$?\a\e]133;A\a\]"
|
||||
_ksi_prompt[ps2]+="\[\e]133;A;k=s\a\]"
|
||||
fi
|
||||
|
||||
builtin alias edit-in-kitty="kitten edit-in-kitty"
|
||||
|
||||
|
||||
if [[ "${_ksi_prompt[complete]}" == "y" ]]; then
|
||||
_ksi_completions() {
|
||||
builtin local src
|
||||
builtin local limit
|
||||
# Send all words up to the word the cursor is currently on
|
||||
builtin let limit=1+$COMP_CWORD
|
||||
src=$(builtin printf "%s\n" "${COMP_WORDS[@]:0:$limit}" | builtin command kitten __complete__ bash)
|
||||
if [[ $? == 0 ]]; then
|
||||
builtin eval "${src}"
|
||||
fi
|
||||
}
|
||||
builtin complete -F _ksi_completions kitty
|
||||
builtin complete -F _ksi_completions edit-in-kitty
|
||||
builtin complete -F _ksi_completions clone-in-kitty
|
||||
builtin complete -F _ksi_completions kitten
|
||||
fi
|
||||
|
||||
# wrap our prompt additions in markers we can use to remove them using
|
||||
# bash's anemic pattern substitution
|
||||
if [[ -n "${_ksi_prompt[ps0]}" ]]; then
|
||||
_ksi_prompt[ps0]="${_ksi_prompt[start_mark]}${_ksi_prompt[ps0]}${_ksi_prompt[end_mark]}"
|
||||
fi
|
||||
if [[ -n "${_ksi_prompt[ps0_suffix]}" ]]; then
|
||||
_ksi_prompt[ps0_suffix]="${_ksi_prompt[start_suffix_mark]}${_ksi_prompt[ps0_suffix]}${_ksi_prompt[end_suffix_mark]}"
|
||||
fi
|
||||
if [[ -n "${_ksi_prompt[ps1]}" ]]; then
|
||||
_ksi_prompt[ps1]="${_ksi_prompt[start_mark]}${_ksi_prompt[ps1]}${_ksi_prompt[end_mark]}"
|
||||
fi
|
||||
if [[ -n "${_ksi_prompt[ps1_suffix]}" ]]; then
|
||||
_ksi_prompt[ps1_suffix]="${_ksi_prompt[start_suffix_mark]}${_ksi_prompt[ps1_suffix]}${_ksi_prompt[end_suffix_mark]}"
|
||||
fi
|
||||
if [[ -n "${_ksi_prompt[ps2]}" ]]; then
|
||||
_ksi_prompt[ps2]="${_ksi_prompt[start_mark]}${_ksi_prompt[ps2]}${_ksi_prompt[end_mark]}"
|
||||
fi
|
||||
# BASH aborts the entire script when doing unset with failglob set, somebody should report this upstream
|
||||
builtin local oldval
|
||||
oldval=$(builtin shopt -p failglob)
|
||||
builtin shopt -u failglob
|
||||
builtin unset _ksi_prompt[start_mark] _ksi_prompt[end_mark] _ksi_prompt[start_suffix_mark] _ksi_prompt[end_suffix_mark] _ksi_prompt[start_secondary_mark] _ksi_prompt[end_secondary_mark]
|
||||
builtin eval "$oldval"
|
||||
|
||||
# install our prompt command, using an array if it is unset or already an array,
|
||||
# otherwise append a string. We check if _ksi_prompt_command exists as some shell
|
||||
# scripts stupidly export PROMPT_COMMAND making it inherited by all programs launched
|
||||
# from the shell
|
||||
builtin local pc
|
||||
pc='builtin declare -F _ksi_prompt_command > /dev/null 2> /dev/null && _ksi_prompt_command'
|
||||
if [[ -z "${PROMPT_COMMAND[*]}" ]]; then
|
||||
PROMPT_COMMAND=([0]="$pc")
|
||||
elif [[ $(builtin declare -p PROMPT_COMMAND 2> /dev/null) =~ 'declare -a PROMPT_COMMAND' ]]; then
|
||||
PROMPT_COMMAND+=("$pc")
|
||||
else
|
||||
builtin local oldval
|
||||
oldval=$(builtin shopt -p extglob)
|
||||
builtin shopt -s extglob
|
||||
PROMPT_COMMAND="${PROMPT_COMMAND%%+([[:space:]])}"
|
||||
PROMPT_COMMAND="${PROMPT_COMMAND%%+(;)}"
|
||||
builtin eval "$oldval"
|
||||
PROMPT_COMMAND+="; $pc"
|
||||
fi
|
||||
if [ -n "${KITTY_IS_CLONE_LAUNCH}" ]; then
|
||||
builtin local orig_conda_env="$CONDA_DEFAULT_ENV"
|
||||
builtin eval "${KITTY_IS_CLONE_LAUNCH}"
|
||||
builtin hash -r 2> /dev/null 1> /dev/null
|
||||
builtin local venv="${VIRTUAL_ENV}/bin/activate"
|
||||
builtin local sourced=""
|
||||
_ksi_s_is_ok() {
|
||||
[[ -z "$sourced" && "$KITTY_CLONE_SOURCE_STRATEGIES" == *",$1,"* ]] && builtin return 0
|
||||
builtin return 1
|
||||
}
|
||||
|
||||
if _ksi_s_is_ok "venv" && [ -n "${VIRTUAL_ENV}" -a -r "$venv" ]; then
|
||||
sourced="y"
|
||||
builtin unset VIRTUAL_ENV
|
||||
builtin source "$venv"
|
||||
fi; if _ksi_s_is_ok "conda" && [ -n "${CONDA_DEFAULT_ENV}" ] && builtin command -v conda >/dev/null 2>/dev/null && [ "${CONDA_DEFAULT_ENV}" != "$orig_conda_env" ]; then
|
||||
sourced="y"
|
||||
conda activate "${CONDA_DEFAULT_ENV}"
|
||||
fi; if _ksi_s_is_ok "env_var" && [[ -n "${KITTY_CLONE_SOURCE_CODE}" ]]; then
|
||||
sourced="y"
|
||||
builtin eval "${KITTY_CLONE_SOURCE_CODE}"
|
||||
fi; if _ksi_s_is_ok "path" && [[ -r "${KITTY_CLONE_SOURCE_PATH}" ]]; then
|
||||
sourced="y"
|
||||
builtin source "${KITTY_CLONE_SOURCE_PATH}"
|
||||
fi
|
||||
builtin unset -f _ksi_s_is_ok
|
||||
# Ensure PATH has no duplicate entries
|
||||
if [ -n "$PATH" ]; then
|
||||
builtin local old_PATH=$PATH:; PATH=
|
||||
while [ -n "$old_PATH" ]; do
|
||||
builtin local x
|
||||
x=${old_PATH%%:*}
|
||||
case $PATH: in
|
||||
*:"$x":*) ;;
|
||||
*) PATH=$PATH:$x;;
|
||||
esac
|
||||
old_PATH=${old_PATH#*:}
|
||||
done
|
||||
PATH=${PATH#:}
|
||||
fi
|
||||
fi
|
||||
builtin unset KITTY_IS_CLONE_LAUNCH KITTY_CLONE_SOURCE_STRATEGIES
|
||||
if [[ -n "$krcs" ]]; then builtin
|
||||
builtin printf "\e]2;%s\a" "${krcs//[[:cntrl:]]}" # removes any control characters
|
||||
eval "$krcs";
|
||||
fi
|
||||
}
|
||||
_ksi_main
|
||||
builtin unset -f _ksi_main
|
||||
|
||||
case :$SHELLOPTS: in
|
||||
*:posix:*) ;;
|
||||
*)
|
||||
|
||||
_ksi_transmit_data() {
|
||||
builtin local data
|
||||
data="${1//[[:space:]]}"
|
||||
builtin local pos=0
|
||||
builtin local chunk_num=0
|
||||
while [ $pos -lt ${#data} ]; do
|
||||
builtin local chunk="${data:$pos:2048}"
|
||||
pos=$(($pos+2048))
|
||||
builtin printf '\eP@kitty-%s|%s:%s\e\\' "${2}" "${chunk_num}" "${chunk}"
|
||||
chunk_num=$(($chunk_num+1))
|
||||
done
|
||||
# save history so it is available in new shell
|
||||
[ "$3" = "save_history" ] && builtin history -a
|
||||
builtin printf '\eP@kitty-%s|\e\\' "${2}"
|
||||
}
|
||||
|
||||
clone-in-kitty() {
|
||||
builtin local bv="${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}.${BASH_VERSINFO[2]}"
|
||||
builtin local data="shell=bash,pid=$$,bash_version=$bv,cwd=$(builtin printf "%s" "$PWD" | builtin command base64),envfmt=bash,env=$(builtin export | builtin command base64)"
|
||||
while :; do
|
||||
case "$1" in
|
||||
"") break;;
|
||||
-h|--help)
|
||||
builtin printf "%s\n\n%s\n" "Clone the current bash session into a new kitty window." "For usage instructions see: https://sw.kovidgoyal.net/kitty/shell-integration/#clone-shell"
|
||||
builtin return
|
||||
;;
|
||||
*) data="$data,a=$(builtin printf "%s" "$1" | builtin command base64)";;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
_ksi_transmit_data "$data" "clone" "save_history"
|
||||
}
|
||||
|
||||
;;
|
||||
esac
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
function __ksi_completions
|
||||
set --local ct (commandline --current-token)
|
||||
set --local tokens (commandline --tokenize --cut-at-cursor --current-process)
|
||||
printf "%s\n" $tokens $ct | command kitten __complete__ fish | source -
|
||||
end
|
||||
|
||||
complete -f -c clone-in-kitty -a "(__ksi_completions)"
|
||||
@@ -0,0 +1,7 @@
|
||||
function __ksi_completions
|
||||
set --local ct (commandline --current-token)
|
||||
set --local tokens (commandline --tokenize --cut-at-cursor --current-process)
|
||||
printf "%s\n" $tokens $ct | command kitten __complete__ fish | source -
|
||||
end
|
||||
|
||||
complete -f -c kitten -a "(__ksi_completions)"
|
||||
@@ -0,0 +1,7 @@
|
||||
function __ksi_completions
|
||||
set --local ct (commandline --current-token)
|
||||
set --local tokens (commandline --tokenize --cut-at-cursor --current-process)
|
||||
printf "%s\n" $tokens $ct | command kitten __complete__ fish | source -
|
||||
end
|
||||
|
||||
complete -f -c kitty -a "(__ksi_completions)"
|
||||
@@ -0,0 +1,282 @@
|
||||
#!/bin/fish
|
||||
|
||||
# To use fish's autoloading feature, kitty prepends the vendored integration script directory to XDG_DATA_DIRS.
|
||||
# The original paths needs to be restored here to not affect other programs.
|
||||
# In particular, if the original XDG_DATA_DIRS does not exist, it needs to be removed.
|
||||
if set -q KITTY_FISH_XDG_DATA_DIR
|
||||
if set -q XDG_DATA_DIRS
|
||||
set --global --export --path XDG_DATA_DIRS "$XDG_DATA_DIRS"
|
||||
if set --local index (contains --index "$KITTY_FISH_XDG_DATA_DIR" $XDG_DATA_DIRS)
|
||||
set --erase --global XDG_DATA_DIRS[$index]
|
||||
test -n "$XDG_DATA_DIRS" || set --erase --global XDG_DATA_DIRS
|
||||
end
|
||||
if set -q XDG_DATA_DIRS
|
||||
set --global --export --unpath XDG_DATA_DIRS "$XDG_DATA_DIRS"
|
||||
end
|
||||
end
|
||||
set --erase KITTY_FISH_XDG_DATA_DIR
|
||||
end
|
||||
|
||||
status is-interactive || exit 0
|
||||
not functions -q __ksi_schedule || exit 0
|
||||
# Check fish version 3.3.0+ efficiently and fallback to check the minimum working version 3.2.0, exit on outdated versions.
|
||||
# "Warning: Update fish to version 3.3.0+ to enable kitty shell integration.\n"
|
||||
set -q fish_killring || set -q status_generation || string match -qnv "3.1.*" "$version"
|
||||
or echo -en \eP@kitty-print\|V2FybmluZzogVXBkYXRlIGZpc2ggdG8gdmVyc2lvbiAzLjMuMCsgdG8gZW5hYmxlIGtpdHR5IHNoZWxsIGludGVncmF0aW9uLgo=\e\\ && exit 0 || exit 0
|
||||
|
||||
|
||||
if test -n "$KITTY_SI_RUN_COMMAND_AT_STARTUP"
|
||||
printf '\e]2;%s\a' (string replace -ra '[\x00-\x1F\x7F]' '' -- "$KITTY_SI_RUN_COMMAND_AT_STARTUP")
|
||||
set --local _krcs "$KITTY_SI_RUN_COMMAND_AT_STARTUP"
|
||||
set --erase KITTY_SI_RUN_COMMAND_AT_STARTUP
|
||||
eval "$_krcs"
|
||||
end
|
||||
|
||||
function __ksi_schedule --on-event fish_prompt -d "Setup kitty integration after other scripts have run, we hope"
|
||||
functions --erase __ksi_schedule
|
||||
test -n "$KITTY_SHELL_INTEGRATION" || return 0
|
||||
set --local _ksi (string split " " -- "$KITTY_SHELL_INTEGRATION")
|
||||
set --erase KITTY_SHELL_INTEGRATION
|
||||
if test -n "$SSH_KITTEN_KITTY_DIR"
|
||||
if not contains -- "$SSH_KITTEN_KITTY_DIR" "$PATH"
|
||||
if not type kitten 2> /dev/null > /dev/null
|
||||
set -gx PATH "$PATH" "$SSH_KITTEN_KITTY_DIR"
|
||||
end
|
||||
end
|
||||
set --erase SSH_KITTEN_KITTY_DIR
|
||||
end
|
||||
# Enable cursor shape changes for default mode and vi mode
|
||||
if not contains "no-cursor" $_ksi
|
||||
function __ksi_set_cursor --on-variable fish_key_bindings -d "Set the cursor shape for different modes when switching key bindings"
|
||||
if test "$fish_key_bindings" = fish_default_key_bindings
|
||||
function __ksi_bar_cursor --on-event fish_prompt -d "Set cursor shape to blinking bar on prompt"
|
||||
echo -en "\e[5 q"
|
||||
end
|
||||
# Change the cursor shape on first run
|
||||
set -q argv[1]
|
||||
and __ksi_bar_cursor
|
||||
else
|
||||
functions --erase __ksi_bar_cursor
|
||||
contains "$fish_key_bindings" fish_vi_key_bindings fish_hybrid_key_bindings
|
||||
and __ksi_set_vi_cursor
|
||||
end
|
||||
end
|
||||
|
||||
function __ksi_set_vi_cursor -d "Set the vi mode cursor shapes"
|
||||
# Set the vi mode cursor shapes only when none of them are configured
|
||||
set --local vi_modes fish_cursor_{default,insert,replace_one,visual}
|
||||
set -q $vi_modes
|
||||
test "$status" -eq 4 || return
|
||||
|
||||
set --local vi_cursor_shapes block line underscore block
|
||||
for i in 1 2 3 4
|
||||
set --global $vi_modes[$i] $vi_cursor_shapes[$i] blink
|
||||
end
|
||||
|
||||
# Change the cursor shape for current mode
|
||||
test "$fish_bind_mode" = "insert" && echo -en "\e[5 q" || echo -en "\e[1 q"
|
||||
end
|
||||
|
||||
function __ksi_default_cursor --on-event fish_preexec -d "Set cursor shape to blinking default shape before executing command"
|
||||
echo -en "\e[0 q"
|
||||
end
|
||||
|
||||
__ksi_set_cursor init
|
||||
end
|
||||
|
||||
# Enable prompt marking with OSC 133
|
||||
if not contains "no-prompt-mark" $_ksi and not set -q __ksi_prompt_state
|
||||
set --local suffix ''
|
||||
if bind --function-names | string match -q forward-char-passive
|
||||
set suffix '-passive'
|
||||
end
|
||||
# fish 3.8 emits prompt markers, so we don't need to. It also is the
|
||||
# first version to define forward-char-passive so use that as a test to detect it
|
||||
if test "$suffix" = ""
|
||||
function __ksi_mark_prompt_start --on-event fish_prompt --on-event fish_cancel --on-event fish_posterror
|
||||
test "$__ksi_prompt_state" != prompt-start
|
||||
and echo -en "\e]133;D\a"
|
||||
set --global __ksi_prompt_state prompt-start
|
||||
echo -en "\e]133;A;special_key=1\a"
|
||||
end
|
||||
__ksi_mark_prompt_start
|
||||
|
||||
function __ksi_mark_output_start --on-event fish_preexec
|
||||
set --global __ksi_prompt_state pre-exec
|
||||
printf '\e]133;C;cmdline_url=%s\a' (string escape --style=url -- "$argv")
|
||||
end
|
||||
|
||||
function __ksi_mark_output_end --on-event fish_postexec
|
||||
set --global __ksi_prompt_state post-exec
|
||||
echo -en "\e]133;D;$status\a"
|
||||
end
|
||||
|
||||
# With prompt marking, kitty clears the current prompt on resize,
|
||||
# so we need fish to redraw it.
|
||||
set --global fish_handle_reflow 1
|
||||
end
|
||||
|
||||
# Binding for special key to move cursor on mouse click without triggering any
|
||||
# autocompletion or other effects
|
||||
for mode in (bind --list-modes | string match -v paste) # bind in all modes except paste
|
||||
bind --preset -M "$mode" \e\[1u "forward-char$suffix"
|
||||
bind --preset -M "$mode" \e\[1\;1u "backward-char$suffix"
|
||||
end
|
||||
end
|
||||
|
||||
# Enable CWD reporting
|
||||
if not contains "no-cwd" $_ksi
|
||||
# This function name is from fish and will override the builtin one, which is enabled by default for kitty in fish 3.5.0+.
|
||||
# We provide this to ensure that fish 3.2.0 and above will work.
|
||||
# https://github.com/fish-shell/fish-shell/blob/3.2.0/share/functions/__fish_config_interactive.fish#L275
|
||||
# An executed program could change cwd and report the changed cwd, so also report cwd at each new prompt
|
||||
function __update_cwd_osc --on-variable PWD --on-event fish_prompt -d "Report PWD changes to kitty"
|
||||
status is-command-substitution
|
||||
or echo -en "\e]7;kitty-shell-cwd://$hostname$PWD\a"
|
||||
end
|
||||
__update_cwd_osc
|
||||
end
|
||||
|
||||
# Note that neither alias nor function is recursive in fish so if the user defines an alias/function
|
||||
# for sudo/run0 it will be clobbered by us, so only install these if they are not already functions
|
||||
if not contains "no-sudo" $_ksi
|
||||
and test -n "$TERMINFO"
|
||||
and not test -r "/usr/share/terminfo/x/xterm-kitty" -o -r "/usr/share/terminfo/78/xterm-kitty"
|
||||
if test "file" = (type -t sudo 2> /dev/null || echo "x")
|
||||
# Ensure terminfo is available in sudo
|
||||
function sudo
|
||||
set --local cannot_set_env_var "n"
|
||||
set --local ignore_arg "n"
|
||||
for arg in $argv
|
||||
if string match -q -- "$ignore_arg" "y"
|
||||
set ignore_arg "n"
|
||||
continue
|
||||
end
|
||||
if string match -r -q -- '^--$' "$arg"
|
||||
break # end of options
|
||||
end
|
||||
if string match -r -q -- '^-[^-]*e' "$arg"; or string match -q -- "--edit" "$arg"
|
||||
set cannot_set_env_var "y" # sudo -e
|
||||
break
|
||||
end
|
||||
if string match -r -q -- '^-[^-]*v' "$arg"; or string match -q -- "--validate" "$arg"
|
||||
set cannot_set_env_var "y" # sudo-rs -e
|
||||
break
|
||||
end
|
||||
if string match -r -q -- '^(--user|--group|--host|--chdir|--chroot|--role|--type|--command-timeout|--auth-type|--login-class|--prompt|--close-from|--other-user)$' "$arg"
|
||||
set ignore_arg "y"
|
||||
continue
|
||||
end
|
||||
if string match -r -q -- '--.+' "$arg"
|
||||
continue
|
||||
end
|
||||
if string match -r -q -- '^-.*a|^-.*C|^-.*c|^-.*D|^-.*g|^-.*h|^-.*p|^-.*R|^-.*r|^-.*t|^-.*T|^-.*u' "$arg"
|
||||
set ignore_arg "y"
|
||||
continue
|
||||
end
|
||||
if string match -r -q -- '-.+' "$arg"; or string match -r -q -- '.+=.+' "$arg"
|
||||
continue
|
||||
end
|
||||
break # command found
|
||||
end
|
||||
if string match -q -- "$cannot_set_env_var" "y"
|
||||
command sudo $argv
|
||||
else
|
||||
command sudo TERMINFO="$TERMINFO" $argv
|
||||
end
|
||||
end
|
||||
end
|
||||
if test "file" = (type -t run0 2> /dev/null || echo "x")
|
||||
# Ensure terminfo is available in run0, --setenv=NAME copies NAME from the current env
|
||||
function run0
|
||||
command run0 --setenv=TERMINFO $argv
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Handle clone launches
|
||||
if test -n "$KITTY_IS_CLONE_LAUNCH"
|
||||
set --local orig_conda_env "$CONDA_DEFAULT_ENV"
|
||||
eval "$KITTY_IS_CLONE_LAUNCH"
|
||||
set --local venv "$VIRTUAL_ENV/bin/activate.fish"
|
||||
set --global _ksi_sourced
|
||||
function _ksi_s_is_ok
|
||||
test -z "$_ksi_sourced"
|
||||
and string match -q -- "*,$argv[1],*" "$KITTY_CLONE_SOURCE_STRATEGIES"
|
||||
and return 0
|
||||
return 1
|
||||
end
|
||||
if _ksi_s_is_ok "venv"
|
||||
and test -n "$VIRTUAL_ENV" -a -r "$venv"
|
||||
set _ksi_sourced "y"
|
||||
set --erase VIRTUAL_ENV _OLD_FISH_PROMPT_OVERRIDE # activate.fish stupidly exports _OLD_FISH_PROMPT_OVERRIDE
|
||||
source "$venv"
|
||||
end
|
||||
if _ksi_s_is_ok "conda"
|
||||
and test -n "$CONDA_DEFAULT_ENV" -a "$CONDA_DEFAULT_ENV" != "$orig_conda_env"
|
||||
and functions -q conda
|
||||
set _ksi_sourced "y"
|
||||
conda activate "$CONDA_DEFAULT_ENV"
|
||||
end
|
||||
if _ksi_s_is_ok "env_var"
|
||||
and test -n "$KITTY_CLONE_SOURCE_CODE"
|
||||
set _ksi_sourced "y"
|
||||
eval "$KITTY_CLONE_SOURCE_CODE"
|
||||
end
|
||||
if _ksi_s_is_ok "path"
|
||||
and test -r "$KITTY_CLONE_SOURCE_PATH"
|
||||
set _ksi_sourced "y"
|
||||
source "$KITTY_CLONE_SOURCE_PATH"
|
||||
end
|
||||
set --erase KITTY_IS_CLONE_LAUNCH KITTY_CLONE_SOURCE_STRATEGIES _ksi_sourced
|
||||
functions --erase _ksi_s_is_ok
|
||||
|
||||
# Ensure PATH has no duplicate entries
|
||||
set --local --path new_path
|
||||
for p in $PATH
|
||||
contains -- "$p" $new_path
|
||||
or set --append new_path "$p"
|
||||
end
|
||||
test (count $new_path) -eq (count $PATH)
|
||||
or set --global --export --path PATH $new_path
|
||||
end
|
||||
end
|
||||
|
||||
function edit-in-kitty --wraps "kitten edit-in-kitty" -d "Edit the specified file in a kitty overlay window with your locally installed editor"
|
||||
kitten edit-in-kitty $argv
|
||||
end
|
||||
|
||||
function __ksi_transmit_data -d "Transmit data to kitty using chunked DCS escapes"
|
||||
set --local data (string replace --regex --all -- "\s" "" "$argv[1]")
|
||||
set --local data_len (string length -- "$data")
|
||||
set --local pos 1
|
||||
set --local chunk_num 0
|
||||
while test "$pos" -le $data_len
|
||||
printf \eP@kitty-%s\|%s:%s\e\\ "$argv[2]" "$chunk_num" (string sub --start $pos --length 2048 -- "$data")
|
||||
set pos (math $pos + 2048)
|
||||
set chunk_num (math $chunk_num + 1)
|
||||
end
|
||||
printf \eP@kitty-%s\|\e\\ "$argv[2]"
|
||||
end
|
||||
|
||||
function clone-in-kitty -d "Clone the current fish session into a new kitty window"
|
||||
set --local data
|
||||
for a in $argv
|
||||
if contains -- "$a" -h --help
|
||||
echo "Clone the current fish session into a new kitty window."
|
||||
echo
|
||||
echo "For usage instructions see: https://sw.kovidgoyal.net/kitty/shell-integration/#clone-shell"
|
||||
return
|
||||
end
|
||||
set --local ea (printf "%s" "$a" | base64)
|
||||
set --append data "a=$ea"
|
||||
end
|
||||
set --local envs
|
||||
for e in (set --export --names)
|
||||
set --append envs "$e=$$e"
|
||||
end
|
||||
set --local b64_envs (string join0 -- $envs | base64)
|
||||
set --local b64_cwd (printf "%s" "$PWD" | base64)
|
||||
set --prepend data "shell=fish" "pid=$fish_pid" "cwd=$b64_cwd" "env=$b64_envs"
|
||||
__ksi_transmit_data (string join "," -- $data) "clone"
|
||||
end
|
||||
@@ -0,0 +1,264 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# bootstrap-utils.sh
|
||||
# Copyright (C) 2022 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
#
|
||||
# Distributed under terms of the MIT license.
|
||||
#
|
||||
|
||||
mv_files_and_dirs() {
|
||||
cwd="$PWD"
|
||||
cd "$1"
|
||||
# Directories not present at the destination are moved intact, preserving
|
||||
# their permissions, and pruned. Existing directories are merged, keeping
|
||||
# their permissions, so make the source writable to allow moving out its
|
||||
# contents. If a move fails fall back to creating the directory and merging.
|
||||
command find . -type d ! -name . -exec sh -c '
|
||||
if [ ! -d "$1/$2" ]; then
|
||||
{ [ -L "$1/$2" ] || [ -e "$1/$2" ]; } && command rm -f -- "$1/$2"
|
||||
command mv -- "$2" "$1/$2" 2> /dev/null && exit 0
|
||||
[ -d "$1/$2" ] && exit 0
|
||||
command mkdir -p -- "$1/$2"
|
||||
fi
|
||||
command chmod u+rwx "$2"
|
||||
exit 1' sh "$2" "{}" ";" -prune
|
||||
command find . -type l -exec sh -c 'tgt=$(command readlink -n "$2"); command ln -snf -- "$tgt" "$1/$2"; command rm -f -- "$2"' sh "$2" "{}" ";"
|
||||
command find . -type f -exec mv "{}" "$2/{}" ";"
|
||||
cd "$cwd"
|
||||
}
|
||||
|
||||
compile_terminfo() {
|
||||
tname=".terminfo"
|
||||
# Ensure the 78 dir is present
|
||||
if [ ! -f "$1/$tname/78/xterm-kitty" ]; then
|
||||
command mkdir -p "$1/$tname/78"
|
||||
command ln -sf "../x/xterm-kitty" "$1/$tname/78/xterm-kitty"
|
||||
fi
|
||||
|
||||
if [ -e "/usr/share/misc/terminfo.cdb" ]; then
|
||||
# NetBSD requires this file, see https://github.com/kovidgoyal/kitty/issues/4622
|
||||
# Also compile terminfo using tic installed via pkgsrc,
|
||||
# so that programs that depend on the new version of ncurses automatically fall back to this one.
|
||||
if [ -x "/usr/pkg/bin/tic" ]; then
|
||||
/usr/pkg/bin/tic -x -o "$1/$tname" "$1/.terminfo/kitty.terminfo" 2>/dev/null
|
||||
fi
|
||||
if [ ! -e "$1/$tname/x/xterm-kitty" ]; then
|
||||
command ln -sf "../../.terminfo.cdb" "$1/$tname/x/xterm-kitty"
|
||||
fi
|
||||
tname=".terminfo.cdb"
|
||||
fi
|
||||
|
||||
# export TERMINFO
|
||||
export TERMINFO="$HOME/$tname"
|
||||
|
||||
# compile terminfo for this system
|
||||
if [ -x "$(command -v tic)" ]; then
|
||||
tic_out=$(command tic -x -o "$1/$tname" "$1/.terminfo/kitty.terminfo" 2>&1)
|
||||
[ $? = 0 ] || die "Failed to compile terminfo with err: $tic_out"
|
||||
fi
|
||||
}
|
||||
|
||||
parse_passwd_record() {
|
||||
printf "%s" "$(command grep -o '[^:]*$')"
|
||||
}
|
||||
|
||||
login_shell_is_ok() {
|
||||
[ -n "$1" ] && login_shell=$(echo $1 | parse_passwd_record)
|
||||
[ -n "$login_shell" -a -x "$login_shell" ] && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
using_getent() {
|
||||
cmd=$(command -v getent) && [ -n "$cmd" ] && output=$(command "$cmd" passwd "$USER" 2>/dev/null) \
|
||||
&& login_shell_is_ok "$output"
|
||||
}
|
||||
|
||||
using_id() {
|
||||
cmd=$(command -v id) && [ -n "$cmd" ] && output=$(command "$cmd" -P "$USER" 2>/dev/null) \
|
||||
&& login_shell_is_ok "$output"
|
||||
}
|
||||
|
||||
using_python() {
|
||||
detect_python && output=$(command "$python" -c "import pwd, os; print(pwd.getpwuid(os.geteuid()).pw_shell)" 2>/dev/null) \
|
||||
&& login_shell="$output" && login_shell_is_ok
|
||||
}
|
||||
|
||||
using_perl() {
|
||||
detect_perl && output=$(command "$perl" -e 'my $shell = (getpwuid($<))[8]; print $shell' 2>/dev/null) \
|
||||
&& login_shell="$output" && login_shell_is_ok
|
||||
}
|
||||
|
||||
using_passwd() {
|
||||
[ -f "/etc/passwd" -a -r "/etc/passwd" ] && output=$(command grep "^$USER:" /etc/passwd 2>/dev/null) \
|
||||
&& login_shell_is_ok "$output"
|
||||
}
|
||||
|
||||
using_shell_env() {
|
||||
[ -n "$SHELL" ] && login_shell="$SHELL" && login_shell_is_ok
|
||||
}
|
||||
|
||||
execute_with_python() {
|
||||
if detect_python; then
|
||||
exec "$python" "-c" 'import os, sys; os.execlp(sys.argv[1], "-" + sys.argv[2])' "$login_shell" "$shell_name"
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
execute_with_perl() {
|
||||
if detect_perl; then
|
||||
exec "$perl" "-e" 'exec {$ARGV[0]} ("-" . $ARGV[1])' "$login_shell" "$shell_name"
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
exec_zsh_with_integration() {
|
||||
zdotdir="$ZDOTDIR"
|
||||
if [ -z "$zdotdir" ]; then
|
||||
zdotdir=~
|
||||
else
|
||||
export KITTY_ORIG_ZDOTDIR="$zdotdir"
|
||||
fi
|
||||
# dont prevent zsh-newuser-install from running
|
||||
if [ -f "$zdotdir/.zshrc" -o -f "$zdotdir/.zshenv" -o -f "$zdotdir/.zprofile" -o -f "$zdotdir/.zlogin" ]; then
|
||||
export ZDOTDIR="$shell_integration_dir/zsh"
|
||||
exec "$login_shell" "-l"
|
||||
fi
|
||||
# ensure this is not propagated
|
||||
unset KITTY_ORIG_ZDOTDIR
|
||||
}
|
||||
|
||||
exec_fish_with_integration() {
|
||||
if [ -z "$XDG_DATA_DIRS" ]; then
|
||||
export XDG_DATA_DIRS="$shell_integration_dir"
|
||||
else
|
||||
export XDG_DATA_DIRS="$shell_integration_dir:$XDG_DATA_DIRS"
|
||||
fi
|
||||
export KITTY_FISH_XDG_DATA_DIR="$shell_integration_dir"
|
||||
exec "$login_shell" "-l"
|
||||
}
|
||||
|
||||
exec_bash_with_integration() {
|
||||
export ENV="$shell_integration_dir/bash/kitty.bash"
|
||||
export KITTY_BASH_INJECT="1"
|
||||
if [ -z "$HISTFILE" ]; then
|
||||
export HISTFILE="$HOME/.bash_history"
|
||||
export KITTY_BASH_UNEXPORT_HISTFILE="1"
|
||||
fi
|
||||
exec "$login_shell" "--login" "--posix"
|
||||
}
|
||||
|
||||
exec_with_shell_integration() {
|
||||
[ -z "$shell_integration_dir" ] && return
|
||||
case "$shell_name" in
|
||||
"zsh")
|
||||
exec_zsh_with_integration
|
||||
;;
|
||||
"fish")
|
||||
exec_fish_with_integration
|
||||
;;
|
||||
"bash")
|
||||
exec_bash_with_integration
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
execute_sh_with_posix_env() {
|
||||
# only for sh as that is likely to be POSIX compliant
|
||||
[ "$shell_name" = "sh" ] || return
|
||||
# sh supports -l so use that
|
||||
command "$login_shell" -l -c ":" > /dev/null 2> /dev/null && return
|
||||
[ -z "$shell_integration_dir" ] && die "Could not read data over tty ssh kitten cannot function"
|
||||
sh_dir="$shell_integration_dir/sh"
|
||||
command mkdir -p "$sh_dir" || die "Creating directory $sh_dir failed"
|
||||
sh_script="$sh_dir/login_shell_env.sh"
|
||||
# Source /etc/profile, ~/.profile, and then check and source ENV
|
||||
printf "%s" '
|
||||
if [ -n "$KITTY_SH_INJECT" ]; then
|
||||
unset ENV; unset KITTY_SH_INJECT
|
||||
_ksi_safe_source() { [ -f "$1" -a -r "$1" ] || return 1; . "$1"; return 0; }
|
||||
[ -n "$KITTY_SH_POSIX_ENV" ] && export ENV="$KITTY_SH_POSIX_ENV"
|
||||
unset KITTY_SH_POSIX_ENV
|
||||
_ksi_safe_source "/etc/profile"; _ksi_safe_source "${HOME-}/.profile"
|
||||
[ -n "$ENV" ] && _ksi_safe_source "$ENV"
|
||||
unset -f _ksi_safe_source
|
||||
fi' > "$sh_script"
|
||||
export KITTY_SH_INJECT="1"
|
||||
[ -n "$ENV" ] && export KITTY_SH_POSIX_ENV="$ENV"
|
||||
export ENV="$sh_script"
|
||||
exec "$login_shell"
|
||||
}
|
||||
|
||||
install_kitty_bootstrap() {
|
||||
kitty_dir="$data_dir/kitty/bin"
|
||||
export SSH_KITTEN_KITTY_DIR="$kitty_dir"
|
||||
kitty_exists="n"
|
||||
command -v kitty 2> /dev/null > /dev/null && kitty_exists="y"
|
||||
if [ "$kitty_remote" = "yes" -o "$kitty_remote-$kitty_exists" = "if-needed-n" ]; then
|
||||
if [ "$kitty_exists" = "y" ]; then
|
||||
export PATH="$kitty_dir:$PATH"
|
||||
else
|
||||
export PATH="$PATH:$kitty_dir"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
prepare_for_exec() {
|
||||
if [ -n "$leading_data" ]; then
|
||||
# clear current line as it might have things echoed on it from leading_data
|
||||
# because we only turn off echo in this script whereas the leading bytes could
|
||||
# have been sent before the script had a chance to run
|
||||
printf "\r\033[K" > /dev/tty
|
||||
fi
|
||||
[ -f "$HOME/.terminfo/kitty.terminfo" ] || die "Incomplete extraction of ssh data"
|
||||
install_kitty_bootstrap
|
||||
|
||||
[ -n "$login_shell" ] || using_getent || using_id || using_python || using_perl || using_passwd || using_shell_env || login_shell="sh"
|
||||
case "$login_shell" in
|
||||
/*) ;;
|
||||
*)
|
||||
if ! command -v "$login_shell" > /dev/null 2> /dev/null; then
|
||||
for i in /opt/homebrew/bin /opt/homebrew/sbin /opt/local/bin /opt/local/sbin /usr/local/bin /usr/bin /bin /usr/sbin /sbin
|
||||
do
|
||||
if [ -x "$i/$login_shell" ]; then
|
||||
login_shell="$i/$login_shell"
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
shell_name=$(command basename "$login_shell")
|
||||
[ -n "$login_cwd" ] && cd "$login_cwd"
|
||||
}
|
||||
|
||||
exec_login_shell() {
|
||||
case "$KITTY_SHELL_INTEGRATION" in
|
||||
("")
|
||||
# only blanks or unset
|
||||
unset KITTY_SHELL_INTEGRATION
|
||||
;;
|
||||
(*)
|
||||
# not blank
|
||||
printf "%s" "$KITTY_SHELL_INTEGRATION" | command grep -q '\bno-rc\b' || exec_with_shell_integration
|
||||
# either no-rc or exec failed
|
||||
unset KITTY_SHELL_INTEGRATION
|
||||
;;
|
||||
esac
|
||||
|
||||
# We need to pass the first argument to the executed program with a leading -
|
||||
# to make sure the shell executes as a login shell. Note that not all shells
|
||||
# support exec -a so we use the below to try to detect such shells
|
||||
[ "$(exec -a echo echo OK 2> /dev/null)" = "OK" ] && exec -a "-$shell_name" "$login_shell"
|
||||
execute_with_python
|
||||
execute_with_perl
|
||||
execute_sh_with_posix_env
|
||||
exec "$login_shell" "-l"
|
||||
if [ -e /dev/stderr ]; then
|
||||
printf "%s\n" "Could not execute the shell $login_shell as a login shell" > /dev/stderr
|
||||
elif [ -e /dev/fd/2 ]; then
|
||||
printf "%s\n" "Could not execute the shell $login_shell as a login shell" > /dev/fd/2
|
||||
else
|
||||
printf "%s\n" "Could not execute the shell $login_shell as a login shell"
|
||||
fi
|
||||
exec "$login_shell"
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import base64
|
||||
import contextlib
|
||||
import errno
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import termios
|
||||
|
||||
tty_file_obj = None
|
||||
echo_on = int('ECHO_ON')
|
||||
data_dir = shell_integration_dir = ''
|
||||
request_data = int('REQUEST_DATA')
|
||||
leading_data = b''
|
||||
login_shell = os.environ.get('SHELL') or '/bin/sh'
|
||||
try:
|
||||
login_shell = pwd.getpwuid(os.geteuid()).pw_shell
|
||||
except KeyError:
|
||||
pass
|
||||
export_home_cmd = b'EXPORT_HOME_CMD'
|
||||
if export_home_cmd:
|
||||
HOME = base64.standard_b64decode(export_home_cmd).decode('utf-8')
|
||||
os.chdir(HOME)
|
||||
else:
|
||||
HOME = os.path.expanduser('~')
|
||||
|
||||
|
||||
def set_echo(fd, on=False):
|
||||
if fd < 0:
|
||||
fd = sys.stdin.fileno()
|
||||
old = termios.tcgetattr(fd)
|
||||
new = termios.tcgetattr(fd)
|
||||
if on:
|
||||
new[3] |= termios.ECHO
|
||||
else:
|
||||
new[3] &= ~termios.ECHO
|
||||
termios.tcsetattr(fd, termios.TCSANOW, new)
|
||||
return fd, old
|
||||
|
||||
|
||||
def cleanup():
|
||||
global tty_file_obj
|
||||
if tty_file_obj is not None:
|
||||
if echo_on:
|
||||
set_echo(tty_file_obj.fileno(), True)
|
||||
tty_file_obj.close()
|
||||
tty_file_obj = None
|
||||
|
||||
|
||||
def write_all(fd, data):
|
||||
if isinstance(data, str):
|
||||
data = data.encode('utf-8')
|
||||
data = memoryview(data)
|
||||
while data:
|
||||
try:
|
||||
n = os.write(fd, data)
|
||||
except BlockingIOError:
|
||||
continue
|
||||
if not n:
|
||||
break
|
||||
data = data[n:]
|
||||
|
||||
|
||||
def dcs_to_kitty(payload, type='ssh'):
|
||||
if isinstance(payload, str):
|
||||
payload = payload.encode('utf-8')
|
||||
payload = base64.standard_b64encode(payload)
|
||||
return b'\033P@kitty-' + type.encode('ascii') + b'|' + payload + b'\033\\'
|
||||
|
||||
|
||||
def send_data_request():
|
||||
write_all(tty_file_obj.fileno(), dcs_to_kitty('id=REQUEST_ID:pwfile=PASSWORD_FILENAME:pw=DATA_PASSWORD'))
|
||||
|
||||
|
||||
def debug(msg):
|
||||
data = dcs_to_kitty('debug: {}'.format(msg), 'print')
|
||||
if tty_file_obj is None:
|
||||
with open(os.ctermid(), 'wb') as fl:
|
||||
write_all(fl.fileno(), data)
|
||||
else:
|
||||
write_all(tty_file_obj.fileno(), data)
|
||||
|
||||
|
||||
def apply_env_vars(raw):
|
||||
global login_shell
|
||||
|
||||
def process_defn(defn):
|
||||
parts = json.loads(defn)
|
||||
if len(parts) == 1:
|
||||
key, val = parts[0], ''
|
||||
else:
|
||||
key, val, literal_quote = parts
|
||||
if not literal_quote:
|
||||
val = os.path.expandvars(val)
|
||||
os.environ[key] = val
|
||||
|
||||
for line in raw.splitlines():
|
||||
val = line.split(' ', 1)[-1]
|
||||
if line.startswith('export '):
|
||||
process_defn(val)
|
||||
elif line.startswith('unset '):
|
||||
os.environ.pop(json.loads(val)[0], None)
|
||||
login_shell = os.environ.pop('KITTY_LOGIN_SHELL', login_shell)
|
||||
|
||||
|
||||
def move_dir(src, dest):
|
||||
try:
|
||||
os.rename(src, dest)
|
||||
except OSError as e:
|
||||
if e.errno != errno.EXDEV:
|
||||
raise
|
||||
# copytree preserves permissions, the source is removed with the
|
||||
# temporary directory
|
||||
shutil.copytree(src, dest, symlinks=True)
|
||||
|
||||
|
||||
def make_deletable(top):
|
||||
# copied directories can be read-only
|
||||
for dirpath, dirnames, filenames in os.walk(top):
|
||||
for x in dirnames:
|
||||
path = os.path.join(dirpath, x)
|
||||
if not os.path.islink(path):
|
||||
os.chmod(path, 0o700)
|
||||
|
||||
|
||||
def move(src, base_dest):
|
||||
for x in os.listdir(src):
|
||||
path = os.path.join(src, x)
|
||||
dest = os.path.join(base_dest, x)
|
||||
if os.path.islink(path):
|
||||
try:
|
||||
os.unlink(dest)
|
||||
except EnvironmentError:
|
||||
pass
|
||||
os.symlink(os.readlink(path), dest)
|
||||
elif os.path.isdir(path):
|
||||
if os.path.isdir(dest):
|
||||
# merge into the existing directory, keeping its permissions,
|
||||
# the source may be read-only so make it writable
|
||||
os.chmod(path, 0o700)
|
||||
move(path, dest)
|
||||
else:
|
||||
# move the directory intact to preserve its permissions
|
||||
if os.path.lexists(dest):
|
||||
os.unlink(dest)
|
||||
move_dir(path, dest)
|
||||
else:
|
||||
shutil.move(path, dest)
|
||||
|
||||
|
||||
def compile_terminfo(base):
|
||||
try:
|
||||
tic = shutil.which('tic')
|
||||
except AttributeError:
|
||||
# python2
|
||||
for x in os.environ.get('PATH', '').split(os.pathsep):
|
||||
q = os.path.join(x, 'tic')
|
||||
if os.access(q, os.X_OK) and os.path.isfile(q):
|
||||
tic = q
|
||||
break
|
||||
else:
|
||||
tic = ''
|
||||
if not tic:
|
||||
return
|
||||
tname = '.terminfo'
|
||||
q = os.path.join(base, tname, '78', 'xterm-kitty')
|
||||
if not os.path.exists(q):
|
||||
try:
|
||||
os.makedirs(os.path.dirname(q))
|
||||
except EnvironmentError as e:
|
||||
if e.errno != errno.EEXIST:
|
||||
raise
|
||||
os.symlink('../x/xterm-kitty', q)
|
||||
if os.path.exists('/usr/share/misc/terminfo.cdb'):
|
||||
# NetBSD requires this
|
||||
os.symlink('../../.terminfo.cdb', os.path.join(base, tname, 'x', 'xterm-kitty'))
|
||||
tname += '.cdb'
|
||||
os.environ['TERMINFO'] = os.path.join(HOME, tname)
|
||||
p = subprocess.Popen(
|
||||
[tic, '-x', '-o', os.path.join(base, tname), os.path.join(base, '.terminfo', 'kitty.terminfo')], stdout=subprocess.PIPE, stderr=subprocess.STDOUT
|
||||
)
|
||||
output = p.stdout.read()
|
||||
rc = p.wait()
|
||||
if rc != 0:
|
||||
getattr(sys.stderr, 'buffer', sys.stderr).write(output)
|
||||
raise SystemExit('Failed to compile the terminfo database')
|
||||
|
||||
|
||||
def iter_base64_data(f):
|
||||
global leading_data
|
||||
started = 0
|
||||
while True:
|
||||
line = f.readline().rstrip()
|
||||
if started == 0:
|
||||
if line == b'KITTY_DATA_START':
|
||||
started = 1
|
||||
else:
|
||||
leading_data += line
|
||||
elif started == 1:
|
||||
if line == b'OK':
|
||||
started = 2
|
||||
else:
|
||||
raise SystemExit(line.decode('utf-8', 'replace').rstrip())
|
||||
else:
|
||||
if line == b'KITTY_DATA_END':
|
||||
break
|
||||
yield line
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def temporary_directory(dir, prefix):
|
||||
# tempfile.TemporaryDirectory not available in python2
|
||||
tdir = tempfile.mkdtemp(dir=dir, prefix=prefix)
|
||||
try:
|
||||
yield tdir
|
||||
finally:
|
||||
make_deletable(tdir)
|
||||
shutil.rmtree(tdir)
|
||||
|
||||
|
||||
def get_data():
|
||||
global data_dir, shell_integration_dir, leading_data
|
||||
data = []
|
||||
data = b''.join(iter_base64_data(tty_file_obj))
|
||||
if leading_data:
|
||||
# clear current line as it might have things echoed on it from leading_data
|
||||
# because we only turn off echo in this script whereas the leading bytes could
|
||||
# have been sent before the script had a chance to run
|
||||
sys.stdout.write('\r\033[K')
|
||||
data = base64.standard_b64decode(data)
|
||||
with temporary_directory(dir=HOME, prefix='.kitty-ssh-kitten-untar-') as tdir, tarfile.open(fileobj=io.BytesIO(data)) as tf:
|
||||
try:
|
||||
# We have to use fully_trusted as otherwise it refuses to extract,
|
||||
# for example, symlinks that point to absolute paths outside
|
||||
# tdir.
|
||||
tf.extractall(tdir, filter='fully_trusted')
|
||||
except TypeError:
|
||||
tf.extractall(tdir)
|
||||
with open(tdir + '/data.sh') as f:
|
||||
env_vars = f.read()
|
||||
apply_env_vars(env_vars)
|
||||
data_dir = os.environ.pop('KITTY_SSH_KITTEN_DATA_DIR')
|
||||
if not os.path.isabs(data_dir):
|
||||
data_dir = os.path.join(HOME, data_dir)
|
||||
data_dir = os.path.abspath(data_dir)
|
||||
shell_integration_dir = os.path.join(data_dir, 'shell-integration')
|
||||
compile_terminfo(tdir + '/home')
|
||||
move(tdir + '/home', HOME)
|
||||
if os.path.exists(tdir + '/root'):
|
||||
move(tdir + '/root', '/')
|
||||
|
||||
|
||||
def exec_with_better_error(*a):
|
||||
try:
|
||||
os.execlp(*a)
|
||||
except OSError as err:
|
||||
if err.errno == errno.ENOENT:
|
||||
raise SystemExit('The program: "' + a[0] + '" was not found')
|
||||
raise
|
||||
|
||||
|
||||
def exec_zsh_with_integration():
|
||||
zdotdir = os.environ.get('ZDOTDIR') or ''
|
||||
if not zdotdir:
|
||||
zdotdir = HOME
|
||||
os.environ.pop('KITTY_ORIG_ZDOTDIR', None) # ensure this is not propagated
|
||||
else:
|
||||
os.environ['KITTY_ORIG_ZDOTDIR'] = zdotdir
|
||||
# dont prevent zsh-newuser-install from running
|
||||
for q in ('.zshrc', '.zshenv', '.zprofile', '.zlogin'):
|
||||
if os.path.exists(os.path.join(zdotdir, q)):
|
||||
os.environ['ZDOTDIR'] = shell_integration_dir + '/zsh'
|
||||
exec_with_better_error(login_shell, os.path.basename(login_shell), '-l')
|
||||
os.environ.pop('KITTY_ORIG_ZDOTDIR', None) # ensure this is not propagated
|
||||
|
||||
|
||||
def exec_fish_with_integration():
|
||||
if not os.environ.get('XDG_DATA_DIRS'):
|
||||
os.environ['XDG_DATA_DIRS'] = shell_integration_dir
|
||||
else:
|
||||
os.environ['XDG_DATA_DIRS'] = shell_integration_dir + ':' + os.environ['XDG_DATA_DIRS']
|
||||
os.environ['KITTY_FISH_XDG_DATA_DIR'] = shell_integration_dir
|
||||
exec_with_better_error(login_shell, os.path.basename(login_shell), '-l')
|
||||
|
||||
|
||||
def exec_bash_with_integration():
|
||||
os.environ['ENV'] = os.path.join(shell_integration_dir, 'bash', 'kitty.bash')
|
||||
os.environ['KITTY_BASH_INJECT'] = '1'
|
||||
if not os.environ.get('HISTFILE'):
|
||||
os.environ['HISTFILE'] = os.path.join(HOME, '.bash_history')
|
||||
os.environ['KITTY_BASH_UNEXPORT_HISTFILE'] = '1'
|
||||
exec_with_better_error(login_shell, os.path.basename('login_shell'), '--posix')
|
||||
|
||||
|
||||
def exec_with_shell_integration():
|
||||
shell_name = os.path.basename(login_shell).lower()
|
||||
if shell_name == 'zsh':
|
||||
exec_zsh_with_integration()
|
||||
if shell_name == 'fish':
|
||||
exec_fish_with_integration()
|
||||
if shell_name == 'bash':
|
||||
exec_bash_with_integration()
|
||||
|
||||
|
||||
def install_kitty_bootstrap():
|
||||
kitty_remote = os.environ.pop('KITTY_REMOTE', '')
|
||||
kitty_exists = shutil.which('kitty')
|
||||
kitty_dir = os.path.join(data_dir, 'kitty', 'bin')
|
||||
os.environ['SSH_KITTEN_KITTY_DIR'] = kitty_dir
|
||||
if kitty_remote == 'yes' or (kitty_remote == 'if-needed' and not kitty_exists):
|
||||
if kitty_exists:
|
||||
os.environ['PATH'] = kitty_dir + os.pathsep + os.environ['PATH']
|
||||
else:
|
||||
os.environ['PATH'] = os.environ['PATH'] + os.pathsep + kitty_dir
|
||||
|
||||
|
||||
def main():
|
||||
global tty_file_obj, login_shell
|
||||
# the value of O_CLOEXEC below is on macOS which is most likely to not have
|
||||
# os.O_CLOEXEC being still stuck with python2
|
||||
tty_file_obj = os.fdopen(os.open(os.ctermid(), os.O_RDWR | getattr(os, 'O_CLOEXEC', 16777216)), 'rb')
|
||||
try:
|
||||
if request_data:
|
||||
set_echo(tty_file_obj.fileno(), on=False)
|
||||
send_data_request()
|
||||
get_data()
|
||||
finally:
|
||||
cleanup()
|
||||
cwd = os.environ.pop('KITTY_LOGIN_CWD', '')
|
||||
install_kitty_bootstrap()
|
||||
if cwd:
|
||||
try:
|
||||
os.chdir(cwd)
|
||||
except Exception as err:
|
||||
print(f'Failed to change working directory to: {cwd} with error: {err}', file=sys.stderr)
|
||||
ksi = frozenset(filter(None, os.environ.get('KITTY_SHELL_INTEGRATION', '').split()))
|
||||
exec_cmd = b'EXEC_CMD'
|
||||
if exec_cmd:
|
||||
os.environ.pop('KITTY_SHELL_INTEGRATION', None)
|
||||
cmd = base64.standard_b64decode(exec_cmd).decode('utf-8')
|
||||
exec_with_better_error(login_shell, os.path.basename(login_shell), '-c', cmd)
|
||||
remote_cmd = b'REMOTE_CMD'
|
||||
if remote_cmd:
|
||||
os.environ.pop('KITTY_SHELL_INTEGRATION', None)
|
||||
cmd = base64.standard_b64decode(remote_cmd).decode('utf-8')
|
||||
exec_with_better_error(login_shell, os.path.basename(login_shell), '-c', cmd)
|
||||
TEST_SCRIPT # noqa
|
||||
if ksi and 'no-rc' not in ksi:
|
||||
exec_with_shell_integration()
|
||||
os.environ.pop('KITTY_SHELL_INTEGRATION', None)
|
||||
exec_with_better_error(login_shell, '-' + os.path.basename(login_shell))
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,172 @@
|
||||
#!/bin/sh
|
||||
# Copyright (C) 2022 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
# Distributed under terms of the GPLv3 license.
|
||||
|
||||
{ \unalias command; \unset -f command; } >/dev/null 2>&1
|
||||
tdir=""
|
||||
shell_integration_dir=""
|
||||
echo_on="ECHO_ON"
|
||||
|
||||
remove_tdir() {
|
||||
# copied directories can be read-only, make them deletable
|
||||
command chmod -R u+rwx "$tdir" 2> /dev/null
|
||||
command rm -rf "$tdir"
|
||||
}
|
||||
|
||||
cleanup_on_bootstrap_exit() {
|
||||
[ "$echo_on" = "1" ] && command stty "echo" 2> /dev/null < /dev/tty
|
||||
echo_on="0"
|
||||
[ -n "$tdir" ] && remove_tdir
|
||||
tdir=""
|
||||
}
|
||||
|
||||
die() {
|
||||
if [ -e /dev/stderr ]; then
|
||||
printf "\033[31m%s\033[m\n\r" "$*" > /dev/stderr;
|
||||
elif [ -e /dev/fd/2 ]; then
|
||||
printf "\033[31m%s\033[m\n\r" "$*" > /dev/fd/2;
|
||||
else
|
||||
printf "\033[31m%s\033[m\n\r" "$*";
|
||||
fi
|
||||
cleanup_on_bootstrap_exit;
|
||||
exit 1;
|
||||
}
|
||||
|
||||
python_detected="0"
|
||||
detect_python() {
|
||||
if [ python_detected = "1" ]; then
|
||||
[ -n "$python" ] && return 0
|
||||
return 1
|
||||
fi
|
||||
python_detected="1"
|
||||
python=$(command -v python3)
|
||||
[ -z "$python" ] && python=$(command -v python2)
|
||||
[ -z "$python" ] && python=$(command -v python)
|
||||
if [ -z "$python" -o ! -x "$python" ]; then python=""; return 1; fi
|
||||
return 0
|
||||
}
|
||||
|
||||
perl_detected="0"
|
||||
detect_perl() {
|
||||
if [ perl_detected = "1" ]; then
|
||||
[ -n "$perl" ] && return 0
|
||||
return 1
|
||||
fi
|
||||
perl_detected="1"
|
||||
perl=$(command -v perl)
|
||||
if [ -z "$perl" -o ! -x "$perl" ]; then perl=""; return 1; fi
|
||||
return 0
|
||||
}
|
||||
|
||||
if command -v base64 > /dev/null 2> /dev/null; then
|
||||
base64_encode() { command base64 | command tr -d \\n\\r; }
|
||||
base64_decode() { command base64 -d; }
|
||||
elif command -v openssl > /dev/null 2> /dev/null; then
|
||||
base64_encode() { command openssl enc -A -base64; }
|
||||
base64_decode() { command openssl enc -A -d -base64; }
|
||||
elif command -v b64encode > /dev/null 2> /dev/null; then
|
||||
base64_encode() { command b64encode - | command sed '1d;$d' | command tr -d \\n\\r; }
|
||||
base64_decode() { command fold -w 76 | command b64decode -r; }
|
||||
elif detect_python; then
|
||||
pybase64() { command "$python" -c "import sys, base64; getattr(sys.stdout, 'buffer', sys.stdout).write(base64.standard_b64$1(getattr(sys.stdin, 'buffer', sys.stdin).read()))"; }
|
||||
base64_encode() { pybase64 "encode"; }
|
||||
base64_decode() { pybase64 "decode"; }
|
||||
elif detect_perl; then
|
||||
base64_encode() { command "$perl" -MMIME::Base64 -0777 -ne 'print encode_base64($_)'; }
|
||||
base64_decode() { command "$perl" -MMIME::Base64 -ne 'print decode_base64($_)'; }
|
||||
else
|
||||
die "base64 executable not present on remote host, ssh kitten cannot function."
|
||||
fi
|
||||
|
||||
dcs_to_kitty() { printf "\033P@kitty-$1|%s\033\134" "$(printf "%s" "$2" | base64_encode)" > /dev/tty; }
|
||||
debug() { dcs_to_kitty "print" "debug: $1"; }
|
||||
|
||||
# If $HOME is configured set it here
|
||||
EXPORT_HOME_CMD
|
||||
# ensure $HOME is set
|
||||
[ -z "$HOME" ] && HOME=~
|
||||
# ensure $USER is set
|
||||
[ -z "$USER" ] && USER="$LOGNAME"
|
||||
[ -z "$USER" ] && USER="$(command whoami 2> /dev/null)"
|
||||
|
||||
leading_data=""
|
||||
login_shell=""
|
||||
login_cwd=""
|
||||
|
||||
request_data="REQUEST_DATA"
|
||||
trap "cleanup_on_bootstrap_exit" EXIT
|
||||
[ "$request_data" = "1" ] && {
|
||||
command stty "-echo" < /dev/tty
|
||||
dcs_to_kitty "ssh" "id="REQUEST_ID":pwfile="PASSWORD_FILENAME":pw="DATA_PASSWORD""
|
||||
}
|
||||
|
||||
read_base64_from_tty() {
|
||||
while IFS= read -r line; do
|
||||
[ "$line" = "KITTY_DATA_END" ] && return 0
|
||||
printf "%s" "$line"
|
||||
done
|
||||
}
|
||||
|
||||
untar_and_read_env() {
|
||||
# extract the tar file atomically, in the sense that any file from the
|
||||
# tarfile is only put into place after it has been fully written to disk
|
||||
command -v tar > /dev/null 2> /dev/null || die "tar is not available on this server. The ssh kitten requires tar."
|
||||
tdir=$(command mktemp -d "$HOME/.kitty-ssh-kitten-untar-XXXXXXXXXXXX")
|
||||
[ $? = 0 ] || die "Creating temp directory failed"
|
||||
# suppress STDERR for tar as tar prints various warnings if for instance, timestamps are in the future
|
||||
old_umask=$(umask)
|
||||
umask 000
|
||||
read_base64_from_tty | base64_decode | command tar "xpzf" "-" "-C" "$tdir" 2> /dev/null
|
||||
umask "$old_umask"
|
||||
. "$tdir/bootstrap-utils.sh"
|
||||
. "$tdir/data.sh"
|
||||
[ -z "$KITTY_SSH_KITTEN_DATA_DIR" ] && die "Failed to read SSH data from tty"
|
||||
case "$KITTY_SSH_KITTEN_DATA_DIR" in
|
||||
/*) data_dir="$KITTY_SSH_KITTEN_DATA_DIR" ;;
|
||||
*) data_dir="$HOME/$KITTY_SSH_KITTEN_DATA_DIR"
|
||||
esac
|
||||
shell_integration_dir="$data_dir/shell-integration"
|
||||
unset KITTY_SSH_KITTEN_DATA_DIR
|
||||
login_shell="$KITTY_LOGIN_SHELL"
|
||||
unset KITTY_LOGIN_SHELL
|
||||
login_cwd="$KITTY_LOGIN_CWD"
|
||||
unset KITTY_LOGIN_CWD
|
||||
kitty_remote="$KITTY_REMOTE"
|
||||
unset KITTY_REMOTE
|
||||
compile_terminfo "$tdir/home"
|
||||
mv_files_and_dirs "$tdir/home" "$HOME"
|
||||
[ -e "$tdir/root" ] && mv_files_and_dirs "$tdir/root" ""
|
||||
remove_tdir
|
||||
tdir=""
|
||||
}
|
||||
|
||||
get_data() {
|
||||
started="n"
|
||||
while IFS= read -r line; do
|
||||
if [ "$started" = "y" ]; then
|
||||
[ "$line" = "OK" ] && break
|
||||
die "$line"
|
||||
else
|
||||
if [ "$line" = "KITTY_DATA_START" ]; then
|
||||
started="y"
|
||||
else
|
||||
leading_data="$leading_data$line"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
untar_and_read_env
|
||||
}
|
||||
|
||||
# ask for the SSH data
|
||||
get_data
|
||||
cleanup_on_bootstrap_exit
|
||||
prepare_for_exec
|
||||
# If a command was passed to SSH execute it here
|
||||
EXEC_CMD
|
||||
|
||||
REMOTE_CMD
|
||||
|
||||
# Used in the tests
|
||||
TEST_SCRIPT
|
||||
|
||||
exec_login_shell
|
||||
Executable
+99
@@ -0,0 +1,99 @@
|
||||
#!/bin/sh
|
||||
# Copyright (C) 2018 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
#
|
||||
# Distributed under terms of the GPLv3 license.
|
||||
|
||||
{ \unalias command; \unset -f command; } >/dev/null 2>&1
|
||||
|
||||
|
||||
die() {
|
||||
if [ -e /dev/stderr ]; then
|
||||
printf "\033[31m%s\033[m\n\r" "$*" > /dev/stderr;
|
||||
elif [ -e /dev/fd/2 ]; then
|
||||
printf "\033[31m%s\033[m\n\r" "$*" > /dev/fd/2;
|
||||
else
|
||||
printf "\033[31m%s\033[m\n\r" "$*";
|
||||
fi
|
||||
exit 1;
|
||||
}
|
||||
|
||||
exec_kitty() {
|
||||
[ -n "$kitty_exe" ] && exec "$kitty_exe" "$@"
|
||||
die "Failed to execute kitty"
|
||||
}
|
||||
|
||||
script_path="$(command readlink -f "$0" 2> /dev/null)"
|
||||
[ $? = 0 ] || script_path="$0"
|
||||
script_dir="$(command dirname "$script_path")"
|
||||
install_dir="$(command dirname "$script_dir")/install-tool"
|
||||
remote_kitty_version_file="$script_dir/../version"
|
||||
local_kitty_version_file="$install_dir/installed-kitten-version"
|
||||
kitty_exe="$install_dir/kitten"
|
||||
local_kitty_version=""
|
||||
|
||||
[ -f "$kitty_exe" -a -x "$kitty_exe" ] && exec_kitty "$@"
|
||||
|
||||
# Use kitten from the downloaded kitty installation, if available.
|
||||
embed_exe="$(command dirname "$script_dir")/install/bin/kitten"
|
||||
[ -f "$embed_exe" -a -x "$embed_exe" ] && {
|
||||
kitty_exe="$embed_exe"
|
||||
exec_kitty "$@"
|
||||
}
|
||||
|
||||
# If called for shell completion with no binary available, do nothing to avoid
|
||||
# downloading kitten and showing spurious output during tab completion.
|
||||
[ "$1" = "__complete__" ] && exit 0
|
||||
|
||||
case "$(command uname)" in
|
||||
'Linux') OS="linux";;
|
||||
'Darwin') OS="darwin";;
|
||||
'FreeBSD') OS="freebsd";;
|
||||
'NetBSD') OS="netbsd";;
|
||||
'OpenBSD') OS="openbsd";;
|
||||
'DragonFlyBSD') OS="dragonfly";;
|
||||
*) die "kitten pre-built binaries are not available for the $(command uname) operating system";;
|
||||
esac
|
||||
|
||||
if command -v curl 2> /dev/null > /dev/null; then
|
||||
fetch() {
|
||||
command curl -fL "$1"
|
||||
}
|
||||
fetch_quiet() {
|
||||
command curl -fsSL "$1"
|
||||
}
|
||||
elif command -v wget 2> /dev/null > /dev/null; then
|
||||
fetch() {
|
||||
command wget -O- "$1"
|
||||
}
|
||||
fetch_quiet() {
|
||||
command wget --quiet -O- "$1"
|
||||
}
|
||||
else
|
||||
die "Neither curl nor wget available, cannot download kitten"
|
||||
fi
|
||||
|
||||
case "$(command uname -m)" in
|
||||
amd64|x86_64) arch="amd64";;
|
||||
aarch64*) arch="arm64";;
|
||||
armv8*) arch="arm64";;
|
||||
arm64) arch="arm64";;
|
||||
arm|armv7l) arch="arm";;
|
||||
i386) arch="386";;
|
||||
i686) arch="386";;
|
||||
*) die "Unknown CPU architecture $(command uname -m)";;
|
||||
esac
|
||||
|
||||
url="https://github.com/kovidgoyal/kitty/releases/latest/download/kitten-$OS-$arch"
|
||||
|
||||
printf "\033[33mkitten needs to be installed\033[m\n\n"
|
||||
command mkdir -p "$install_dir"
|
||||
printf "Downloading kitten from: \033[32m%s\033[m\n\n" "$url"
|
||||
download_dest="$(command mktemp "$kitty_exe.XXXXXXXXXX")"
|
||||
fetch "$url" > "$download_dest" || {
|
||||
command rm -f "$download_dest"
|
||||
die "Failed to download kitten"
|
||||
}
|
||||
command chmod 755 "$download_dest"
|
||||
command mv "$download_dest" "$kitty_exe"
|
||||
command "$kitty_exe" --version | cut -d" " -f2 > "$local_kitty_version_file"
|
||||
exec_kitty "$@"
|
||||
Executable
+160
@@ -0,0 +1,160 @@
|
||||
#!/bin/sh
|
||||
# Copyright (C) 2018 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
#
|
||||
# Distributed under terms of the GPLv3 license.
|
||||
|
||||
{ \unalias command; \unset -f command; } >/dev/null 2>&1
|
||||
|
||||
|
||||
die() { printf "\033[31m%s\033[m\n\r" "$*" > /dev/stderr; exit 1; }
|
||||
|
||||
delete_lock_dir() {
|
||||
trap '' EXIT INT QUIT TERM
|
||||
[ -n "$lock_dir" ] && {
|
||||
command rm -rf "$lock_dir"
|
||||
lock_dir=""
|
||||
}
|
||||
}
|
||||
|
||||
exec_kitty() {
|
||||
delete_lock_dir
|
||||
[ -n "$kitty_exe" ] && exec "$kitty_exe" "$@"
|
||||
die "Failed to execute kitty"
|
||||
}
|
||||
|
||||
|
||||
has_diskutil_image() {
|
||||
# hdiutil is deprecated in macOS 27
|
||||
macos_major=$(command sw_vers -productVersion 2> /dev/null)
|
||||
macos_major="${macos_major%%.*}"
|
||||
case "$macos_major" in
|
||||
''|*[!0-9]*) return 1;;
|
||||
esac
|
||||
[ "$macos_major" -ge 27 ]
|
||||
}
|
||||
|
||||
mount_dmg() {
|
||||
if has_diskutil_image; then
|
||||
command diskutil image attach --readOnly --mountPoint "$2" "$1"
|
||||
else
|
||||
command hdiutil attach "$1" "-mountpoint" "$2"
|
||||
fi
|
||||
}
|
||||
|
||||
unmount_dmg() {
|
||||
if has_diskutil_image; then
|
||||
command diskutil eject "$1"
|
||||
else
|
||||
command hdiutil detach "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
is_wrapped_kitten() {
|
||||
wrapped_kittens="clipboard icat hyperlinked_grep ask hints unicode_input ssh themes diff show_key transfer query_terminal choose-files command-palette resize_window broadcast remote_file"
|
||||
[ -n "$1" ] && {
|
||||
case " $wrapped_kittens " in
|
||||
*" $1 "*) printf "%s" "$1" ;;
|
||||
esac
|
||||
}
|
||||
}
|
||||
|
||||
test "(" "$1" = "+kitten" -a -n "$(is_wrapped_kitten "$2")" ")" -o "(" "$1" = "+" -a "$2" = "kitten" -a "$(is_wrapped_kitten "$3")" ")" && {
|
||||
if [ "$1" = "+kitten" ]; then shift "1"; else shift "2"; fi
|
||||
exec kitten "$@"
|
||||
}
|
||||
|
||||
lock_dir=""
|
||||
script_path="$(command readlink -f "$0" 2> /dev/null)"
|
||||
[ $? = 0 ] || script_path="$0"
|
||||
script_dir="$(command dirname "$script_path")"
|
||||
install_dir="$(command dirname "$script_dir")/install"
|
||||
remote_kitty_version_file="$script_dir/../version"
|
||||
local_kitty_version_file="$install_dir/installed-kitty-version"
|
||||
kitty_exe="$install_dir/bin/kitty"
|
||||
local_kitty_version=""
|
||||
|
||||
[ -f "$kitty_exe" -a -x "$kitty_exe" -a "$1" != "+update-kitty" ] && exec_kitty "$@"
|
||||
|
||||
case "$(command uname)" in
|
||||
'Linux') OS="linux";;
|
||||
'Darwin') OS="macos";;
|
||||
*) die "kitty pre-built binaries are not available for the $(command uname) operating system";;
|
||||
esac
|
||||
|
||||
if command -v curl 2> /dev/null > /dev/null; then
|
||||
fetch() {
|
||||
command curl -fL "$1"
|
||||
}
|
||||
fetch_quiet() {
|
||||
command curl -fsSL "$1"
|
||||
}
|
||||
elif command -v wget 2> /dev/null > /dev/null; then
|
||||
fetch() {
|
||||
command wget -O- "$1"
|
||||
}
|
||||
fetch_quiet() {
|
||||
command wget --quiet -O- "$1"
|
||||
}
|
||||
else
|
||||
die "Neither curl nor wget available, cannot download kitty"
|
||||
fi
|
||||
|
||||
if [ "$OS" = "linux" ]; then
|
||||
case "$(command uname -m)" in
|
||||
amd64|x86_64) arch="x86_64";;
|
||||
aarch64*) arch="arm64";;
|
||||
armv8*) arch="arm64";;
|
||||
arm64) arch="arm64";;
|
||||
i386) arch="i686";;
|
||||
i686) arch="i686";;
|
||||
*) die "Unknown CPU architecture $(command uname -m)";;
|
||||
esac
|
||||
fi
|
||||
|
||||
release_version=$(fetch_quiet "https://sw.kovidgoyal.net/kitty/current-version.txt")
|
||||
[ $? -ne 0 -o -z "$release_version" ] && {
|
||||
[ -n "$local_kitty_version" ] && exec_kitty "$@"
|
||||
die "Could not get kitty latest release version"
|
||||
}
|
||||
|
||||
if [ "$OS" = "linux" ]; then
|
||||
url="https://github.com/kovidgoyal/kitty/releases/download/v$release_version/kitty-$release_version-$arch.txz"
|
||||
else
|
||||
url="https://github.com/kovidgoyal/kitty/releases/download/v$release_version/kitty-$release_version.dmg"
|
||||
fi
|
||||
|
||||
lock_dir="$script_dir/kitty-install-lock"
|
||||
if ! command mkdir "$lock_dir" 2> /dev/null; then
|
||||
ed="$lock_dir"
|
||||
lock_dir="";
|
||||
die "Failed to create lock dir another instance of the kitty bootstrap script is running. If you are sure that is not the case delete: $ed";
|
||||
fi
|
||||
trap 'delete_lock_dir' EXIT INT QUIT TERM
|
||||
|
||||
printf "\033[33mkitty needs to be installed\033[m\n\n"
|
||||
command rm -rf "$install_dir"
|
||||
command mkdir -p "$install_dir"
|
||||
printf "Downloading kitty from: \033[32m%s\033[m\n\n" "$url"
|
||||
|
||||
if [ "$OS" = "linux" ]; then
|
||||
old_umask=$(umask)
|
||||
umask 000
|
||||
fetch "$url" | command tar -C "$install_dir" -xJof -
|
||||
umask "$old_umask"
|
||||
[ $? = 0 ] || die "Failed to download and install kitty"
|
||||
else
|
||||
tdir=$(command mktemp -d "$install_dir/tmp-for-dmg-XXXXXXXXXXXX")
|
||||
[ $? = 0 ] || die "Creating temp directory failed"
|
||||
fetch "$url" > "$tdir/kitty.dmg"
|
||||
command mkdir "$tdir/mp"
|
||||
mount_dmg "$tdir/kitty.dmg" "$tdir/mp" || die "Failed to mount kitty.dmg"
|
||||
command ditto -v "$tdir/mp/kitty.app" "$install_dir/kitty.app"
|
||||
rc="$?"
|
||||
unmount_dmg "$tdir/mp"
|
||||
command rm -rf "$tdir"
|
||||
[ "$rc" != "0" ] && die "Failed to copy kitty.app from mounted dmg"
|
||||
command mkdir "$install_dir/bin"
|
||||
command ln -sf "$install_dir/kitty.app/Contents/MacOS/kitty" "$install_dir/bin/kitty"
|
||||
fi
|
||||
command "$kitty_exe" +runpy "from kitty.constants import str_version; print(end=str_version)" > "$local_kitty_version_file"
|
||||
exec_kitty "$@"
|
||||
@@ -0,0 +1,45 @@
|
||||
# This file can get sourced with aliases enabled. To avoid alias expansion
|
||||
# we quote everything that can be quoted. Some aliases will still break us
|
||||
# though.
|
||||
|
||||
# Don't use [[ -v ... ]] because it doesn't work in zsh < 5.4.
|
||||
if [[ -n "${KITTY_ORIG_ZDOTDIR+X}" ]]; then
|
||||
# Normally ZDOTDIR shouldn't be exported but it was in the environment
|
||||
# of kitty, so we export it.
|
||||
'builtin' 'export' ZDOTDIR="$KITTY_ORIG_ZDOTDIR"
|
||||
'builtin' 'unset' 'KITTY_ORIG_ZDOTDIR'
|
||||
else
|
||||
'builtin' 'unset' 'ZDOTDIR'
|
||||
fi
|
||||
|
||||
# Use try-always to have the right error code.
|
||||
{
|
||||
# Zsh treats empty $ZDOTDIR as if it was "/". We do the same.
|
||||
#
|
||||
# Source the user's zshenv before sourcing kitty.zsh because the former
|
||||
# might set fpath and other things without which kitty.zsh won't work.
|
||||
#
|
||||
# Use typeset in case we are in a function with warn_create_global in
|
||||
# effect. Unlikely but better safe than sorry.
|
||||
'builtin' 'typeset' _ksi_file=${ZDOTDIR-~}"/.zshenv"
|
||||
# Zsh ignores unreadable rc files. We do the same.
|
||||
# Zsh ignores rc files that are directories, and so does source.
|
||||
[[ ! -r "$_ksi_file" ]] || 'builtin' 'source' '--' "$_ksi_file"
|
||||
} always {
|
||||
if [[ -o 'interactive' && -n "${KITTY_SHELL_INTEGRATION-}" ]]; then
|
||||
'builtin' 'autoload' '--' 'is-at-least'
|
||||
'is-at-least' "5.1" || {
|
||||
builtin echo "ZSH ${ZSH_VERSION} is too old for kitty shell integration" > /dev/stderr
|
||||
return
|
||||
}
|
||||
# ${(%):-%x} is the path to the current file.
|
||||
# On top of it we add :A:h to get the directory.
|
||||
'builtin' 'typeset' _ksi_file="${${(%):-%x}:A:h}"/kitty-integration
|
||||
if [[ -r "$_ksi_file" ]]; then
|
||||
'builtin' 'autoload' '-Uz' '--' "$_ksi_file"
|
||||
"${_ksi_file:t}"
|
||||
'builtin' 'unfunction' '--' "${_ksi_file:t}"
|
||||
fi
|
||||
fi
|
||||
'builtin' 'unset' '_ksi_file'
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
#compdef kitty
|
||||
|
||||
(( ${+commands[kitten]} )) || builtin return
|
||||
builtin local src cmd=${(F)words:0:$CURRENT}
|
||||
# Send all words up to the word the cursor is currently on.
|
||||
src=$(builtin command kitten __complete__ zsh "_matcher=$_matcher" <<<$cmd) || builtin return
|
||||
builtin eval "$src"
|
||||
@@ -0,0 +1,501 @@
|
||||
#!/bin/zsh
|
||||
#
|
||||
# Enables integration between zsh and kitty based on KITTY_SHELL_INTEGRATION.
|
||||
# The latter is set by kitty based on kitty.conf.
|
||||
#
|
||||
# This is an autoloadable function. It's invoked automatically in shells
|
||||
# directly spawned by kitty but not in any other shells. For example, running
|
||||
# `exec zsh`, `sudo -E zsh`, `tmux`, or plain `zsh` will create a shell where
|
||||
# kitty-integration won't automatically run. Zsh users who want integration with
|
||||
# kitty in all shells should add the following lines to their .zshrc:
|
||||
#
|
||||
# if [[ -n "$KITTY_INSTALLATION_DIR" ]]; then
|
||||
# export KITTY_SHELL_INTEGRATION="enabled"
|
||||
# autoload -Uz -- "$KITTY_INSTALLATION_DIR"/shell-integration/zsh/kitty-integration
|
||||
# kitty-integration
|
||||
# unfunction kitty-integration
|
||||
# fi
|
||||
#
|
||||
# Implementation note: We can assume that alias expansion is disabled in this
|
||||
# file, so no need to quote defensively. We still have to defensively prefix all
|
||||
# builtins with `builtin` to avoid accidentally invoking user-defined functions.
|
||||
# We avoid `function` reserved word as an additional defensive measure.
|
||||
|
||||
builtin emulate -L zsh -o no_warn_create_global -o no_aliases
|
||||
|
||||
[[ -o interactive ]] || builtin return 0 # non-interactive shell
|
||||
[[ -n "$KITTY_SHELL_INTEGRATION" ]] || builtin return 0 # integration disabled
|
||||
(( ! $+_ksi_state )) || builtin return 0 # already initialized
|
||||
|
||||
# 0: no OSC 133 [AC] marks have been written yet.
|
||||
# 1: the last written OSC 133 C has not been closed with D yet.
|
||||
# 2: none of the above.
|
||||
builtin typeset -gi _ksi_state
|
||||
|
||||
# Attempt to create a writable file descriptor to the TTY so that we can print
|
||||
# to the TTY later even when STDOUT is redirected. This code is fairly subtle.
|
||||
#
|
||||
# - It's tempting to do `[[ -t 1 ]] && exec {_ksi_state}>&1` but we cannot do this
|
||||
# because it'll create a file descriptor >= 10 without O_CLOEXEC. This file
|
||||
# descriptor will leak to child processes.
|
||||
# - If we do `exec {3}>&1`, the file descriptor won't leak to the child processes
|
||||
# but it'll still leak if the current process is replaced with another. In
|
||||
# addition, it'll break user code that relies on fd 3 being available.
|
||||
# - Zsh doesn't expose dup3, which would have allowed us to copy STDOUT with
|
||||
# O_CLOEXEC. The only way to create a file descriptor with O_CLOEXEC is via
|
||||
# sysopen.
|
||||
# - `zmodload zsh/system` and `sysopen -o cloexec -wu _ksi_fd -- /dev/tty` can
|
||||
# fail with an error message to STDERR (the latter can happen even if /dev/tty
|
||||
# is writable), hence the redirection of STDERR. We do it for the whole block
|
||||
# for performance reasons (redirections are slow).
|
||||
# - We must open the file descriptor right here rather than in _ksi_deferred_init
|
||||
# because there are broken zsh plugins out there that run `exec {fd}< <(cmd)`
|
||||
# and then close the file descriptor more than once while suppressing errors.
|
||||
# This could end up closing our file descriptor if we opened it in
|
||||
# _ksi_deferred_init.
|
||||
typeset -gi _ksi_fd
|
||||
{
|
||||
builtin zmodload zsh/system && (( $+builtins[sysopen] )) && {
|
||||
{ [[ -w $TTY ]] && builtin sysopen -o cloexec -wu _ksi_fd -- $TTY } ||
|
||||
{ [[ -w /dev/tty ]] && builtin sysopen -o cloexec -wu _ksi_fd -- /dev/tty }
|
||||
}
|
||||
} 2>/dev/null || (( _ksi_fd = 1 ))
|
||||
|
||||
# Asks kitty to print $@ to its STDERR. This is for debugging.
|
||||
_ksi_debug_print() {
|
||||
builtin local data
|
||||
data=$(builtin command base64 <<<"${(j: :)@}") || builtin return
|
||||
# Removing all spaces rather than just \n allows this code to
|
||||
# work on broken systems where base64 outputs \r\n.
|
||||
builtin print -nu "$_ksi_fd" '\eP@kitty-print|'"${data//[[:space:]]}"'\e\\'
|
||||
}
|
||||
|
||||
# We defer initialization until precmd for several reasons:
|
||||
#
|
||||
# - Oh My Zsh and many other configs remove zle-line-init and
|
||||
# zle-line-finish hooks when they initialize.
|
||||
# - By deferring initialization we allow user rc files to opt out from some
|
||||
# parts of integration. For example, if a zshrc theme prints OSC 133
|
||||
# marks, it can append " no-prompt-mark" to KITTY_SHELL_INTEGRATION during
|
||||
# initialization to avoid redundant marks from our code.
|
||||
builtin typeset -ag precmd_functions
|
||||
precmd_functions+=(_ksi_deferred_init)
|
||||
|
||||
_ksi_deferred_init() {
|
||||
builtin emulate -L zsh -o no_warn_create_global -o no_aliases
|
||||
|
||||
# Recognized options: no-cursor, no-title, no-prompt-mark, no-complete, no-cwd, no-sudo.
|
||||
builtin local -a opt
|
||||
opt=(${(s: :)KITTY_SHELL_INTEGRATION})
|
||||
builtin unset KITTY_SHELL_INTEGRATION
|
||||
builtin local krcs="$KITTY_SI_RUN_COMMAND_AT_STARTUP"
|
||||
builtin unset KITTY_SI_RUN_COMMAND_AT_STARTUP
|
||||
|
||||
if [[ -n "$SSH_KITTEN_KITTY_DIR" ]]; then
|
||||
if [[ ! "$PATH" =~ (^|:)${SSH_KITTEN_KITTY_DIR}(:|$) ]] && [[ -z "$(builtin command -v kitten)" ]]; then
|
||||
builtin export PATH="${PATH}:${SSH_KITTEN_KITTY_DIR}"
|
||||
fi
|
||||
builtin unset SSH_KITTEN_KITTY_DIR
|
||||
fi
|
||||
|
||||
# The directory where kitty-integration is located: /.../shell-integration/zsh.
|
||||
builtin local self_dir="${functions_source[_ksi_deferred_init]:A:h}"
|
||||
# The directory with _kitty. We store it in a directory of its own rather than
|
||||
# in $self_dir because we are adding it to fpath and we don't want any other
|
||||
# files to be accidentally autoloadable.
|
||||
builtin local comp_dir="$self_dir/completions"
|
||||
|
||||
# Enable completions for `kitty` command.
|
||||
if (( ! opt[(Ie)no-complete] )) && [[ -r $comp_dir/_kitty ]]; then
|
||||
if (( $+functions[compdef] )); then
|
||||
# If compdef is defined, then either compinit has already run or it's
|
||||
# a shim that records all calls for the purpose of replaying them after
|
||||
# compinit. Either way we clobber the existing completion for kitty and
|
||||
# install our own.
|
||||
builtin unset "functions[_kitty]"
|
||||
builtin autoload -Uz -- $comp_dir/_kitty
|
||||
compdef _kitty kitty
|
||||
compdef _kitty clone-in-kitty
|
||||
compdef _kitty kitten
|
||||
fi
|
||||
|
||||
# If compdef is not set, compinit has not run yet. In this case we must
|
||||
# add our completions directory to fpath so that _kitty gets picked up by
|
||||
# compinit.
|
||||
#
|
||||
# We extend fpath even if compinit has run because it might run again.
|
||||
# Without our completions directory in fpath compinit would our _comp
|
||||
# mapping.
|
||||
builtin typeset -ga fpath
|
||||
fpath=($comp_dir ${fpath:#$comp_dir})
|
||||
fi
|
||||
|
||||
# Enable semantic markup with OSC 133.
|
||||
if (( ! opt[(Ie)no-prompt-mark] )); then
|
||||
_ksi_precmd() {
|
||||
builtin local -i cmd_status=$?
|
||||
builtin emulate -L zsh -o no_warn_create_global -o no_aliases
|
||||
|
||||
# Don't write OSC 133 D when our precmd handler is invoked from zle.
|
||||
# Some plugins do that to update prompt on cd.
|
||||
if ! builtin zle; then
|
||||
# This code works incorrectly in the presence of a precmd or chpwd
|
||||
# hook that prints. For example, sindresorhus/pure prints an empty
|
||||
# line on precmd and marlonrichert/zsh-snap prints $PWD on chpwd.
|
||||
# We'll end up writing our OSC 133 D mark too late.
|
||||
#
|
||||
# Another failure mode is when the output of a command doesn't end
|
||||
# with LF and prompst_sp is set (it is by default). In this case
|
||||
# we'll incorrectly state that '%' from prompt_sp is a part of the
|
||||
# command's output.
|
||||
if (( _ksi_state == 1 )); then
|
||||
# The last written OSC 133 C has not been closed with D yet.
|
||||
# Close it and supply status.
|
||||
builtin print -nu $_ksi_fd '\e]133;D;'$cmd_status'\a'
|
||||
(( _ksi_state = 2 ))
|
||||
elif (( _ksi_state == 2 )); then
|
||||
# There might be an unclosed OSC 133 C. Close that.
|
||||
builtin print -nu $_ksi_fd '\e]133;D\a'
|
||||
fi
|
||||
fi
|
||||
|
||||
builtin local mark1=$'%{\e]133;A\a%}'
|
||||
if [[ -o prompt_percent ]]; then
|
||||
builtin typeset -g precmd_functions
|
||||
if [[ ${precmd_functions[-1]} == _ksi_precmd ]]; then
|
||||
# This is the best case for us: we can add our marks to PS1 and
|
||||
# PS2. This way our marks will be printed whenever zsh
|
||||
# redisplays prompt: on reset-prompt, on SIGWINCH, and on
|
||||
# SIGCHLD if notify is set. Themes that update prompt
|
||||
# asynchronously from a `zle -F` handler might still remove our
|
||||
# marks. Oh well.
|
||||
builtin local mark2=$'%{\e]133;A;k=s\a%}'
|
||||
# Add marks conditionally to avoid a situation where we have
|
||||
# several marks in place. These conditions can have false
|
||||
# positives and false negatives though.
|
||||
#
|
||||
# - False positive (with prompt_percent): PS1="%(?.$mark1.)"
|
||||
# - False negative (with prompt_subst): PS1='$mark1'
|
||||
[[ $PS1 == *$mark1* ]] || PS1=${mark1}${PS1}
|
||||
# PS2 mark is needed when clearing the prompt on resize
|
||||
[[ $PS2 == *$mark2* ]] || PS2=${mark2}${PS2}
|
||||
(( _ksi_state = 2 ))
|
||||
else
|
||||
# If our precmd hook is not the last, we cannot rely on prompt
|
||||
# changes to stick, so we don't even try. At least we can move
|
||||
# our hook to the end to have better luck next time. If there is
|
||||
# another piece of code that wants to take this privileged
|
||||
# position, this won't work well. We'll break them as much as
|
||||
# they are breaking us.
|
||||
precmd_functions=(${precmd_functions:#_ksi_precmd} _ksi_precmd)
|
||||
# Plugins that invoke precmd hooks from zle do that before zle
|
||||
# is trashed. This means that the cursor is in the middle of
|
||||
# BUFFER and we cannot print our mark there. Prompt might
|
||||
# already have a mark, so the following reset-prompt will write
|
||||
# it. If it doesn't, there is nothing we can do.
|
||||
if ! builtin zle; then
|
||||
builtin print -rnu $_ksi_fd -- $mark1[3,-3]
|
||||
(( _ksi_state = 2 ))
|
||||
fi
|
||||
fi
|
||||
elif ! builtin zle; then
|
||||
# Without prompt_percent we cannot patch prompt. Just print the
|
||||
# mark, except when we are invoked from zle. In the latter case we
|
||||
# cannot do anything.
|
||||
builtin print -rnu $_ksi_fd -- $mark1[3,-3]
|
||||
(( _ksi_state = 2 ))
|
||||
fi
|
||||
}
|
||||
|
||||
_ksi_preexec() {
|
||||
builtin emulate -L zsh -o no_warn_create_global -o no_aliases
|
||||
|
||||
# This can potentially break user prompt. Oh well. The robustness of
|
||||
# this code can be improved in the case prompt_subst is set because
|
||||
# it'll allow us distinguish (not perfectly but close enough) between
|
||||
# our own prompt, user prompt, and our own prompt with user additions on
|
||||
# top. We cannot force prompt_subst on the user though, so we would
|
||||
# still need this code for the no_prompt_subst case.
|
||||
PS1=${PS1//$'%{\e]133;A\a%}'}
|
||||
PS2=${PS2//$'%{\e]133;A;k=s\a%}'}
|
||||
|
||||
# This will work incorrectly in the presence of a preexec hook that
|
||||
# prints. For example, if MichaelAquilina/zsh-you-should-use installs
|
||||
# its preexec hook before us, we'll incorrectly mark its output as
|
||||
# belonging to the command (as if the user typed it into zle) rather
|
||||
# than command output.
|
||||
builtin print -nu "$_ksi_fd" -f '\e]133;C;cmdline=%q\a' -- "$1"
|
||||
(( _ksi_state = 1 ))
|
||||
}
|
||||
|
||||
# the following two lines are commented out as currently kitty doesn't use B prompt marking
|
||||
# and hooking zle widgets in ZSH is a total minefield, see https://github.com/kovidgoyal/kitty/issues/4428
|
||||
# so we can at least tell users to use no-cursor and with that avoid hooking ZLE widgets at all
|
||||
# functions[_ksi_zle_line_init]+='
|
||||
# builtin print -nu "$_ksi_fd" "\\e]133;B\\a"'
|
||||
fi
|
||||
|
||||
# Enable reporting current working dir to terminal
|
||||
if (( ! opt[(Ie)no-cwd] )); then
|
||||
_ksi_report_pwd() { builtin print -nu $_ksi_fd '\e]7;kitty-shell-cwd://'"$HOST""$PWD"'\a'; }
|
||||
chpwd_functions=(${chpwd_functions[@]} "_ksi_report_pwd")
|
||||
# An executed program could change cwd and report the changed cwd, so also report cwd at each new prompt
|
||||
# as in this case chpwd_functions is insufficient. chpwd_functions is still needed for things like: cd x && something
|
||||
functions[_ksi_precmd]+="
|
||||
_ksi_report_pwd"
|
||||
_ksi_report_pwd
|
||||
fi
|
||||
|
||||
# Enable terminal title changes.
|
||||
if (( ! opt[(Ie)no-title] )); then
|
||||
# We don't use `print -P` because it depends on prompt options, which
|
||||
# we don't control and cannot change.
|
||||
#
|
||||
# We use (V) in preexec to convert control characters to something visible
|
||||
# (LF becomes \n, etc.). This isn't necessary in precmd because (%) does it
|
||||
# for us.
|
||||
builtin local is_ssh_session="n"
|
||||
if [[ -n "$KITTY_PID" ]]; then
|
||||
# kitty running locally
|
||||
elif [[ -n "$SSH_TTY" || -n "$SSH2_TTY$KITTY_WINDOW_ID" ]]; then
|
||||
# connected to most SSH servers
|
||||
# or use ssh kitten to connected to some SSH servers that do not set SSH_TTY
|
||||
is_ssh_session="y"
|
||||
elif [[ -n "$(builtin command -v who)" ]]; then
|
||||
# the shell integration script is installed manually on the remote system
|
||||
# the environment variables are cleared after sudo
|
||||
# OpenSSH's sshd creates entries in utmp for every login so use those
|
||||
[[ "$(builtin command who -m 2> /dev/null)" =~ "\([a-fA-F.:0-9]+\)$" ]] && is_ssh_session="y"
|
||||
fi
|
||||
|
||||
if [[ "$is_ssh_session" == "y" ]]; then
|
||||
functions[_ksi_precmd]+="
|
||||
builtin print -rnu $_ksi_fd \$'\\e]2;'\"\${(V)\${HOST-}/%.*/}: \${(%):-%(4~|…/%3~|%~)}\"\$'\\a'"
|
||||
functions[_ksi_preexec]+="
|
||||
builtin print -rnu $_ksi_fd \$'\\e]2;'\"\${(V)\${HOST-}/%.*/}: \${(V)1}\"\$'\\a'"
|
||||
else
|
||||
functions[_ksi_precmd]+="
|
||||
builtin print -rnu $_ksi_fd \$'\\e]2;'\"\${(%):-%(4~|…/%3~|%~)}\"\$'\\a'"
|
||||
functions[_ksi_preexec]+="
|
||||
builtin print -rnu $_ksi_fd \$'\\e]2;'\"\${(V)1}\"\$'\\a'"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Enable cursor shape changes depending on the current keymap.
|
||||
if (( ! opt[(Ie)no-cursor] )); then
|
||||
# This implementation leaks blinking block cursor into external commands
|
||||
# executed from zle. For example, users of fzf-based widgets may find
|
||||
# themselves with a blinking block cursor within fzf.
|
||||
_ksi_zle_line_init _ksi_zle_line_finish _ksi_zle_keymap_select() {
|
||||
case ${KEYMAP-} in
|
||||
# Blinking block cursor.
|
||||
vicmd|visual) builtin print -nu "$_ksi_fd" '\e[1 q';;
|
||||
# Blinking bar cursor.
|
||||
*) builtin print -nu "$_ksi_fd" '\e[5 q';;
|
||||
esac
|
||||
}
|
||||
# Restore the blinking default shape before executing an external command
|
||||
functions[_ksi_preexec]+="
|
||||
builtin print -rnu $_ksi_fd \$'\\e[0 q'"
|
||||
fi
|
||||
|
||||
|
||||
# Some zsh users manually run `source ~/.zshrc` in order to apply rc file
|
||||
# changes to the current shell. This is a terrible practice that breaks many
|
||||
# things, including our shell integration. For example, Oh My Zsh and Prezto
|
||||
# (both very popular among zsh users) will remove zle-line-init and
|
||||
# zle-line-finish hooks if .zshrc is manually sourced. Prezto will also remove
|
||||
# zle-keymap-select.
|
||||
#
|
||||
# Another common (and much more robust) way to apply rc file changes to the
|
||||
# current shell is `exec zsh`. This will remove our integration from the shell
|
||||
# unless it's explicitly invoked from .zshrc. This is not an issue with
|
||||
# `exec zsh` but rather with our implementation of automatic shell integration.
|
||||
|
||||
# In the ideal world we would use add-zle-hook-widget to hook zle-line-init
|
||||
# and similar widget. This breaks user configs though, so we have do this
|
||||
# horrible thing instead.
|
||||
builtin local hook func widget orig_widget flag
|
||||
for hook in line-init line-finish keymap-select; do
|
||||
func=_ksi_zle_${hook/-/_}
|
||||
(( $+functions[$func] )) || builtin continue
|
||||
widget=zle-$hook
|
||||
if [[ $widgets[$widget] == user:azhw:* &&
|
||||
$+functions[add-zle-hook-widget] -eq 1 ]]; then
|
||||
# If the widget is already hooked by add-zle-hook-widget at the top
|
||||
# level, add our hook at the end. We MUST do it this way. We cannot
|
||||
# just wrap the widget ourselves in this case because it would
|
||||
# trigger bugs in add-zle-hook-widget.
|
||||
add-zle-hook-widget $hook $func
|
||||
else
|
||||
if (( $+widgets[$widget] )); then
|
||||
# There is a widget but it's not from add-zle-hook-widget. We
|
||||
# can rename the original widget, install our own and invoke
|
||||
# the original when we are called.
|
||||
#
|
||||
# Note: The leading dot is to work around bugs in
|
||||
# zsh-syntax-highlighting.
|
||||
orig_widget=._ksi_orig_$widget
|
||||
builtin zle -A $widget $orig_widget
|
||||
if [[ $widgets[$widget] == user:* ]]; then
|
||||
# No -w here to preserve $WIDGET within the original widget.
|
||||
flag=
|
||||
else
|
||||
flag=w
|
||||
fi
|
||||
functions[$func]+="
|
||||
builtin zle $orig_widget -N$flag -- \"\$@\""
|
||||
fi
|
||||
builtin zle -N $widget $func
|
||||
fi
|
||||
done
|
||||
|
||||
# run startup command
|
||||
if [[ -n "$krcs" ]]; then
|
||||
builtin print -nu "$_ksi_fd" -f '\e]2;%s\e\\' -- "${(V)krcs}"
|
||||
# If the command is interrupted with Ctrl-C, zsh aborts the rest of
|
||||
# this function, leaving it in precmd_functions so it runs again on the
|
||||
# next prompt and wraps our zle widgets around themselves, causing
|
||||
# infinite recursion. Clear the interrupt so initialization completes.
|
||||
{
|
||||
builtin eval "$krcs"
|
||||
} always {
|
||||
TRY_BLOCK_INTERRUPT=0
|
||||
}
|
||||
fi
|
||||
|
||||
if (( $+functions[_ksi_preexec] )); then
|
||||
builtin typeset -ag preexec_functions
|
||||
preexec_functions+=(_ksi_preexec)
|
||||
fi
|
||||
|
||||
builtin typeset -ag precmd_functions
|
||||
if (( $+functions[_ksi_precmd] )); then
|
||||
precmd_functions=(${precmd_functions:/_ksi_deferred_init/_ksi_precmd})
|
||||
_ksi_precmd
|
||||
else
|
||||
precmd_functions=(${precmd_functions:#_ksi_deferred_init})
|
||||
fi
|
||||
|
||||
if [ -n "${KITTY_IS_CLONE_LAUNCH}" ]; then
|
||||
builtin local orig_conda_env="$CONDA_DEFAULT_ENV"
|
||||
builtin eval "${KITTY_IS_CLONE_LAUNCH}"
|
||||
builtin hash -r 2> /dev/null 1> /dev/null
|
||||
builtin local venv="${VIRTUAL_ENV}/bin/activate"
|
||||
builtin local sourced=""
|
||||
_ksi_s_is_ok() {
|
||||
[[ -z "$sourced" && "$KITTY_CLONE_SOURCE_STRATEGIES" == *",$1,"* ]] && builtin return 0
|
||||
builtin return 1
|
||||
}
|
||||
|
||||
if _ksi_s_is_ok "venv" && [[ -n "${VIRTUAL_ENV}" && -r "$venv" ]]; then
|
||||
sourced="y"
|
||||
builtin unset VIRTUAL_ENV
|
||||
builtin source "$venv"
|
||||
fi; if _ksi_s_is_ok "conda" && [[ -n "${CONDA_DEFAULT_ENV}" && (( $+commands[conda] )) && "${CONDA_DEFAULT_ENV}" != "$orig_conda_env" ]]; then
|
||||
sourced="y"
|
||||
conda activate "${CONDA_DEFAULT_ENV}"
|
||||
fi; if _ksi_s_is_ok "env_var" && [[ -n "${KITTY_CLONE_SOURCE_CODE}" ]]; then
|
||||
sourced="y"
|
||||
builtin eval "${KITTY_CLONE_SOURCE_CODE}"
|
||||
fi; if _ksi_s_is_ok "path" && [[ -r "${KITTY_CLONE_SOURCE_PATH}" ]]; then
|
||||
sourced="y"
|
||||
builtin source "${KITTY_CLONE_SOURCE_PATH}"
|
||||
fi
|
||||
builtin unfunction _ksi_s_is_ok
|
||||
# Ensure PATH has no duplicate entries
|
||||
builtin typeset -gxU PATH="$PATH"
|
||||
fi
|
||||
builtin unset KITTY_IS_CLONE_LAUNCH KITTY_CLONE_SOURCE_STRATEGIES
|
||||
|
||||
builtin alias edit-in-kitty="kitten edit-in-kitty"
|
||||
|
||||
if (( ! opt[(Ie)no-sudo] )) ; then
|
||||
if [[ -n "$TERMINFO" && ! ( -r "/usr/share/terminfo/x/xterm-kitty" || -r "/usr/share/terminfo/78/xterm-kitty" ) ]]; then
|
||||
sudo() {
|
||||
# Ensure terminfo is available in sudo
|
||||
builtin local cannot_set_env_var="n"
|
||||
builtin local ignore_arg="n"
|
||||
for arg; do
|
||||
if [[ "$ignore_arg" == "y" ]]; then ignore_arg="n"; builtin continue; fi
|
||||
case "$arg" in
|
||||
--) builtin break ;; # end of options
|
||||
# sudo -e disallows setting env vars
|
||||
--edit | -e* | -[!-]*e*) cannot_set_env_var="y"; builtin break ;;
|
||||
# sudo-rs -v disallows setting env vars
|
||||
--validate | -v* | -[!-]*v*) cannot_set_env_var="y"; builtin break ;;
|
||||
# flags that require a following argument
|
||||
--user|--group|--host|--chdir|--chroot|--role|--type|--command-timeout|--auth-type|--login-class|--prompt|--close-from|--other-user) ignore_arg="y" ;;
|
||||
--*) ;; # misc long opt
|
||||
-*a|-*C|-*c|-*D|-*g|-*h|-*p|-*R|-*r|-*t|-*T|-*u) ignore_arg="y" ;;
|
||||
# flag or env var setting
|
||||
-* | *=*) ;;
|
||||
*) builtin break ;; # command found
|
||||
esac
|
||||
done
|
||||
if [[ "$cannot_set_env_var" == "y" ]]; then
|
||||
builtin command sudo "$@";
|
||||
else
|
||||
builtin command sudo TERMINFO="$TERMINFO" "$@";
|
||||
fi
|
||||
}
|
||||
if (( $+commands[run0] && ! $+functions[run0] )); then
|
||||
run0() {
|
||||
# Ensure terminfo is available in run0, --setenv=NAME copies NAME from the current env
|
||||
builtin command run0 --setenv=TERMINFO "$@";
|
||||
}
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Map alt+left/right to move by word if not already mapped. This is expected behavior on macOS and I am tired
|
||||
# of answering questions about it.
|
||||
[[ $(builtin bindkey "^[[1;3C") == *" undefined-key" ]] && builtin bindkey "^[[1;3C" "forward-word"
|
||||
[[ $(builtin bindkey "^[[1;3D") == *" undefined-key" ]] && builtin bindkey "^[[1;3D" "backward-word"
|
||||
|
||||
# Unfunction _ksi_deferred_init to save memory. Don't unfunction
|
||||
# kitty-integration though because decent public functions aren't supposed to
|
||||
# to unfunction themselves when invoked. Unfunctioning is done by calling code.
|
||||
builtin unfunction _ksi_deferred_init
|
||||
|
||||
}
|
||||
|
||||
_ksi_transmit_data() {
|
||||
builtin local data="${1//[[:space:]]}"
|
||||
builtin local pos=0
|
||||
builtin local chunk_num=0
|
||||
while [ $pos -lt ${#data} ]; do
|
||||
builtin local chunk="${data:$pos:2048}"
|
||||
pos=$(($pos+2048))
|
||||
builtin print -nu "$_ksi_fd" -f '\eP@kitty-%s|%s:%s\e\\' "${2}" "${chunk_num}" "${chunk}"
|
||||
chunk_num=$(($chunk_num+1))
|
||||
done
|
||||
# save history so it is available in new shell
|
||||
[ "$3" = "save_history" ] && builtin fc -AI
|
||||
builtin print -nu "$_ksi_fd" -f '\eP@kitty-%s|\e\\' "${2}"
|
||||
}
|
||||
|
||||
clone-in-kitty() {
|
||||
builtin local data="shell=zsh,pid=$$,cwd=$(builtin printf "%s" "$PWD" | builtin command base64)"
|
||||
while :; do
|
||||
case "$1" in
|
||||
"") break;;
|
||||
-h|--help)
|
||||
builtin printf "%s\n\n%s\n" "Clone the current zsh session into a new kitty window." "For usage instructions see: https://sw.kovidgoyal.net/kitty/shell-integration/#clone-shell"
|
||||
builtin return
|
||||
;;
|
||||
*) data="$data,a=$(builtin printf "%s" "$1" | builtin command base64)";;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
builtin local env
|
||||
builtin local env_vars
|
||||
builtin local varname
|
||||
env_vars=(${(f)"$(builtin export)"})
|
||||
for i in $env_vars; do
|
||||
varname="${i%%=*}"
|
||||
env="${env}$(builtin printf "%s=%s\0" "$varname" "${(P)varname}")"
|
||||
done
|
||||
data="$data,env=$(builtin printf "%s" "$env" | builtin command base64)"
|
||||
_ksi_transmit_data "$data" "clone" "save_history"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/zsh
|
||||
#
|
||||
# This file can get sourced with aliases enabled. Moreover, it be sourced from
|
||||
# zshrc, so the chance of having some aliases already defined is high. To avoid
|
||||
# alias expansion we quote everything that can be quoted. Some aliases will
|
||||
# still break us. For example:
|
||||
#
|
||||
# alias -g -- -r='$RANDOM'
|
||||
#
|
||||
# For this reason users are discouraged from sourcing kitty.zsh in favor of
|
||||
# invoking kitty-integration directly.
|
||||
|
||||
# ${(%):-%x} is the path to the current file.
|
||||
# On top of it we add :A:h to get the directory.
|
||||
'builtin' 'typeset' _ksi_file="${${(%):-%x}:A:h}"/kitty-integration
|
||||
if [[ -r "$_ksi_file" ]]; then
|
||||
'builtin' 'autoload' '-Uz' '--' "$_ksi_file"
|
||||
"${_ksi_file:t}"
|
||||
'builtin' 'unfunction' '--' "${_ksi_file:t}"
|
||||
fi
|
||||
'builtin' 'unset' '_ksi_file'
|
||||
Reference in new issue
Block a user