first commit

This commit is contained in:
Arctic 2025-07-04 11:48:40 -05:00
commit 0610f4aeab
130 changed files with 9897 additions and 0 deletions

1
.gitattributes vendored Normal file
View file

@ -0,0 +1 @@
* text eol=lf

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*.zwc
/fn/-z4h-compinit-impl

14
.tmux.conf Normal file
View file

@ -0,0 +1,14 @@
unbind -a
set -g prefix None
set -g prefix2 None
set -g escape-time 1
set -g status off
set -g automatic-rename off
set -g set-titles on
set -g set-titles-string "#T"
set -g history-limit 0
set -g message-limit 0
set -g assume-paste-time 0
set -ga update-environment ' VTE_VERSION KITTY_LISTEN_ON GUAKE_TAB_UUID NVIM NVIM_LISTEN_ADDRESS VIMRUNTIME VIM _Z4H_LINES _Z4H_COLUMNS _Z4H_ORIG_CWD'
set -s set-clipboard on
set -as terminal-overrides ',*:Ms=\E]52;%p1%s;%p2%s\007'

45
.zshenv Normal file
View file

@ -0,0 +1,45 @@
# Documentation: https://github.com/romkatv/zsh4humans/blob/v5/README.md.
#
# Do not modify this file unless you know exactly what you are doing.
# It is strongly recommended to keep all shell customization and configuration
# (including exported environment variables such as PATH) in ~/.zshrc or in
# files sourced from ~/.zshrc. If you are certain that you must export some
# environment variables in ~/.zshenv, do it where indicated by comments below.
if [ -n "${ZSH_VERSION-}" ]; then
# If you are certain that you must export some environment variables
# in ~/.zshenv (see comments at the top!), do it here:
#
# export GOPATH=$HOME/go
#
# Do not change anything else in this file.
: ${ZDOTDIR:=~}
setopt no_global_rcs
[[ -o no_interactive && -z "${Z4H_BOOTSTRAPPING-}" ]] && return
setopt no_rcs
unset Z4H_BOOTSTRAPPING
fi
Z4H_URL="https://raw.githubusercontent.com/romkatv/zsh4humans/v5"
: "${Z4H:=${XDG_CACHE_HOME:-$HOME/.cache}/zsh4humans/v5}"
umask o-w
if [ ! -e "$Z4H"/z4h.zsh ]; then
mkdir -p -- "$Z4H" || return
>&2 printf '\033[33mz4h\033[0m: fetching \033[4mz4h.zsh\033[0m\n'
if command -v curl >/dev/null 2>&1; then
curl -fsSL -- "$Z4H_URL"/z4h.zsh >"$Z4H"/z4h.zsh.$$ || return
elif command -v wget >/dev/null 2>&1; then
wget -O- -- "$Z4H_URL"/z4h.zsh >"$Z4H"/z4h.zsh.$$ || return
else
>&2 printf '\033[33mz4h\033[0m: please install \033[32mcurl\033[0m or \033[32mwget\033[0m\n'
return 1
fi
mv -- "$Z4H"/z4h.zsh.$$ "$Z4H"/z4h.zsh || return
fi
. "$Z4H"/z4h.zsh || return
setopt rcs

100
.zshrc Normal file
View file

@ -0,0 +1,100 @@
# Personal Zsh configuration file. It is strongly recommended to keep all
# shell customization and configuration (including exported environment
# variables such as PATH) in this file or in files sourced from it.
#
# Documentation: https://github.com/romkatv/zsh4humans/blob/v5/README.md.
# Periodic auto-update on Zsh startup: 'ask' or 'no'.
# You can manually run `z4h update` to update everything.
zstyle ':z4h:' auto-update 'no'
# Ask whether to auto-update this often; has no effect if auto-update is 'no'.
zstyle ':z4h:' auto-update-days '28'
# Keyboard type: 'mac' or 'pc'.
zstyle ':z4h:bindkey' keyboard 'pc'
# Mark up shell's output with semantic information.
zstyle ':z4h:' term-shell-integration 'yes'
# Right-arrow key accepts one character ('partial-accept') from
# command autosuggestions or the whole thing ('accept')?
zstyle ':z4h:autosuggestions' forward-char 'accept'
# Recursively traverse directories when TAB-completing files.
zstyle ':z4h:fzf-complete' recurse-dirs 'no'
# Enable direnv to automatically source .envrc files.
zstyle ':z4h:direnv' enable 'no'
# Show "loading" and "unloading" notifications from direnv.
zstyle ':z4h:direnv:success' notify 'yes'
# Enable ('yes') or disable ('no') automatic teleportation of z4h over
# SSH when connecting to these hosts.
zstyle ':z4h:ssh:example-hostname1' enable 'yes'
zstyle ':z4h:ssh:*.example-hostname2' enable 'no'
# The default value if none of the overrides above match the hostname.
zstyle ':z4h:ssh:*' enable 'no'
# Send these files over to the remote host when connecting over SSH to the
# enabled hosts.
zstyle ':z4h:ssh:*' send-extra-files '~/.nanorc' '~/.env.zsh'
# Clone additional Git repositories from GitHub.
#
# This doesn't do anything apart from cloning the repository and keeping it
# up-to-date. Cloned files can be used after `z4h init`. This is just an
# example. If you don't plan to use Oh My Zsh, delete this line.
z4h install ohmyzsh/ohmyzsh || return
# Install or update core components (fzf, zsh-autosuggestions, etc.) and
# initialize Zsh. After this point console I/O is unavailable until Zsh
# is fully initialized. Everything that requires user interaction or can
# perform network I/O must be done above. Everything else is best done below.
z4h init || return
# Extend PATH.
path=(~/bin $path)
# Export environment variables.
export GPG_TTY=$TTY
# Source additional local files if they exist.
z4h source ~/.env.zsh
# Use additional Git repositories pulled in with `z4h install`.
#
# This is just an example that you should delete. It does nothing useful.
z4h source ohmyzsh/ohmyzsh/lib/diagnostics.zsh # source an individual file
z4h load ohmyzsh/ohmyzsh/plugins/emoji-clock # load a plugin
# Define key bindings.
z4h bindkey z4h-backward-kill-word Ctrl+Backspace Ctrl+H
z4h bindkey z4h-backward-kill-zword Ctrl+Alt+Backspace
z4h bindkey undo Ctrl+/ Shift+Tab # undo the last command line change
z4h bindkey redo Alt+/ # redo the last undone command line change
z4h bindkey z4h-cd-back Alt+Left # cd into the previous directory
z4h bindkey z4h-cd-forward Alt+Right # cd into the next directory
z4h bindkey z4h-cd-up Alt+Up # cd into the parent directory
z4h bindkey z4h-cd-down Alt+Down # cd into a child directory
# Autoload functions.
autoload -Uz zmv
# Define functions and completions.
function md() { [[ $# == 1 ]] && mkdir -p -- "$1" && cd -- "$1" }
compdef _directories md
# Define named directories: ~w <=> Windows home directory on WSL.
[[ -z $z4h_win_home ]] || hash -d w=$z4h_win_home
# Define aliases.
alias tree='tree -a -I .git'
# Add flags to existing aliases.
alias ls="${aliases[ls]:-ls} -A"
# Set shell options: http://zsh.sourceforge.net/Doc/Release/Options.html.
setopt glob_dots # no special treatment for file names with a leading dot
setopt no_auto_menu # require an extra TAB press to open the completion menu

97
.zshrc.mac Normal file
View file

@ -0,0 +1,97 @@
# Personal Zsh configuration file. It is strongly recommended to keep all
# shell customization and configuration (including exported environment
# variables such as PATH) in this file or in files sourced from it.
#
# Documentation: https://github.com/romkatv/zsh4humans/blob/v5/README.md.
# Periodic auto-update on Zsh startup: 'ask' or 'no'.
# You can manually run `z4h update` to update everything.
zstyle ':z4h:' auto-update 'no'
# Ask whether to auto-update this often; has no effect if auto-update is 'no'.
zstyle ':z4h:' auto-update-days '28'
# Keyboard type: 'mac' or 'pc'.
zstyle ':z4h:bindkey' keyboard 'mac'
# Mark up shell's output with semantic information.
zstyle ':z4h:' term-shell-integration 'yes'
# Right-arrow key accepts one character ('partial-accept') from
# command autosuggestions or the whole thing ('accept')?
zstyle ':z4h:autosuggestions' forward-char 'accept'
# Recursively traverse directories when TAB-completing files.
zstyle ':z4h:fzf-complete' recurse-dirs 'no'
# Enable direnv to automatically source .envrc files.
zstyle ':z4h:direnv' enable 'no'
# Show "loading" and "unloading" notifications from direnv.
zstyle ':z4h:direnv:success' notify 'yes'
# Enable ('yes') or disable ('no') automatic teleportation of z4h over
# SSH when connecting to these hosts.
zstyle ':z4h:ssh:example-hostname1' enable 'yes'
zstyle ':z4h:ssh:*.example-hostname2' enable 'no'
# The default value if none of the overrides above match the hostname.
zstyle ':z4h:ssh:*' enable 'no'
# Send these files over to the remote host when connecting over SSH to the
# enabled hosts.
zstyle ':z4h:ssh:*' send-extra-files '~/.nanorc' '~/.env.zsh'
# Clone additional Git repositories from GitHub.
#
# This doesn't do anything apart from cloning the repository and keeping it
# up-to-date. Cloned files can be used after `z4h init`. This is just an
# example. If you don't plan to use Oh My Zsh, delete this line.
z4h install ohmyzsh/ohmyzsh || return
# Install or update core components (fzf, zsh-autosuggestions, etc.) and
# initialize Zsh. After this point console I/O is unavailable until Zsh
# is fully initialized. Everything that requires user interaction or can
# perform network I/O must be done above. Everything else is best done below.
z4h init || return
# Extend PATH.
path=(~/bin $path)
# Export environment variables.
export GPG_TTY=$TTY
# Source additional local files if they exist.
z4h source ~/.env.zsh
# Use additional Git repositories pulled in with `z4h install`.
#
# This is just an example that you should delete. It does nothing useful.
z4h source ohmyzsh/ohmyzsh/lib/diagnostics.zsh # source an individual file
z4h load ohmyzsh/ohmyzsh/plugins/emoji-clock # load a plugin
# Define key bindings.
z4h bindkey undo Ctrl+/ Shift+Tab # undo the last command line change
z4h bindkey redo Option+/ # redo the last undone command line change
z4h bindkey z4h-cd-back Shift+Left # cd into the previous directory
z4h bindkey z4h-cd-forward Shift+Right # cd into the next directory
z4h bindkey z4h-cd-up Shift+Up # cd into the parent directory
z4h bindkey z4h-cd-down Shift+Down # cd into a child directory
# Autoload functions.
autoload -Uz zmv
# Define functions and completions.
function md() { [[ $# == 1 ]] && mkdir -p -- "$1" && cd -- "$1" }
compdef _directories md
# Define named directories: ~w <=> Windows home directory on WSL.
[[ -z $z4h_win_home ]] || hash -d w=$z4h_win_home
# Define aliases.
alias tree='tree -a -I .git'
# Add flags to existing aliases.
alias ls="${aliases[ls]:-ls} -A"
# Set shell options: http://zsh.sourceforge.net/Doc/Release/Options.html.
setopt glob_dots # no special treatment for file names with a leading dot
setopt no_auto_menu # require an extra TAB press to open the completion menu

34
fn/-z4h-autosuggest-fetch Normal file
View file

@ -0,0 +1,34 @@
#!/usr/bin/env zsh
if [[ -z $BUFFER || $CONTEXT != start ]]; then
unset POSTDISPLAY _z4h_autosuggest_buffer _z4h_autosuggestion
else
() {
if [[ "$BUFFER" == "${_z4h_autosuggest_buffer-}"* ]]; then
if (( ${#BUFFER} == ${#_z4h_autosuggest_buffer} )); then
return
elif [[ -v _z4h_autosuggestion ]]; then
if [[ -z "$_z4h_autosuggestion" ]]; then
return
elif [[ $POSTDISPLAY == ${BUFFER:${#_z4h_autosuggest_buffer}}* ]]; then
POSTDISPLAY="${POSTDISPLAY:$((${#BUFFER} - ${#_z4h_autosuggest_buffer}))}"
typeset -g _z4h_autosuggest_buffer="$BUFFER"
return
fi
fi
fi
local suggestion
if [[ ${+_ZSH_AUTOSUGGEST_DISABLED} == 0 &&
${#BUFFER} -le ${ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE:-${#BUFFER}} ]]; then
_zsh_autosuggest_fetch_suggestion "$BUFFER"
fi
POSTDISPLAY=${suggestion:${#BUFFER}}
typeset -g _z4h_autosuggest_buffer="$BUFFER"
typeset -g _z4h_autosuggestion="$suggestion"
}
fi
if [[ -n $POSTDISPLAY ]]; then
region_highlight+=(
"${#BUFFER} $((${#BUFFER} + ${#POSTDISPLAY})) $ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE")
fi

11
fn/-z4h-cd-rotate Normal file
View file

@ -0,0 +1,11 @@
#!/usr/bin/env zsh
(( ${+_z4h_dir_hist_fd} )) && -z4h-update-dir-history
() {
eval "$_z4h_opt"
while (( $#dirstack )) && ! pushd -q $1 &>/dev/null; do
popd -q $1
done
(( $#dirstack ))
} "$@" && -z4h-redraw-prompt

25
fn/-z4h-check-rc-zwcs Normal file
View file

@ -0,0 +1,25 @@
#!/usr/bin/env zsh
zstyle -T :z4h: check-orphan-rc-zwc || return 0
local -a zwcs=($@)
local -a rcs=(${^@:r}(N))
if (( $#rcs != $#zwcs )); then
local home=~
local zdotdir=${${${(q)ZDOTDIR}/#${(q)home}/'~'}//\%/%%}
print -Pru2 -- "%F{3}z4h%f: detected %F{1}orphan zwc files%f"
print -Pru2 -- ""
local rc rm_args=()
for rc in ${${(@)zwcs:r}:|rcs}; do
rm_args+=("%U$zdotdir/${rc:t}.zwc%u")
print -Pru2 -- " $rm_args[-1]"
done
print -Pru2 -- ""
print -Pru2 -- "It is highly recommended to delete them:"
print -Pru2 -- ""
print -Pru2 -- " %F{2}rm%f -f -- ${(j: :)rm_args}"
print -Pru2 -- ""
fi
return 0

123
fn/-z4h-chsh Normal file
View file

@ -0,0 +1,123 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local user=${(%):-%n}
[[ -n $user && -r /etc/shells && $_z4h_exe == /* && -x $_z4h_exe &&
$user != cloudshell-user && -t 0 && -t 1 && -t 2 ]] || return 0
if [[ $OSTYPE == linux* ]]; then
[[ -r /etc/passwd ]] || return 0
if (( ! $+commands[chsh] )); then
[[ $+commands[sudo] == 1 || -w /etc ]] || return 0
fi
local passwd
passwd="$(</etc/passwd)" || return '_z4h_err()'
local -a match mbegin mend
[[ $passwd == (#b)*((#s)|$'\n')$user:[^$'\n']#:([^:]##)((#e)|$'\n')* ]] || return 0
local login_shell=$match[2]
elif [[ $OSTYPE == darwin* ]]; then
(( $+commands[dscl] && $+commands[chsh] )) || return 0
local login_shell
login_shell=$(dscl . -read ~/ UserShell) || return '_z4h_err()'
[[ $login_shell == 'UserShell: /'* ]] || return '_z4h_err()'
login_shell=${login_shell#UserShell: }
else
return 0
fi
[[ -x $login_shell && ! $login_shell -ef $_z4h_exe ]] || return 0
local -a shells
shells=(${(f)"$(</etc/shells)"}) || return '_z4h_err()'
local my_shell=$shells[(re)$_z4h_exe]
if [[ -z $my_shell ]]; then
local shell
for shell in $shells; do
if [[ $shell -ef $_z4h_exe ]]; then
my_shell=$shell
break
fi
done
fi
[[ -n $my_shell || $+commands[sudo] == 1 || -w /etc/shells ]] || return 0
-z4h-flowing -- %F{3}z4h%f: login shell isn\'t the same as this shell
print -Pr -- ""
print -Pr -- " user %F{3}${user//\%/%%}%f"
print -Pr -- " login shell %F{2}${login_shell//\%/%%}%f"
print -Pr -- " this shell %F{2}${${my_shell:-$_z4h_exe}//\%/%%}%f"
print -Pr -- ""
-z4h-flowing -- Change login shell of "%F{3}${user//\%/%%}%f" to "%F{2}${${my_shell:-$_z4h_exe}//\%/%%}%f?"
print -Pr -- ""
print -Pr -- " %B(y)%b Yes. %BRecommended%b."
print -Pr -- " %B(n)%b No."
print -Pr -- ""
(
trap '' INT
(
local -i error
while true; do
if (( error )); then
print -Pr -- ''
print -Pr -- 'Bummer! Try again?'
print -Pr -- ""
print -Pr -- " %B(y)%b Yes."
print -Pr -- " %B(n)%b No."
print -Pr -- ""
fi
print -Prn -- "%BChoice [yn]:%b "
{
read -k choice || return
} always {
[[ $choice == $'\n' ]] || print
}
if [[ $choice == (n|N) ]]; then
print
print -rn >$Z4H/stickycache/no-chsh || return '_z4h_err()'
local home=~
local zdotdir=${${${(q)ZDOTDIR}/#${(q)home}/'~'}//\%/%%}
print -Pr -- "Won't ask again unless %U\$Z4H/stickycache/no-chsh%u is deleted."
return 1
fi
[[ $choice == $'\n' ]] && continue
if [[ $choice != (y|Y) ]]; then
print -Pr -- '%F{3}z4h%f: invalid choice: '${(q-)choice//\%/%%}
continue
fi
error=1
print
if [[ -z $my_shell ]]; then
print -Pr -- "Adding %F{2}${_z4h_exe//\%/%%}%f to %U/etc/shells%u."
local precmd=(command)
[[ -w /etc/shells ]] || precmd+=(sudo)
$precmd tee -a /etc/shells >/dev/null <<<$_z4h_exe || continue
my_shell=$_z4h_exe
(( $#precmd == 1 )) || print
fi
print -Pr -- "Changing login shell to %F{2}${my_shell//\%/%%}%f."
if (( $+commands[chsh] )); then
command chsh -s $my_shell || continue
else
local MATCH MBEGIN MEND
local p=("${(@)${(@f)passwd}/#%(#m)$user:*/${MATCH%:*}:$my_shell}")
if [[ ${(F)p} == $passwd ]]; then
print -Pru2 -- '%F{3}z4h%f: %F{1}internal error%f'
return '_z4h_err()'
fi
local precmd=(command)
[[ -w /etc ]] || precmd+=(sudo)
$precmd tee -- /etc/passwd.bak.$$ >/dev/null <<<${(F)p} || continue
$precmd mv -f -- /etc/passwd.bak.$$ /etc/passwd || continue
fi
print -Pr -- "Changed login shell of %F{3}${user//\%/%%}%f to %F{2}${my_shell//\%/%%}%f."
print
return 0
done
)
) && export SHELL=${my_shell:-$_z4h_exe}

54
fn/-z4h-cmd-bindkey Normal file
View file

@ -0,0 +1,54 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
zparseopts -D -F -- || return '_z4h_err()'
if (( ARGC < 2 )); then
-z4h-help-bindkey >&2
return 1
fi
(( ${+_z4h_key} )) || return 0
local kb seq seqs new_seqs
for kb in ${@:2}; do
seqs=('')
for kb in ${(@s: :)kb}; do
if [[ -n ${seq::=$_z4h_key[$kb]} ]]; then
seqs=(${^seqs}$seq)
else
case $kb in
?~[a-z])
seqs=(${^seqs}$kb ${^seqs}${(L)kb})
;;
Ctrl+[A-Z'[]\'])
seqs=(${^seqs}'^'$kb[-1])
;;
(Alt|Option)+[A-Z'[]\/.,'])
new_seqs=(${^seqs}'^['$kb[-1] ${^seqs}'^['${(L)kb[-1]})
if zstyle -T :z4h:bindkey macos-option-as-alt &&
[[ -n ${seq::=$_z4h_macos_opt_key[$kb[-1]]} ]]; then
new_seqs+=(${^seqs}$seq)
if [[ -n ${seq::=$_z4h_macos_opt_key[${(L)kb[-1]}]} ]]; then
new_seqs+=(${^seqs}$seq)
fi
fi
seqs=($new_seqs)
;;
Ctrl+(Alt|Option)+[A-Z'[]\'])
seqs=(${^seqs}'^[^'$kb[-1])
;;
*)
print -Pru2 -- '%F{3}z4h%f: invalid key binding: %F{1}'${kb//\%/%%}'%f'
return '_z4h_err()'
;;
esac
fi
done
done
for seq in ${(u)seqs}; do
builtin bindkey -- $seq $1
done

9
fn/-z4h-cmd-compile Normal file
View file

@ -0,0 +1,9 @@
#!/usr/bin/env zsh
local file
zparseopts -D -F -- || return '_z4h_err()'
emulate zsh -o extended_glob -c 'local files=(${^@}(N))'
builtin set --
for file in "${files[@]}"; do
-z4h-compile "$file"
done

7
fn/-z4h-cmd-docker Normal file
View file

@ -0,0 +1,7 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local term
zstyle -s :z4h:docker term term || term=${TERM:/tmux-256color/screen-256color}
TERM=${term:-$TERM} command docker "$@"

54
fn/-z4h-cmd-help Normal file
View file

@ -0,0 +1,54 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
if (( ARGC == 1 )); then
case $1 in
install)
print -Pr -- "Usage: %F{2}z4h%f %Binstall%b [-f|--force] [%Uuser/project[@branch]%u]..."
print -Pr -- ""
print -Pr -- "Clone or update GitHub project(s)."
;;
update)
print -Pr -- "Usage: %F{2}z4h%f %Bupdate%b"
print -Pr -- ""
print -Pr -- "Update %Bzsh4humans%b and all dependencies (%Bfzf%b, %Bzsh-autosuggestions%b, etc.)."
;;
init)
print -Pr -- "Usage: %F{2}z4h%f %Binit%b"
print -Pr -- ""
print -Pr -- "Initialize Zsh. Should be called just once from %U.zshrc%u."
;;
help)
print -Pr -- "Usage: %F{2}z4h%f %Bhelp%b [%Ucommand%u]"
print -Pr -- ""
print -Pr -- "Print help for the command."
;;
*)
if (( $+functions[-z4h-help-$1] )); then
-z4h-help-$1
else
print -Pru2 -- "%F{3}z4h%f: unknown command: %F{1}${1//\%/%%}%f"
return 1
fi
;;
esac
return
fi
if (( ARGC == 0 )); then
local fd=1 ret=0
else
local fd=2 ret=1
fi
print -Pru$fd -- "Usage: %F{2}z4h%f %Binstall%b [-f|--force] [%Uuser/project[@branch]%u]..."
print -Pru$fd -- " %Bupdate%b"
print -Pru$fd -- " %Binit%b"
print -Pru$fd -- " %Bsource%b [-c|--compile] [--] [%Ufile%u]..."
print -Pru$fd -- " %Bcompile%b [--] [%Ufile%u]..."
print -Pru$fd -- " %Bload%b [-c|--compile] [--] [%Udir%u]..."
print -Pru$fd -- " %Bbindkey%b [--] zle-widget [key-binding] [key-binding]..."
print -Pru$fd -- " %Bssh%b [%Ussh-options%u] [%Uuser@%u]%Uhostname%u"
print -Pru$fd -- " %Bhelp%b [%Ucommand%u]"
return ret

519
fn/-z4h-cmd-ssh Normal file
View file

@ -0,0 +1,519 @@
#!/usr/bin/env zsh
# TODO: write proper docs for these configuration options.
#
# zstyle ':z4h:ssh:my_host' enable 'yes'
# zstyle ':z4h:ssh:*' send-extra-files '~/foo' '"$ZDOTDIR"/bar'
# zstyle ':z4h:ssh:*' retrieve-extra-files '~/foo' '"$ZDOTDIR"/bar'
# zstyle ':z4h:ssh:*' ssh-command command ssh
# zstyle ':z4h:ssh:*' retrieve-history $ZDOTDIR/.zsh_history.remote
# zstyle ':z4h:ssh:*' term tmux-256color
#
# z4h-ssh-configure() {
# z4h_ssh_prelude+=(
# "export BLAH=${(q)BLAH}"
# )
# z4h_ssh_send_files+=(
# ~/foo '~/foo'
# $ZDOTDIR/bar '"$ZDOTDIR"/bar'
# )
# z4h_ssh_setup+=(
# 'echo "setting up"'
# )
# z4h_ssh_run=(
# 'echo "starting z4h"'
# $z4h_ssh_launch_commands
# )
# z4h_ssh_teardown+=(
# 'echo "tearing down"'
# )
# z4h_ssh_retrieve_files+=(
# '~/foo' ~/foo
# '"$ZDOTDIR"/bar' $ZDOTDIR/bar
# )
# }
eval "$_z4h_opt"
-z4h-check-core-params || return
if (( _z4h_dangerous_root )); then
print -Pru2 -- "%F{3}z4h%f: refusing to %Bssh%b as %F{1}root%f"
return 1
fi
local -i must_passthrough i
local -a pos
for ((i = 1; i <= $#; ++i)); do
case $*[i] in
--) (( ++i <= $# )) && pos+=({$i..$#}); break;;
-[OG]) must_passthrough=1; ((++i));;
-*) [[ bcDEeFIiJLlmOopQRSWw == *${${*[i]}[-1]}* ]] && ((++i));;
*) pos+=($i);;
esac
done
local z4h_min_version
z4h_min_version=${$(<$Z4H/zsh4humans/version)%$'\r'} || return
if [[ $z4h_min_version != <1-> ]]; then
print -Pru2 -- '%F{3}z4h%f: invalid file content: %F{1}%U$Z4H/zsh4humans/version%f%u'
return 1
fi
local -r z4h_min_version
local -r z4h_ssh_client=${${(%):-%m}:-unknown}
local z4h_ssh_host
if (( $#pos == 1 )); then
local user_host=$*[pos[1]]
z4h_ssh_host=${${user_host##*@}%%:*}
fi
local -r z4h_ssh_host
[[ -n $z4h_ssh_host ]] || must_passthrough=1
local -i z4h_ssh_enable=$(( !must_passthrough ))
zstyle -t :z4h:ssh:$z4h_ssh_host enable || z4h_ssh_enable=0
local -i mkdir_control_master=0
local default_ssh_command=(command ssh)
if (( z4h_ssh_enable )); then
mkdir_control_master=1
default_ssh_command+=(
-o ControlMaster=auto
-o ControlPersist=5
-o ControlPath='~/.ssh/s/%C')
fi
local -a z4h_ssh_command
if ! zstyle -a :z4h:ssh:$z4h_ssh_host ssh-command z4h_ssh_command; then
z4h_ssh_command=($default_ssh_command)
fi
local term
zstyle -s :z4h:ssh:$z4h_ssh_host term term || term=${TERM:/tmux-256color/screen-256color}
local -A z4h_ssh_send_files z4h_ssh_retrieve_files
local -a z4h_ssh_prelude z4h_ssh_setup z4h_ssh_run z4h_ssh_teardown
local -aU z4h_retrieve_history
if (( !must_passthrough )); then
z4h_ssh_prelude=(
'"export" ZDOTDIR="$HOME"'
'if command -v "locale" >"/dev/null" 2>&1; then
"export" LC_ALL="C"
fi')
z4h_ssh_send_files=(
$ZDOTDIR/.zshenv '"$ZDOTDIR"/.zshenv'
$ZDOTDIR/.zprofile '"$ZDOTDIR"/.zprofile'
$ZDOTDIR/.zshrc '"$ZDOTDIR"/.zshrc'
$ZDOTDIR/.zlogin '"$ZDOTDIR"/.zlogin'
$ZDOTDIR/.zlogout '"$ZDOTDIR"/.zlogout')
local file
for file in $ZDOTDIR/.p10k{,-ascii}{,-8color}.zsh(N) $ZDOTDIR/.zsh_history.*:$z4h_ssh_host(N); do
z4h_ssh_send_files[$file]='"$ZDOTDIR"/'${(q)file:t}
done
local -a extra_files
if zstyle -a :z4h:ssh:$z4h_ssh_host send-extra-files extra_files; then
local src dst
for dst in $extra_files; do
eval "src=$dst"
z4h_ssh_send_files[$src]=$dst
done
fi
z4h_ssh_run=(
'if "[" "-f" "$ZDOTDIR"/.zshenv "-a" "-r" "$ZDOTDIR"/.zshenv "]"; then
"." "$ZDOTDIR"/.zshenv
else
>&2 "printf" "\\033[33mz4h\\033[0m: not a readable file: \\033[31m%s\033[0m\n" "$ZDOTDIR"/.zshenv
"false"
fi')
if zstyle -a :z4h:ssh:$z4h_ssh_host retrieve-extra-files extra_files; then
local src dst
for src in $extra_files; do
eval "dst=$src"
z4h_ssh_retrieve_files[$src]=$dst
done
fi
zstyle -a :z4h:ssh:$z4h_ssh_host retrieve-history z4h_retrieve_history || z4h_retrieve_history=()
fi
local configure
if zstyle -s :z4h:ssh:$z4h_ssh_host configure configure; then
eval $configure || return
elif (( $+functions[z4h-ssh-configure] )); then
z4h-ssh-configure || return
fi
if (( ! $#z4h_ssh_command )); then
print -Pru2 -- '%F{3}z4h%f: empty %F{1}z4h_ssh_command%f'
return 1
fi
if [[ $mkdir_control_master == 1 &&
${(pj:\0:)z4h_ssh_command} == ${(pj:\0:)default_ssh_command} &&
! -d ~/.ssh/s && -n ~(#qNU) ]]; then
zf_mkdir -pm 700 ~/.ssh/s || return
{
>~/.ssh/s/README <<\END
This directory has been created by `z4h ssh`. It stores control sockets
for SSH connections. See ControlMaster, ControlPath and ControlPersist
in `man ssh_config`. This directory must not be writable by anyone other
than the current user.
END
} || return
if [[ -e ~/.ssh/control-master/README ]]; then
{
>>~/.ssh/s/README <<\END
You might also have ~/.ssh/control-master with the same file in it. This
is the old directory that was used by zsh4humans for the same purpose
before 2021-11-14. If you don't reference that directory explicitly from
~/.ssh/config, you can safely delete it.
END
} || return
fi
fi
if (( must_passthrough || !z4h_ssh_enable )); then
TERM=${term:-$TERM} "${z4h_ssh_command[@]}" "$@"
return
fi
if (( $#z4h_retrieve_history )); then
local local_hist_tmp=$Z4H/tmp/ssh-history.tmp.$sysparams[pid]
z4h_ssh_retrieve_files[\$HISTFILE]=$local_hist_tmp
zf_rm -f -- $local_hist_tmp || return
else
local local_hist_tmp=
fi
local file
for file in "${(@kv)z4h_ssh_send_files}"; do
if [[ -z $file ]]; then
print -Pru2 -- '%F{3}z4h%f: empty element(s) in %F{1}z4h_ssh_send_files%f'
return 1
fi
if [[ $file == */ ]]; then
print -Pru2 -- "%F{3}z4h%f: element(s) of %Bz4h_ssh_send_files%b end with %B/%b: %F{1}${file//\%/%%}%f"
return 1
fi
done
for file in "${(@kv)z4h_ssh_retrieve_files}"; do
if [[ -z $file ]]; then
print -Pru2 -- '%F{3}z4h%f: empty element(s) in %F{1}z4h_ssh_retrieve_files%f'
return 1
fi
if [[ $file == */ ]]; then
print -Pru2 -- "%F{3}z4h%f: element(s) of %Bz4h_ssh_retrieve_files%b end with %B/%b: %F{1}${file//\%/%%}%f"
return 1
fi
done
for file in "${(@)z4h_retrieve_history}"; do
if [[ -z $file ]]; then
print -Pru2 -- '%F{3}z4h%f: empty element(s) in %F{1}z4h_retrieve_history%f'
return 1
fi
if [[ $file == */ ]]; then
print -Pru2 -- "%F{3}z4h%f: element(s) of %Bz4h_retrieve_history%b end with %B/%b: %F{1}${file//\%/%%}%f"
return 1
fi
if [[ -e $file ]]; then
if [[ ! ( -f $file && -r $file && -w $file ) ]]; then
print -Pru2 -- "%F{3}z4h%f: element of %Bz4h_retrieve_history%b is not a readable & writable file: %F{1}${file//\%/%%}%f"
return 1
fi
elif [[ -d ${file:h} ]]; then
if [[ ! -w ${file:h} ]]; then
print -Pru2 -- "%F{3}z4h%f: element of %Bz4h_retrieve_history%b is in a non-writable directory: %F{1}${file//\%/%%}%f"
return 1
fi
else
zf_mkdir -p -- ${file:h} || return
fi
done
if (( $#z4h_ssh_retrieve_files && ! $+commands[base64] )); then
print -Pru2 -- '%F{3}z4h%f: command not found: %F{1}base64%f'
return 1
fi
local tmpdir
if (( $+commands[mktemp] )); then
tmpdir=$(command mktemp -d -- $Z4H/tmp/ssh.XXXXXXXXXX) || return
else
tmpdir=$Z4H/tmp/ssh.tmp.$sysparams[pid]
zf_rm -rf -- $tmpdir || return
zf_mkdir -- $tmpdir || return
fi
{
local -i i=0
local src dst
local indices=() send_to=()
for src dst in ${(kv)z4h_ssh_send_files}; do
(( ++i ))
send_to+=($dst)
[[ -e $src ]] || continue
local target=${src:A}
if [[ -z $target(#qN.) && -z $target(#qN/) ]]; then
print -Pru2 -- "%F{3}z4h%f: unsupported file type: %F{1}${src//\%/%%}%f"
return 1
fi
if [[ ${tmpdir:A} == $target(|/*) ]]; then
print -Pru2 -- "%F{3}z4h%f: cannot send file: %F{1}${src//\%/%%}%f"
return 1
fi
zf_ln -s -- $target $tmpdir/$i || return
indices+=($i)
done
local -a retrieve_from retrieve_to
local from to
for from to in ${(kv)z4h_ssh_retrieve_files}; do
retrieve_from+=($from)
retrieve_to+=($to)
done
local dump_marker=${(%):-%n}.$sysparams[pid].$EPOCHSECONDS.$RANDOM
local script
script=${"$(<$Z4H/zsh4humans/sc/ssh-bootstrap)"//$'\r'} || return
script=${script//'^TERM^'/${(q)term}}
script=${script//'^MIN_VERSION^'/${(q)z4h_min_version}}
script=${script//'^SSH_HOST^'/${(q)z4h_ssh_host}}
script=${script//'^SSH_CLIENT^'/${(q)z4h_ssh_client}}
script=${script//'^SSH_ARGS^'/${(q)${(j: :)@}}}
script=${script//'^PRELUDE^'/${(F)z4h_ssh_prelude}}
script=${script//'^SEND_TO^'/${(j: :)send_to}}
script=${script//'^SETUP^'/${(F)z4h_ssh_setup}}
script=${script//'^RUN^'/${(F)z4h_ssh_run}}
script=${script//'^TEARDOWN^'/${(F)z4h_ssh_teardown}}
if (( $#retrieve_from )); then
script=${script//'^EMPTY_RETRIEVE_FROM^'/"'false'"}
else
script=${script//'^EMPTY_RETRIEVE_FROM^'/"'true'"}
fi
script=${script//'^RETRIEVE_FROM^'/${(j: :)retrieve_from}}
script=${script//'^DUMP_MARKER^'/${(q)dump_marker}}
script=${script//'^CAN_SAVE_RESTORE_SCREEN^'/${_z4h_can_save_restore_screen}}
script=${script//'^DUMP_POS^'/${(r:8:: :)${#script}}}
print -r -- $script >$tmpdir/script || return
local tar_v tar_c_opt tar_x_opt
if tar_v=$(command tar --version 2>/dev/null) && [[ $tar_v == *'GNU tar'* ]]; then
tar_c_opt=(--owner=0 --group=0)
tar_x_opt=(--warning=no-unknown-keyword --warning=no-timestamp --no-same-owner)
fi
if (( $#indices )); then
command tar -C $tmpdir $tar_c_opt -czhf - -- $indices >>$tmpdir/script || return
fi
local args=("$@")
args[pos[1],pos[1]-1]=('-T')
local remote_script=.z4h-ssh.${(%):-%n}.$sysparams[pid].$EPOCHSECONDS.$RANDOM
# Tricky corner cases where this command must work:
#
# 1. The remote shell is csh (default on FreeBSD).
# 2. There is no /tmp on the remote host (e.g., Termux).
# 3. TMPDIR is not set.
# 4. TMPDIR has spaces in it.
#
# The next command (the one that invokes /bin/sh) must also work in these
# cases. It should also propagate the exit status of /bin/sh.
local cmd="test -w /tmp && cat >/tmp/$remote_script && echo 1 && exit"
cmd+=" || "
cmd+="test ! -e /tmp/$remote_script && cat >~/$remote_script && echo 2"
local loc
loc=$("${z4h_ssh_command[@]}" "${args[@]}" $cmd <$tmpdir/script) || return
} always {
zf_rm -rf -- $tmpdir
}
case ${loc//[[:space:]]} in
1) remote_script="/tmp/$remote_script";;
2) remote_script="~/$remote_script";;
*)
print -Pru2 -- "%F{3}z4h%f: failed to upload bootstrap script"
return 1
;;
esac
args[pos[1]]='-t'
local stty
if [[ -v commands[stty] && -v _z4h_tty_fd ]]; then
stty=$(command stty -g <&$_z4h_tty_fd 2>/dev/null) || stty=
fi
{ ( # subshell to avoid TTOU
local -i bypass=0
local -i pid=$sysparams[pid]
{
setopt no_multi_os
"${z4h_ssh_command[@]}" "${args[@]}" "sh $remote_script" 2>&1 1>&3 |
LC_ALL=C command grep -vxE '(Shared c|C)onnection to .* closed\.(.)?' >&2
return $pipestatus[1]
} 3>&1 | {
if (( $+commands[mktemp] )); then
tmpdir=$(command mktemp -d -- $Z4H/tmp/ssh.XXXXXXXXXX) || return
else
tmpdir=$Z4H/tmp/ssh.tmp.$sysparams[pid]
zf_rm -rf -- $tmpdir || return
zf_mkdir -- $tmpdir || return
fi
unsetopt multibyte
local LC_ALL=C
unset _z4h_saved_screen
{
local buf=
local mark=$'\001z4h.'$dump_marker
while true; do
[[ -n $buf ]] || sysread 'buf[$#buf+1]' || return $(( $? != 5 ))
if [[ $buf != *$mark[1]* ]]; then
print -rn -- $buf
buf=
continue
fi
while true; do
print -rn -- ${buf%%$mark[1]*}
buf=$mark[1]${buf#*$mark[1]}
local -i prefix=$(($#buf < $#mark ? $#buf : $#mark))
(( prefix )) || continue
[[ ${buf:0:$prefix} == ${mark:0:$prefix} ]] && break
print -rn -- $buf[1]
buf[1]=""
continue 2
done
while (( $#buf < $#mark )) && [[ $mark == $buf* ]]; do
# What should we do if the output ends with a proper prefix of mark?
# Print it or not? Return an error or not? We choose to not print and return
# success iff we've reached eof.
sysread -s $(($#mark - $#buf)) 'buf[$#buf+1]' && continue
return $(( $? != 5 ))
done
if [[ $buf != $mark* ]]; then
print -rn -- $buf[1]
buf[1]=""
continue
fi
buf[1,$#mark]=""
while (( $#buf < 16 )); do
sysread -s $((16 - $#buf)) 'buf[$#buf+1]' && continue
return $(( $? != 5 ))
done
{
case ${buf[1,16]%% #} in
bypass)
bypass=1
break
;;
save-screen)
(( _z4h_can_save_restore_screen )) || return
local _z4h_saved_screen=
-z4h-save-screen || return
_z4h_saved_screen+=x
continue
;;
restore-screen)
[[ -n $_z4h_saved_screen ]] || return
_z4h_saved_screen[-1]=
-z4h-restore-screen || return
unset _z4h_saved_screen
continue
;;
<->)
local -i len=buf[1,16]
;;
*)
return 1
;;
esac
} always {
buf=${buf:16}
}
(( len )) || continue
if [[ -d $tmpdir ]]; then
local dump_file=$tmpdir/dump.base64
else
local dump_file=/dev/null
fi
{
local -i n=$((len < $#buf ? len : $#buf))
print -rn -- $buf[1,n] || return
(( len -= n ))
buf[1,n]=""
while (( len )); do
sysread -s $((len > 65636 ? 65636 : len)) -o 1 -c n || return $(( $? != 5 ))
(( len -= n, 1 ))
done
} >$dump_file || return
if [[ $dump_file != /dev/null ]]; then
if base64 -d <<<'Cg==' &>/dev/null; then
local base64_opt=-d
else
local base64_opt=-D
fi
<$tmpdir/dump.base64 command base64 $base64_opt |
command tar -C $tmpdir $tar_x_opt -xzf - || return
local -i i
for i in {1..$#retrieve_to}; do
local src=$tmpdir/$i
local dst=$retrieve_to[i]
[[ -e $src ]] || continue
if [[ -e $dst ]]; then
zf_rm -rf -- $dst || return
fi
if ! command mv -f -- $src $dst 2>/dev/null; then
command cp -rf -- $src $dst || return
fi
done
if [[ -s $local_hist_tmp ]]; then
local local_hist
for local_hist in $z4h_retrieve_history; do
local TMPPREFIX=$local_hist
() {
() { fc -pa -- $1 $HISTSIZE $SAVEHIST } $1 && zf_mv -f -- $1 $local_hist
} =(command cat -- $local_hist(N) $local_hist_tmp) || return
done
fi
fi
done
} always {
local -i err=$?
zf_rm -rf -- $tmpdir $local_hist_tmp
if (( err )); then
kill -- -$pid 2>/dev/null
fi
}
}
if (( bypass )); then
setopt no_multi_os
{
TERM=${term:-$TERM} "${z4h_ssh_command[@]}" "${args[@]}" 2>&1 1>&3 |
LC_ALL=C command grep -vxE '(Shared c|C)onnection to .* closed\.(.)?' >&2
return $pipestatus[1]
} 3>&1
fi
) } always {
[[ -n $stty ]] && command stty $stty <&$_z4h_tty_fd 2>/dev/null
}

7
fn/-z4h-cmd-sudo Normal file
View file

@ -0,0 +1,7 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local term
zstyle -s :z4h:sudo term term || term=${TERM:/tmux-256color/screen-256color}
TERM=${term:-$TERM} command sudo "$@"

32
fn/-z4h-cmd-tty-wait Normal file
View file

@ -0,0 +1,32 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local -a timeout pattern
zparseopts -D -F -- \
{t,-timeout-seconds}:=timeout \
{p,-lines-columns-pattern}:=pattern \
|| return '_z4h_err()'
if (( $#pattern == 2 )); then
pattern=$pattern[2]
else
return '_z4h_err()'
fi
if (( $#timeout == 2 )); then
[[ $timeout[2] == <->(|.<->) ]] || return '_z4h_err()'
typeset -F timeout=$timeout[2]
else
return '_z4h_err()'
fi
[[ $TERM == (screen|tmux)* ]] && return 0
[[ -v commands[true] ]] || return 0
local -F deadline='EPOCHREALTIME + timeout'
while [[ "$LINES $COLUMNS" != $~pattern ]] && (( EPOCHREALTIME < deadline )); do
command true
done
return 0

82
fn/-z4h-cmd-update Normal file
View file

@ -0,0 +1,82 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
-z4h-check-core-params || return
if (( ARGC )); then
print -Pru2 -- '%F{3}z4h%f: unexpected %F{1}update%f argument'
return '_z4h_err()'
fi
if (( _z4h_dangerous_root )); then
print -Pru2 -- "%F{3}z4h%f: refusing to %Bupdate%b as %F{1}root%f"
return 1
fi
local old=$Z4H.old.$$
local new=$Z4H.new.$$
{
zf_rm -rf -- $old $new || return
zf_mkdir -p -- $new || return
print -n >$new/.updating || return
Z4H_UPDATING=$Z4H Z4H=$new </dev/null >/dev/null $_z4h_exe -ic '
(( $? )) && "exit" "1"
"builtin" "emulate" "zsh" "-o" "no_aliases"
[[ $Z4H == '${(q)new}' ]] || exit 0
print -n >$Z4H/tmp/update-successful' || return
if [[ ! -e $new/tmp/update-successful ]]; then
local home=~
local zdotdir=${${${(q)ZDOTDIR}/#${(q)home}/'~'}//\%/%%}
local z4h=${${${(q)Z4H}/#${(q)home}/'~'}//\%/%%}
print -Pru2 -- '%F{3}z4h%f: %B$Z4H%b %F{1}does not propagate%f through %U.zshrc%u'
print -Pru2 -- ''
print -Pru2 -- 'Change %U'$zdotdir'/.zshrc%u to keep %BZ4H%b intact if already set.'
print -Pru2 -- ''
print -Pru2 -- 'For example:'
print -Pru2 -- ''
print -Pru2 -- ' %F{2}:%f %F{3}"${Z4H:=${XDG_CACHE_HOME:-$HOME/.cache}/zsh4humans}"%f'
print -Pru2 -- ''
print -Pru2 -- 'Note: The leading colon (%F{2}:%f) is necessary.'
return 1
fi
zf_rm -- $new/tmp/update-successful || return
zf_rm -- $new/.updating || return
-z4h-mv $Z4H $old 2>/dev/null || zf_rm -rf -- $Z4H || return
if [[ -e $Z4H ]]; then
local home=~
local z4h=${${${(q)Z4H}/#${(q)home}/'~'}//\%/%%}
print -Pru2 -- '%F{3}z4h%f: %F{1}cannot delete %U'$z4h'%u%f'
print -Pru2 -- ''
print -Pru2 -- 'This might help:'
print -Pru2 -- ''
print -Pru2 -- ' %F{2}%Ucommand%u %Usudo%u rm%f -rf -- %U'$z4h'%u && %U%F{2}exec%u zsh%f'
print -Pru2 -- ''
print -Pru2 -- '%F{3}z4h%f: attempting to recover'
if [[ ! -e $Z4H/stickycache ]]; then
command cp -r -- $new/stickycache $Z4H/stickycache || true
fi
if [[ -o zle ]]; then
exec -- $_z4h_exe -i || return
else
exec -- $_z4h_exe -i --no-zle || return
fi
fi
-z4h-mv $new $Z4H || return
} always {
if (( $? )); then
-z4h-error-command update
fi
zf_rm -rf -- $old $new || return
}
print -Pru2 -- "%F{3}z4h%f: %Bupdate successful%b"
print -Pru2 -- "%F{3}z4h%f: restarting %F{2}zsh%f"
if [[ -o zle ]]; then
exec -- $_z4h_exe -i || return
else
exec -- $_z4h_exe -i --no-zle || return
fi

36
fn/-z4h-command-not-found Normal file
View file

@ -0,0 +1,36 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local fd fname
if zstyle -s :z4h:command-not-found to-file fname &&
[[ -w $fname || ! -e $fname && -w ${fname:h} ]]; then
fd=3
else
fd=2
fname=/dev/null
fi
{
if (( $#functrace >= 2 )); then
print -r -- "$functrace[1]: command not found: $1"
return 127
fi
local msg
if [[ -x /usr/lib/command-not-found ]]; then
msg="$(/usr/lib/command-not-found --no-failure-msg -- $1 2>&1)"
if [[ -n $msg ]]; then
print -r -- ${msg#$'\n'}
return 127
fi
fi
if [[ -v commands[brew] &&
-n $HOMEBREW_REPOSITORY &&
-e $HOMEBREW_REPOSITORY/Library/Taps/homebrew/homebrew-command-not-found/cmd/which-formula.rb ]]; then
if msg="$(command brew which-formula --explain $1 2>/dev/null)" && [[ -n $msg ]]; then
print -r -- $msg
return 127
fi
fi
print -r -- "zsh: command not found: $1"
return 127
} 3>$fname >&$fd

148
fn/-z4h-comp-files Normal file
View file

@ -0,0 +1,148 @@
#!/usr/bin/env zsh
() {
eval "$_z4h_opt"
local -i dot_glob list_types
[[ $1 == on ]] && dot_glob=1
[[ $2 == on ]] && list_types=1
if (( _z4h_only_dirs )); then
local dirs=($_z4h_path_prefix${^${(Q)_z4h_words}}/*(D-/Y1N:h:t))
else
local dirs=($_z4h_path_prefix${^${(Q)_z4h_words}}/*(DY1N:h:t))
fi
-z4h-set-list-colors "$_z4h_curcontext" "$list_types"
local -i list_colors=$((!$?))
autoload +X -Uz -- -z4h-present-files -z4h-cursor-show -z4h-find -z4h-fzf
local -i pct=60
(( _z4h_can_save_restore_screen )) && pct=100
local -i recurse
() {
emulate -L zsh
# Set curcontext and dot_glob in case the value of recurse depends on them (via `zstyle -e`).
# Ideally we should run this with user options.
(( dot_glob )) && setopt dot_glob
local curcontext=$_z4h_curcontext
zstyle -T :z4h:${WIDGET#z4h-} recurse-dirs && recurse=1
}
local -i height=$(( ! (recurse && $#dirs) && 100 * ($#_z4h_words + 4) < pct * LINES ? $#_z4h_words + 4 : pct * LINES / 100 ))
(( height >= 6 )) || (( height = 6 ))
(( height <= LINES - 1 )) || (( height = LINES - 1 ))
local opts=(
--query=${_z4h_word_prefix:+"^$_z4h_word_prefix"}
--color=hl:201,hl+:201
--with-nth=2
--delimiter='\000'
--ansi
--exact
--no-mouse
--tiebreak=length,begin,index
--multi
--cycle
--border=horizontal
)
() {
emulate -L zsh
# Set dot_glob in case the value of find-flags depends on it (via `zstyle -e`).
# Ideally we should run this with user options.
(( dot_glob )) && setopt dot_glob
local -a bin
zstyle -a :z4h:${WIDGET#z4h-} find-command bin
if (( ! $#bin )) && (( $+commands[bfs] )); then
opts+=(--no-sort)
fi
}
local cursor_y cursor_x
-z4h-get-cursor-pos || return
if (( _z4h_can_save_restore_screen )); then
opts+=(--no-clear)
if { (( height <= cursor_y - 1 )) && zstyle -T :z4h: prompt-at-bottom } ||
(( cursor_y - 1 > LINES - cursor_y && cursor_y - 1 > 6 )) &&
{ (( height > LINES - cursor_y )) || zstyle -T :z4h: prompt-at-bottom }; then
(( height <= cursor_y - 1 )) || (( height = cursor_y - 1 ))
local move=$'\e[0m\e['$((cursor_y-height))';1H'
opts+=(--layout=default)
elif (( LINES - cursor_y > 6 )); then
(( height <= LINES - cursor_y )) || (( height = LINES - cursor_y ))
local move=$'\e[0m\n\r'
opts+=(--layout=reverse)
else
local -i extra=$((height - LINES + cursor_y))
print -rnu $_z4h_tty_fd -- ${(pl:$height::\n:)} || return
(( cursor_y += LINES - cursor_y - height ))
local move=$'\e[0m\e['$((cursor_y+1))';1H'
opts+=(--layout=reverse)
fi
local _z4h_saved_screen
-z4h-save-screen || return
else
print -u $_z4h_tty_fd || return
local move=
opts+=(--layout=reverse)
fi
opts+=(--height=$height)
{
local choice
choice="$(
unsetopt pipe_fail
exec 2>/dev/null
[[ -n $_z4h_path_prefix ]] && builtin cd -q -- $_z4h_path_prefix
{
print -r -- $sysparams[pid]
print -lr -- ${(Q)_z4h_words}
if (( recurse )); then
# Set curcontext to support this:
#
# zstyle -e :z4h:fzf-complete find-flags my-find-flags
#
# function my-find-flags() {
# if [[ $curcontext == :complete:cd:* ]]; then
# reply=(...)
# fi
# }
local curcontext=$_z4h_curcontext
-z4h-find $dot_glob $_z4h_only_dirs $dirs | command sed -n '/\/.*\// s/^..//p'
fi
} | {
local -a pids
IFS=' ' builtin read -rA pids || exit
print -r -- $pids $sysparams[pid] || exit
-z4h-present-files $list_colors $list_types 0
} | {
local -a pids
IFS=' ' builtin read -rA pids || pids=()
print -rnu $_z4h_tty_fd -- $move
-z4h-cursor-show
2>&$_z4h_tty_fd -z4h-fzf $opts
(( $#pids )) && builtin kill -- $pids
}
)"
} always {
-z4h-cursor-hide
if (( _z4h_can_save_restore_screen )); then
-z4h-restore-screen
print -rn -- $'\e[0m\e['$cursor_y';'$cursor_x'H'
else
builtin echoti cuu 1
(( cursor_x > 1 )) && builtin echoti cuf $((cursor_x-1))
fi
}
[[ -n $choice ]] || return
choice=("${(@f)choice}")
typeset -g _z4h_reply=(0 ${${choice:1}%$'\0'*})
[[ -z $choice[1] ]] || _z4h_reply[1]=1
} "${options[dot_glob]}" "${options[list_types]}"

44
fn/-z4h-comp-insert-all Normal file
View file

@ -0,0 +1,44 @@
#!/usr/bin/env zsh
emulate -L zsh
if (( $#_z4h_scaffolds == 1 )); then
local -a s=("${(@ps:\1:)_z4h_scaffolds}")
local PREFIX=$s[14] SUFFIX=$s[15]
$_z4h_orig_compadd \
${s[2]:+-P$s[2]} \
${s[3]:+-S$s[3]} \
${s[4]:+-p$s[4]} \
${s[5]:+-s$s[5]} \
${s[6]:+-i$s[6]} \
${s[7]:+-I$s[7]} \
$s[8] \
${s[9]:+-r$s[9]} \
${s[10]:+-R$s[10]} \
$s[11] \
$s[12] \
${s[13]:+-W$s[13]} \
-V- -2 -o nosort -J- -Q -U -a _z4h_words
else
local word scaffold
for word scaffold in "${(@)_z4h_words:^_z4h_scaffolds}"; do
local -a s=("${(@ps:\1:)scaffold}")
local PREFIX=$s[14] SUFFIX=$s[15]
$_z4h_orig_compadd \
${s[2]:+-P$s[2]} \
${s[3]:+-S$s[3]} \
${s[4]:+-p$s[4]} \
${s[5]:+-s$s[5]} \
${s[6]:+-i$s[6]} \
${s[7]:+-I$s[7]} \
$s[8] \
${s[9]:+-r$s[9]} \
${s[10]:+-R$s[10]} \
$s[11] \
$s[12] \
${s[13]:+-W$s[13]} \
-V- -2 -o nosort -J- -Q -U - $word
done
fi
compstate[insert]=all

125
fn/-z4h-comp-words Normal file
View file

@ -0,0 +1,125 @@
#!/usr/bin/env zsh
() {
eval "$_z4h_opt"
local -i list_types
[[ $1 == on ]] && list_types=1
typeset -ga _z4h_naturals
if (( $#_z4h_naturals < $#_z4h_words )); then
_z4h_naturals+=({$(($#_z4h_naturals+1))..$#_z4h_words})
fi
local -A seen
local -a indices
local word idx
for word idx in "${(@)_z4h_words:^_z4h_naturals}"; do
if (( ! ${+seen[$word]} )); then
seen[$word]=1
indices+=($idx)
fi
done
-z4h-set-list-colors "$_z4h_curcontext" "$list_types"
local -i list_colors=$((!$?))
zstyle -t :completion:${_z4h_curcontext}:default sort
local -i sort=$((!$?))
autoload +X -Uz -- -z4h-cursor-show -z4h-fzf
local -i pct=60
(( _z4h_can_save_restore_screen )) && pct=100
local -i height=$(( 100 * ($#indices + 4) < pct * LINES ? $#indices + 4 : pct * LINES / 100 ))
(( height >= 6 )) || (( height = 6 ))
(( height <= LINES - 1 )) || (( height = LINES - 1 ))
local opts=(
--query=${_z4h_word_prefix:+"^$_z4h_word_prefix"}
--color=hl:201,hl+:201
--with-nth=2
--delimiter='\000'
--ansi
--exact
--no-mouse
--tiebreak=length,begin,index
--multi
--cycle
--border=horizontal
)
local cursor_y cursor_x
-z4h-get-cursor-pos || return
if (( _z4h_can_save_restore_screen )); then
opts+=(--no-clear)
if { (( height <= cursor_y - 1 )) && zstyle -T :z4h: prompt-at-bottom } ||
(( cursor_y - 1 > LINES - cursor_y && cursor_y - 1 > 6 )) &&
{ (( height > LINES - cursor_y )) || zstyle -T :z4h: prompt-at-bottom }; then
(( height <= cursor_y - 1 )) || (( height = cursor_y - 1 ))
local move=$'\e[0m\e['$((cursor_y-height))';1H'
opts+=(--layout=default)
elif (( LINES - cursor_y > 6 )); then
(( height <= LINES - cursor_y )) || (( height = LINES - cursor_y ))
local move=$'\e[0m\n\r'
opts+=(--layout=reverse)
else
local -i extra=$((height - LINES + cursor_y))
print -rnu $_z4h_tty_fd -- ${(pl:$height::\n:)} || return
(( cursor_y += LINES - cursor_y - height ))
local move=$'\e[0m\e['$((cursor_y+1))';1H'
opts+=(--layout=reverse)
fi
local _z4h_saved_screen
-z4h-save-screen || return
else
print >&$_z4h_tty_fd || return
local move=
opts+=(--layout=reverse)
fi
opts+=(--height=$height)
{
local choice
choice="$(
unsetopt pipe_fail
exec 2>/dev/null
{
# TODO: colorize files.
if (( sort )); then
local rows=()
for idx in $indices; do
rows+=($_z4h_descrs[idx]$'\0'$idx)
done
printf '%2$s\0%1$s\n' "${(@0)${(@o)rows}}"
else
for idx in $indices; do
printf '%s\0%s\n' $idx "$_z4h_descrs[idx]"
done
fi
} | {
print -rnu $_z4h_tty_fd -- $move
-z4h-cursor-show
2>&$_z4h_tty_fd -z4h-fzf $opts
}
)"
} always {
-z4h-cursor-hide
if (( _z4h_can_save_restore_screen )); then
-z4h-restore-screen
print -rn -- $'\e[0m\e['$cursor_y';'$cursor_x'H'
else
builtin echoti cuu 1
(( cursor_x > 1 )) && builtin echoti cuf $((cursor_x-1))
fi
}
[[ -n $choice ]] || return
choice=("${(@f)choice}")
typeset -g _z4h_reply=(0 ${${choice:1}%$'\0'*})
[[ -z $choice[1] ]] || _z4h_reply[1]=1
} "${options[list_types]}"

41
fn/-z4h-compile Normal file
View file

@ -0,0 +1,41 @@
#!/usr/bin/env zsh
# Runs with user options.
#
# Precondition: [[ -e $1 ]].
local -a stat
# Checking [[ -e "$1".zwc ]] is faster than redirecting stderr of zstat to /dev/null.
[[ -e "$1".zwc ]] && zstat +mtime -A stat -- "$1" "$1".zwc && {
# Negative indices to handle ksh_arrays.
(( stat[-1] == stat[-2] + 1 )) && return # common case
stat[-1]=()
} || {
zstat +mtime -A stat -- "$1" || return
}
[[ -w "${1:h}" ]] || return
local t
builtin strftime -s t '%Y%m%d%H%M.%S' $((stat + 1))
local tmp="$1".tmp."${sysparams[pid]}".zwc
{
# This zf_rm is to work around bugs in NTFS and/or WSL. The following code fails there:
#
# touch a b
# chmod -w b
# zf_rm -f a b
#
# The last command produces this error:
#
# zf_mv: a: permission denied
(( !_z4h_dangerous_root )) &&
zcompile -R -- "$tmp" "$1" &&
command touch -ct $t -- "$tmp" &&
zf_rm -f -- "$1".zwc &&
zf_mv -f -- "$tmp" "$1".zwc
} always {
(( $? )) && zf_rm -f -- "$tmp" "$1".zwc 2>/dev/null
}

107
fn/-z4h-compinit Normal file
View file

@ -0,0 +1,107 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
if [[ -v _z4h_compinit_fd ]]; then
zle -F $_z4h_compinit_fd
exec {_z4h_compinit_fd}>&-
unset _z4h_compinit_fd
fi
unfunction compdef
local -aU editors=(
vi vim nvim emacs nano gedit code kak kate mcedit joe $EDITOR $VISUAL
bat cat less more $PAGER)
zstyle ':completion:*:*:('${(j:|:)editors}'):*:*' ignored-patterns '*.zwc'
zstyle ':completion:*' list-colors "${(@s.:.)LS_COLORS}"
(( _z4h_use[zsh-completions] )) &&
[[ -d $Z4H/zsh-completions/src ]] &&
fpath+=($Z4H/zsh-completions/src)
(( _z4h_use[systemd] )) &&
[[ -e $Z4H/systemd/shell-completion/zsh/_systemctl && -z ${^fpath}/_systemctl(#qN) ]] &&
fpath+=($Z4H/systemd/shell-completion/zsh)
if (( !_z4h_dangerous_root )) && zstyle -t ':completion::complete:' use-cache; then
local cache
zstyle -s ':completion::complete:' cache-path cache
: ${cache:=${ZDOTDIR:-~}/.zcompcache}
if [[ ! -e $cache ]]; then
zf_mkdir -m 0700 -p -- $cache
fi
fi
local dump
zstyle -s ':z4h:compinit' dump-path dump
: ${dump:=$Z4H/cache/zcompdump-$EUID-$ZSH_VERSION}
local -a stat files=(${^fpath}/^([^_]*|*~|*.zwc)(-.N))
(( ! $#files )) || zstat -A stat +mtime -- $files
local real_sig=($ZSH_VERSION $ZSH_PATCHLEVEL $files $stat)
real_sig='# '${(V)${(pj:\0:)real_sig}}$'\n'
local sig
if [[ -r $dump ]] &&
sysread -s $#real_sig sig <$dump &&
[[ $sig == $real_sig && -r $dump.zwc ]] &&
zstat -A stat +mtime -- $dump $dump.zwc &&
(( stat[2] == stat[1] + 1 )); then
-z4h-compinit-impl -C -d $dump
else
local tmp=$Z4H/tmp/zcompdump.$sysparams[pid]
zf_rm -f -- $dump $dump.zwc $tmp $tmp.2
-z4h-compinit-impl -C -d $tmp
{ print -rn -- $real_sig; <$tmp } >$tmp.2
zf_rm -f -- $tmp
zf_mv -- $tmp.2 $dump
-z4h-compile $dump
fi
# Replay compdef calls.
local args
for args in $_z4h_compdef; do
compdef "${(@0)args}"
done
unset _z4h_compdef
local cmd
for cmd in helm kitty kubectl oc; do
# Homebrew ships broken completions for kubectl, so we use our own even
# if _comps[kubectl] is set.
#
# TODO: what about the rest of them in the list? Move them below?
[[ -v commands[$cmd] ]] && compdef -- -z4h-complete-$cmd $cmd
done
for cmd in cargo bw gh rustup; do
if [[ -v commands[$cmd] && ! -v _comps[$cmd] ]]; then
compdef -- -z4h-complete-$cmd $cmd
fi
done
for cmd in terraform vault packer; do
if [[ -v commands[$cmd] && ! -v _comps[$cmd] ]]; then
complete -o nospace -C =$cmd $cmd
fi
done
if [[ -v commands[aws_completer] && ! -v _comps[aws] ]]; then
complete -C =aws_completer aws
fi
if [[ -v commands[gcloud] && ! -v _comps[gcloud] ]]; then
local dirs=(
${HOMEBREW_PREFIX:+$HOMEBREW_PREFIX/share/google-cloud-sdk}
~/google-cloud-sdk
/usr/share/google-cloud-sdk
/snap/google-cloud-sdk/current
/snap/google-cloud-cli/current
/usr/lib/google-cloud-sdk
/usr/lib64/google-cloud-sdk
/opt/google-cloud-sdk
/opt/local/libexec/google-cloud-sdk
)
source -- $^dirs/completion.zsh.inc(-.Ne'<[[ -r ${REPLY:a} ]]>') /dev/null
fi

29
fn/-z4h-complete-bw Normal file
View file

@ -0,0 +1,29 @@
#!/usr/bin/env zsh
local bw="${commands[bw]-}"
local comp="$Z4H"/cache/bw-completion-$EUID.zsh
() {
[[ -n "$bw" ]] || return
[[ "$comp" -nt "$bw" ]] || {
local tmp="$comp".tmp."${sysparams[pid]}"
"$bw" completion --shell zsh >"$tmp" || return
zf_mv -f -- "$tmp" "$comp" || return
-z4h-compile "$comp" || return
}
() {
emulate -L zsh
local -h funcstack=(_bw)
builtin source -- "$comp"
} || true
[[ -v functions[_bw] ]] || return
_comps[bw]=_bw
_bw "$@"
} "$@" || {
builtin unset '_comps[bw]'
_default "$@"
return
}

13
fn/-z4h-complete-cargo Normal file
View file

@ -0,0 +1,13 @@
#!/usr/bin/env zsh
(( $+commands[rustup] && $+commands[rustc] )) || {
unset '_comps[cargo]'
_default "$@"
return
}
{
builtin source <(rustup completions zsh cargo)
} always {
(( $+functions[_cargo] )) && _comps[cargo]=_cargo || unset '_comps[cargo]'
}

28
fn/-z4h-complete-gh Normal file
View file

@ -0,0 +1,28 @@
#!/usr/bin/env zsh
local gh="${commands[gh]-}"
local comp="$Z4H"/cache/gh-completion-$EUID.zsh
() {
[[ -n "$gh" ]] || return
[[ "$comp" -nt "$gh" ]] || {
local tmp="$comp".tmp."${sysparams[pid]}"
"$gh" completion -s zsh >"$tmp" || return
zf_mv -f -- "$tmp" "$comp" || return
-z4h-compile "$comp" || return
}
() {
emulate -L zsh
local -h funcstack=(_gh)
builtin source -- "$comp"
} || true
[[ -v functions[_gh] ]] || return
_comps[gh]=_gh
} || {
builtin unset '_comps[gh]'
_default "$@"
return
}

32
fn/-z4h-complete-helm Normal file
View file

@ -0,0 +1,32 @@
#!/usr/bin/env zsh
local helm="${commands[helm]-}"
local orig_cmd="${_comps[helm]-}"
local comp="$Z4H"/cache/helm-completion-$EUID.zsh
local cmd
() {
[[ -n "$helm" ]] || return
[[ "$comp" -nt "$helm" ]] || {
local tmp="$comp".tmp."${sysparams[pid]}"
"$helm" completion zsh >"$tmp" || return
zf_mv -f -- "$tmp" "$comp" || return
-z4h-compile "$comp" || return
}
() {
emulate -L zsh
builtin source -- "$comp"
unset LWORD RWORD
} || true
cmd="${_comps[helm]-}"
[[ "$cmd" != "$orig_cmd" ]] || return
} || {
builtin unset '_comps[helm]'
_default "$@"
return
}
builtin eval "$cmd"

32
fn/-z4h-complete-kitty Normal file
View file

@ -0,0 +1,32 @@
#!/usr/bin/env zsh
local kitty="${commands[kitty]-}"
local orig_cmd="${_comps[kitty]-}"
local comp="$Z4H"/cache/kitty-completion-$EUID.zsh
local src="${kitty:h}"/../lib/kitty/kitty/complete.py
local cmd
() {
[[ -n "$kitty" ]] || return
[[ "$comp" -nt "$kitty" && (! -e "$src" || "$comp" -nt "$src" ) ]] || {
local tmp="$comp".tmp."${sysparams[pid]}"
"$kitty" + complete setup zsh >"$tmp" || return
zf_mv -f -- "$tmp" "$comp" || return
-z4h-compile "$comp" || return
}
() {
emulate -L zsh
builtin source -- "$comp"
} || true
cmd="${_comps[kitty]-}"
[[ "$cmd" != "$orig_cmd" ]] || return
} || {
builtin unset '_comps[kitty]'
_default "$@"
return
}
builtin eval "$cmd"

41
fn/-z4h-complete-kubectl Normal file
View file

@ -0,0 +1,41 @@
#!/usr/bin/env zsh
local kubectl="${commands[kubectl]-}"
local orig_cmd="${_comps[kubectl]-}"
local comp="$Z4H"/cache/kubectl-completion-$EUID.zsh
local cmd
() {
[[ -n "$kubectl" ]] || return
[[ "$comp" -nt "$kubectl" ]] || {
local tmp="$comp".tmp."${sysparams[pid]}"
"$kubectl" completion zsh >"$tmp" || return
zf_mv -f -- "$tmp" "$comp" || return
-z4h-compile "$comp" || return
}
() {
emulate -L zsh
if (( ${+functions[_bash_comp]} )); then
builtin source -- "$comp"
else
{
function _bash_comp() {}
builtin source -- "$comp"
} always {
unfunction _bash_comp
}
fi
unset LWORD RWORD
} || true
cmd="${_comps[kubectl]-}"
[[ "$cmd" != "$orig_cmd" ]] || return
} || {
builtin unset '_comps[kubectl]'
_default "$@"
return
}
builtin eval "$cmd"

41
fn/-z4h-complete-oc Normal file
View file

@ -0,0 +1,41 @@
#!/usr/bin/env zsh
local oc="${commands[oc]-}"
local orig_cmd="${_comps[oc]-}"
local comp="$Z4H"/cache/oc-completion-$EUID.zsh
local cmd
() {
[[ -n "$oc" ]] || return
[[ "$comp" -nt "$oc" ]] || {
local tmp="$comp".tmp."${sysparams[pid]}"
"$oc" completion zsh >"$tmp" || return
zf_mv -f -- "$tmp" "$comp" || return
-z4h-compile "$comp" || return
}
() {
emulate -L zsh
if (( ${+functions[_bash_comp]} )); then
builtin source -- "$comp"
else
{
function _bash_comp() {}
builtin source -- "$comp"
} always {
unfunction _bash_comp
}
fi
unset LWORD RWORD
} || true
cmd="${_comps[oc]-}"
[[ "$cmd" != "$orig_cmd" ]] || return
} || {
builtin unset '_comps[oc]'
_default "$@"
return
}
builtin eval "$cmd"

13
fn/-z4h-complete-rustup Normal file
View file

@ -0,0 +1,13 @@
#!/usr/bin/env zsh
(( $+commands[rustup] )) || {
unset '_comps[rustup]'
_default "$@"
return
}
{
builtin source <(rustup completions zsh rustup)
} always {
(( $+functions[_rustup] )) && _comps[rustup]=_rustup || unset '_comps[rustup]'
}

81
fn/-z4h-direnv-hook Normal file
View file

@ -0,0 +1,81 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
unset _z4h_direnv_err
if (( ARGC )); then
local direnv=$1
else
local direnv=${commands[direnv]-}
if [[ -z $direnv ]]; then
unset _z4h_direnv_sig
return 1
fi
fi
# { print -n '\x1f\x8b\x08\x00\x00\x00\x00\x00'; base64 -d <<<${${DIRENV_WATCHES//-/+}//_//} } | zcat 2>/dev/null
# zcat
# gzcat
# uncompress -c
# gunzip -c
# gzip -cd
local sig
local envrc=(./(../)#.envrc(NY1:a))
if (( $#envrc )); then
local -a deps=(
${XDG_DATA_HOME:-~/.local/share}/direnv/allow
${XDG_CONFIG_HOME:-~/.config}/{direnv.toml,config.toml})
local -a stat
local files=($^deps(N))
local non_files=(${deps:|files})
if zstat -A stat +mtime -- $envrc $files 2>/dev/null; then
local sig=$envrc$'\0'${(pj:\0:)stat}
else
local sig=stat-error
fi
elif [[ ! -v DIRENV_WATCHES ]]; then
typeset -g _z4h_direnv_sig=none
return
else
local sig=none
fi
[[ $sig == ${_z4h_direnv_sig-} ]] && return
unset _z4h_direnv_sig
local data
data=$(
local out
out=$($direnv export zsh) 2>&1
builtin printf '%s%18d%d' "$out" $#out $(( ! $? ))
) || return
local -i success=$data[-1]
local -i out_len=$data[-19,-2]
local out=$data[-out_len-19,-20]
local err=${data[1,-out_len-20]%%$'\n'#}
if [[ -n $err ]]; then
local ctx=:z4h:direnv:
(( success )) && ctx+='success' || ctx+='error'
if zstyle -T $ctx notify; then
if builtin zle; then
typeset -g _p9k__raw_msg=${err//\%/%%}$'\n'
else
print -ru2 -- $err
fi
fi
fi
emulate -L zsh
if [[ ! -v __p9k_trapped ]]; then
local -i __p9k_trapped
builtin trap : INT
builtin trap "builtin trap ${(q)__p9k_trapint:--} INT" EXIT
fi
builtin eval -- $out
typeset -g _z4h_direnv_sig=$sig

32
fn/-z4h-direnv-init Normal file
View file

@ -0,0 +1,32 @@
#!/usr/bin/env zsh
local direnv cache=$Z4H/cache/direnv
if [[ -e $cache ]]; then
builtin source -- $cache || return
[[ -n $direnv ]] || return '_z4h_err()'
fi
if (( $1 )); then
local real_direnv=${commands[direnv]-}
if [[ $direnv != $real_direnv ]]; then
if [[ -n $real_direnv ]]; then
direnv=$real_direnv
if (( ! _z4h_dangerous_root )); then
local tmp=$cache.tmp.$$
typeset -p direnv >$tmp || return
zf_mv -f -- $tmp $cache || return
fi
else
[[ ! -e $cache ]] || builtin : >$cache || return
return
fi
elif [[ -z $direnv ]]; then
return
fi
elif [[ ! -x $direnv ]]; then
return
fi
-z4h-direnv-hook $direnv || return
typeset -gi _z4h_direnv_initialized=1

View file

@ -0,0 +1,47 @@
#!/usr/bin/env zsh
function iterm2_set_user_var() {
(( ${+commands[base64]} )) || return
local x
x="$(printf '%s' "$2" | command base64 2>/dev/null)" || return
-z4h-tmux-bypass '\e]1337;SetUserVar=%s=%s\007' "$1" "${x//$'\n'}"
}
if (( ! $+functions[iterm2_print_user_vars] )); then
function iterm2_print_user_vars() { }
fi
function -z4h-iterm2-dump() {
-z4h-tmux-bypass '\e]1337;RemoteHost=%s@%s\a' "${(%):-%n}" "${iterm2_hostname:-${(%):-%m}}"
# I don't know what iTerm2 wants to be escaped and how. The official shell
# integration doesn't escape anything, which is clearly wrong because \a
# obviously cannot be passed as is.
if [[ $PWD == /* && $PWD -ef . ]]; then
local cwd=$PWD
else
local cwd=${${:-.}:a}
fi
-z4h-tmux-bypass '\e]1337;CurrentDir=%s\a' "${${cwd//$'\a'/\\a}//$'\e'/\\e}"
iterm2_print_user_vars
}
function -z4h-iterm2-precmd() {
zle && return
if (( _z4h_iterm_cmd )); then
(( _z4h_iterm_cmd == 1 )) && -z4h-tmux-bypass '\e]133;C;\a'
-z4h-tmux-bypass '\e]133;D;%s\a' $1
fi
-z4h-iterm2-dump
typeset -gi _z4h_iterm_cmd=1
}
function -z4h-iterm2-preexec() {
-z4h-tmux-bypass '\e]133;C;\a'
typeset -gi _z4h_iterm_cmd=2
}
typeset -g ITERM_SHELL_INTEGRATION_INSTALLED=Yes
typeset -gi _z4h_iterm_cmd=0 # this parameter is read by p10k
unfunction -- -z4h-enable-iterm2-integration
autoload -Uz -- -z4h-enable-iterm2-integration

37
fn/-z4h-error-command Normal file
View file

@ -0,0 +1,37 @@
#!/usr/bin/env zsh
local home=~
local zdotdir=${${${(q)ZDOTDIR}/#${(q)home}/'~'}//\%/%%}
local z4h=${${${(q)Z4H}/#${(q)home}/'~'}//\%/%%}
print -Pru2 -- ''
print -Pru2 -- '%F{3}z4h%f: %B'${1//\%/%%}'%b %F{1}failed%f'
print -Pru2 -- ''
print -Pru2 -- 'See error messages above to identify the culprit.'
print -Pru2 -- ''
print -Pru2 -- 'Edit Zsh configuration:'
print -Pru2 -- ''
print -Pru2 -- ' %F{2}'${(q)${VISUAL:-${EDITOR:-vi}}}'%f %U'$zdotdir'/.zshrc%u'
if [[ $1 != update ]]; then
print -Pru2 -- ''
print -Pru2 -- 'Retry Zsh initialization:'
print -Pru2 -- ''
print -Pru2 -- ' %U%F{2}exec%u zsh%f'
fi
print -Pru2 -- ''
print -Pru2 -- 'If nothing helps and you are about to give up:'
print -Pru2 -- ''
print -Pru2 -- ' %F{5}# nuke the entire site from orbit'
print -Pru2 -- ' %F{2}%Usudo%u rm%f -rf -- %U'$z4h'%u'
if (( $+commands[curl] )); then
print -Pru2 -- ''
print -Pru2 -- 'Give up and start over:'
print -Pru2 -- ''
print -Pru2 -- ' %F{2}sh%f -c %F{3}"%f$(%F{2}curl%f -fsSL %Uhttps://raw.githubusercontent.com/romkatv/zsh4humans/v5/install%u)%F{3}"%f'
print -Pru2 -- ''
elif (( $+commands[wget] )); then
print -Pru2 -- ''
print -Pru2 -- 'Give up and start over:'
print -Pru2 -- ''
print -Pru2 -- ' %F{2}sh%f -c %F{3}"%f$(%F{2}wget%f -O- %Uhttps://raw.githubusercontent.com/romkatv/zsh4humans/v5/install%u)%F{3}"%f'
print -Pru2 -- ''
fi

View file

@ -0,0 +1,23 @@
#!/usr/bin/env zsh
local home=~
local zdotdir=${${${(q)ZDOTDIR}/#${(q)home}/'~'}//\%/%%}
if [[ ! -t 2 ]]; then
(( $+functions[p10k] )) && p10k clear-instant-prompt
fi
print -Pru2 -- '%F{3}z4h%f: iTerm2 integration loaded incorrectly!'
print -Pru2 -- ''
print -Pru2 -- 'To fix this issue:'
print -Pru2 -- ''
print -Pru2 -- '1. Add this line at the top of %U'$zdotdir'/.zshrc%u:'
print -Pru2 -- ''
print -Pru2 -- " %F{2}zstyle%f %F{3}':z4h:'%f term-shell-integration %F{3}'yes'%f"
print -Pru2 -- ''
print -Pru2 -- '2. (Optional) Remove the following line (or similar) from %U'$zdotdir'/.zshrc%u:'
print -Pru2 -- ''
print -Pru2 -- ' %F{2}source%f %U~/.iterm2_shell_integration.zsh%u'
unfunction -- -z4h-error-iterm2-integration
autoload -Uz -- -z4h-error-iterm2-integration

View file

@ -0,0 +1,19 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
print -Pru2 -- "%F{3}z4h%f: core parameters have unexpectedly changed"
local -a old=(${(0)_z4h_param_sig})
local -a new=(${(0)${(e)_z4h_param_pat}})
local diff_old=(${new:|old})
local diff_new=(${old:|new})
print -Pru2 -- ""
print -Pru2 -- "%F{2}Expected:%f"
print -Pru2 -- ""
print -lru2 -- " "$^diff_old
print -Pru2 -- ""
print -Pru2 -- "%F{1}Found:%f"
print -Pru2 -- ""
print -lru2 -- " "$^diff_new
print -Pru2 -- ""
print -Pru2 -- "Restore the parameters or restart Zsh with %F{2}%Uexec%u zsh%f."

58
fn/-z4h-find Normal file
View file

@ -0,0 +1,58 @@
#!/usr/bin/env zsh
local dot_glob=$1
local only_dirs=$2
local dirs=("${@:3}")
(( $#dirs )) || return 0
local -a bin
local -a flags
() {
emulate -L zsh
# Set dot_glob in case the value of find-flags depends on it (via `zstyle -e`).
# Ideally we should run this with user options.
(( dot_glob )) && setopt dot_glob
local widget=${WIDGET#z4h-}
zstyle -a :z4h:$widget find-command bin
if (( ! $#bin )); then
if (( $+commands[bfs] )); then
bin=(command bfs)
else
bin=(command find)
fi
fi
zstyle -a :z4h:$widget find-flags flags
if (( ! $#flags )); then
flags=(-name '.*' -prune -print -o -print)
fi
}
local -a cmd
local -aU fss
fss=(${(f)"$("${bin[@]}" / . -maxdepth 0 -printf '%F\n' 2>/dev/null)"}) || fss=()
if (( $#fss )) && [[ -z ${(M)fss:#unknown} ]]; then
cmd+=("${bin[@]}" -L ./$^dirs)
(( only_dirs )) && cmd+=('!' -type d -prune -o)
cmd+=('!' '(')
local fs
for fs in $fss; do
cmd+=(-fstype $fs -o)
done
cmd[-1]=(')' -prune '(' "${flags[@]}" ')')
(( dot_glob )) || cmd+=(-o -name '.*' -prune)
cmd+=(-o "${flags[@]}")
else
cmd+=("${bin[@]}" -L . -xdev -mindepth 1)
(( only_dirs )) && cmd+=('!' -type d -prune -o)
cmd+=('!' -path './*/*' '!' '(')
local dir
for dir in $dirs; do
cmd+=(-name ${(b)dir} -o)
done
cmd[-1]=(')' -prune)
(( dot_glob )) || cmd+=(-o -name '.*' -prune)
cmd+=(-o "${flags[@]}")
fi
"${cmd[@]}"

21
fn/-z4h-find-prev-zword Normal file
View file

@ -0,0 +1,21 @@
#!/usr/bin/env zsh
#
# Usage: -z4h-find-prev-zword
#
# Sets reply=(START END) such that BUFFER[START,END] contains the shell word
# that the cursor is on, or the previous shell word if the cursor is on
# whitespace. If there are no shell words in $PREBUFFER$BUFFER, return 1
# without setting reply. START and END can be non-positive, which means that
# a part of the shell word is in PREBUFFER.
emulate -L zsh -o extended_glob
local word buf=$PREBUFFER$BUFFER
for word in '' ${(Z:n:)buf}; do
tail=${${buf:$#word}##[[:space:]]#}
(( ! $#tail || $#tail < $#RBUFFER )) && break
buf=$tail
done
[[ -n $word ]] || return
local -i start=$(($#BUFFER - $#buf + 1))
local -i end=$((start + $#word - 1))
typeset -g reply=($start $end)

7
fn/-z4h-fix-locale Normal file
View file

@ -0,0 +1,7 @@
#!/usr/bin/env zsh
# Try in order: C.UTF-8, en_US.UTF-8, the first UTF-8 locale in lexicographical order.
(( $+commands[locale] )) || return
local loc=(${(@M)$(locale -a):#*.(utf|UTF)(-|)8})
(( $#loc )) || return
export LC_ALL=${loc[(r)(#i)C.UTF(-|)8]:-${loc[(r)(#i)en_US.UTF(-|)8]:-$loc[1]}}

30
fn/-z4h-flowing Normal file
View file

@ -0,0 +1,30 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local -a centered indentation
zparseopts -D -F -- c=centered i:=indentation || return '_z4h_err()'
local -i centered=$#centered
local -i indentation=$(( indentation[2] ))
local -i columns='COLUMNS > 0 && COLUMNS <= 80 ? COLUMNS: 80'
local REPLY line word lines=()
for word in "$@"; do
-z4h-prompt-length ${(g::):-"$line $word"}
if (( REPLY > columns )); then
[[ -z $line ]] || lines+=$line
line=
fi
if [[ -n $line ]]; then
line+=' '
elif (( $#lines )); then
line=${(pl:$indentation:: :)}
fi
line+=$word
done
[[ -z $line ]] || lines+=$line
for line in $lines; do
-z4h-prompt-length ${(g::)line}
(( centered && REPLY < columns )) && print -n -- ${(pl:$(((columns - REPLY) / 2)):: :)}
print -P -- $line
done

64
fn/-z4h-fzf Normal file
View file

@ -0,0 +1,64 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local widget=${WIDGET#z4h-}
local -a cmd flags bindings
zstyle -a :z4h:$widget fzf-command cmd || cmd=($Z4H/fzf/bin/fzf)
zstyle -a :z4h:$widget fzf-flags flags || flags=()
zstyle -a :z4h:$widget fzf-bindings bindings || bindings=()
local -A keys=(
ctrl-h backward-kill-word
alt-j clear-query
ctrl-u clear-query
ctrl-k kill-line
alt-k unix-line-discard
ctrl-space toggle-out
ctrl-a toggle-all
)
if (( ${@[(I)--layout=default]} )); then
keys+=(
tab up
btab down
ctrl-r up
ctrl-s down
)
else
keys+=(
tab down
btab up
ctrl-r down
ctrl-s up
)
fi
local kv
for kv in $bindings; do
kv=(${(s.:.)kv})
(( $#kv == 2 )) || continue
keys[$kv[1]]=$kv[2]
done
local k v
local -i expect
for k v in ${(kv)keys}; do
if [[ +$v+ == *+repeat+* ]]; then
flags=(--expect=$k "${flags[@]}")
expect=1
if [[ $v == repeat(|+*) ]]; then
keys[$k]=ignore
else
keys[$k]=${v%%+repeat(|+*)}
fi
fi
done
local keymap
printf -v keymap '%s:%s,' ${(kv)keys}
local out=$("${cmd[@]}" "$@" --bind=${keymap%,} "${flags[@]}")
[[ -n $out ]] || return
(( expect )) || print
print -r -- $out

View file

@ -0,0 +1,32 @@
#!/usr/bin/env zsh
local -a deps=(
'/usr/libexec/path_helper'
'/etc/paths(N)'
'/etc/paths.d/*(N)'
'/etc/manpaths(N)'
'/etc/manpaths.d/*(N)'
)
local -a stat files=($~deps)
zstat -A stat +mtime -- $files 2>/dev/null || return
local script
script="$(PATH= MANPATH= $deps[1] -s)" || return
(
eval "$script" || return
>$Z4H/cache/init-darwin-paths.tmp.$$ print -r -- '() {
local deps=('${(@q)deps}')
local -a stat files=($~deps)
[[ ${(j: :)${(@q)files}} == '${(q)${(j: :)${(@q)files}}}' ]] &&
zstat -A stat +mtime -- $files 2>/dev/null &&
[[ ${(j: :)stat} == '${(q)${(j: :)stat}}' ]] && {
local path_dirs=('${(j: :)${(@q)path}}')
local manpath_dirs=('${(j: :)${(@q)manpath}}')
path=(${path_dirs:|path} $path)
manpath=(${manpath_dirs:|manpath} $manpath)
}
}' || return
zf_mv -f -- $Z4H/cache/init-darwin-paths.tmp.$$ $Z4H/cache/init-darwin-paths
)

24
fn/-z4h-get-cursor-pos Normal file
View file

@ -0,0 +1,24 @@
#!/usr/bin/env zsh
#
# If invoked with an argument, passes unrecognized TTY content to zle.
local fd=${_z4h_tty_fd-1}
[[ -t $fd ]] || return
# Note: `read -u $fd` doesn't work.
local resp
IFS= builtin read -srt 5 -d R resp$'?\e[6n' <&$fd || return
while [[ $resp != *$'\e['<->';'<-> ]]; do
IFS= builtin read -srt 5 -d R resp <&$fd || return
done
if (( ARGC )); then
local pref=${resp%$'\e['*}
[[ -n $pref ]] && print -rz -- $pref
fi
resp=${resp##*'['}
typeset -g cursor_y=${resp%';'*}
typeset -g cursor_x=${resp#*';'}

8
fn/-z4h-help-bindkey Normal file
View file

@ -0,0 +1,8 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
print -Pr -- "$(<<\END
Usage: %F{2}z4h%f %Bbindkey%b [--] zle-widget key-binding [key-binding]...
END
)"

36
fn/-z4h-help-compile Normal file
View file

@ -0,0 +1,36 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
print -Pr -- "$(<<\END
Usage: %F{2}z4h%f %Bcompile%b [--] [%Ufile%u]...
Compile the specified Zsh files with %F{2}zcompile%f, skipping over
inexisting files. It takes less time to %F{2}source%f a file that thas
previously been compiled.
If you want to source files immediately after compiling them,
use %F{2}z4h%f %Bsource%b with %B--compile%b instead.
Exit code of %F{2}z4h%f %Bcompile%b is that of the last %F{2}zcompile%f call.
Inexisting files do not affect exit code.
Note that sourcing compiled files may have a different effect
than plain sourcing. Namely, aliases defined within a sourced
file are not expanded in that same file when it's compiled.
For example:
%% %F{2}cat%f %Uconfig.zsh%u
%F{2}alias%f echo=%F{3}'echo hello'%f
%F{2}echo%f world
%% ( %F{2}source%f %Uconfig.zsh%u )
hello world
%% ( %F{2}z4h%f compile %Uconfig.zsh%u; %F{2}source%f %Uconfig.zsh%u )
world
END
)"

25
fn/-z4h-help-load Normal file
View file

@ -0,0 +1,25 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
print -Pr -- "$(<<\END
Usage: %F{2}z4h%f %Bload%b [-c|--compile] [--] [%Udir%u]...
Load plugins in Oh My Zsh or Prezto format skipping over
inexisting directories. If %B-c%b or %B--compile%b is specified,
plugin source files are automatically compiled with %F{2}zcompile%f
to speed up subsequent loading. This gives you faster Zsh
startup.
Relative directory names are resolved from %U$Z4H/%u. This is
the directory where %F{2}z4h%f %Binstall%b puts downloaded files.
%F{2}z4h%f %Binstall%b ohmyzsh/ohmyzsh
...
%F{2}z4h%f %Bload%b ohmyzsh/ohmyzsh/plugins/emoji-clock
Exit code of %F{2}z4h%f %Bload%b is that of sourcing the last plugin's
source file. Inexisting plugin directories do not affect
exit code.
END
)"

41
fn/-z4h-help-source Normal file
View file

@ -0,0 +1,41 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
print -Pr -- "$(<<\END
Usage: %F{2}z4h%f %Bsource%b [-c|--compile] [--] [%Ufile%u]...
Source the specified Zsh files, skipping over inexisting ones.
If %B-c%b or %B--compile%b is specified, files are automatically
compiled with %F{2}zcompile%f to speed up subsequent sourcing. This
gives you faster Zsh startup.
Relative file names are resolved from %U$Z4H/%u. This is the
directory where %F{2}z4h%f %Binstall%b puts downloaded files.
%F{2}z4h%f %Binstall%b ohmyzsh/ohmyzsh
...
%F{2}z4h%f %Bsource%b ohmyzsh/ohmyzsh/lib/diagnostics.zsh
Exit code of %F{2}z4h%f %Bsource%b is that of the last sourced file.
Inexisting files do not affect exit code.
Compilation isn't enabled by default because it has one
negative side effect. Namely, aliases defined within a
sourced file are not expanded in that same file. For
example:
%% %F{2}cat%f %U~/config.zsh%u
%F{2}alias%f echo=%F{3}'echo hello'%f
%F{2}echo%f world
%% ( %F{2}z4h%f source %U~/config.zsh%u )
hello world
%% ( %F{2}z4h%f source -c %U~/config.zsh%u )
world
END
)"

22
fn/-z4h-help-ssh Normal file
View file

@ -0,0 +1,22 @@
#!/usr/bin/env zsh
print -Pr -- "$(<<\END
Usage: %F{2}z4h%f %Bssh%b [%Ussh-options%u]... [--] [%Uuser@%u]%Uhostname%u
Connect to the remote host over SSH and start Zsh with local configs.
The remote host must have internet access, standard POSIX utilities
and directories, and a login shell compatible with the Bourne shell
(sh, bash, zsh, ash, dash, etc.) or csh/tcsh. Nothing else is required.
Here's what %F{2}z4h%f %Bssh%b does in more detail:
1. Archives Zsh config files on the local host and sends them to the
remote host.
2. Extracts Zsh config files on the remote host.
3. Sources %U.zshenv%u with Z4H_BOOTSRAPING=%F{3}'1'%f, which starts the usual
%Bzsh4humans%b bootstrap process.
The first login to a remote host may take some time. After that it's
as fast as normal %F{2}ssh%f.
END
)"

136
fn/-z4h-init Normal file
View file

@ -0,0 +1,136 @@
#!/usr/bin/env zsh
autoload -Uz add-zsh-hook || return
if [[ $commands[zsh] != $_z4h_exe ]]; then
export _Z4H_EXE=$_z4h_exe
path=($Z4H/zsh4humans/zb $path)
fi
# Use lesspipe if available. It allows you to use less on binary files (*.tar.gz, *.jpg, etc.).
if (( $+commands[lesspipe] || $+commands[lesspipe.sh] )); then
export LESSOPEN="| /usr/bin/env ${(q)${commands[lesspipe]:-${commands[lesspipe.sh]}}} %s 2>/dev/null"
fi
# This affects every invocation of `less`.
#
# -i case-insensitive search unless search string contains uppercase letters
# -R color
# -F exit if there is less than one page of content
# -X keep content on screen after exit
# -M show more info at the bottom prompt line
# -x4 tabs are 4 instead of 8
export LESS='-iRFXMx4'
(( $+commands[less] )) && export PAGER=less
# LS_COLORS is used by GNU ls and Zsh completions. LSCOLORS is used by BSD ls.
export LS_COLORS='fi=00:mi=00:mh=00:ln=01;36:or=01;31:di=01;34:ow=04;01;34:st=34:tw=04;34:'
LS_COLORS+='pi=01;33:so=01;33:do=01;33:bd=01;33:cd=01;33:su=01;35:sg=01;35:ca=01;35:ex=01;32'
export LSCOLORS='ExGxDxDxCxDxDxFxFxexEx'
# TREE_COLORS is used by GNU tree. It looks awful with underlined text, so we turn it off.
export TREE_COLORS=${LS_COLORS//04;}
if [[ $OSTYPE == linux-* && -r /proc/version &&
( -v commands[cmd.exe] || -e /mnt/c/Windows/System32/cmd.exe ) ]]; then
-z4h-init-wsl
fi
if (( $+commands[less] )); then
READNULLCMD=less
elif (( $+commands[more] )); then
READNULLCMD=more
elif (( $+commands[cat] )); then
READNULLCMD=cat
fi
TIMEFMT='user=%U system=%S cpu=%P total=%*E' # output format of `time` reserved word
: ${DIRSTACKSIZE:=10000}
zstyle -t :z4h:ssh-agent: start && -z4h-start-ssh-agent
function -z4h-wrap-commands() {
emulate -L zsh
if (( _z4h_wrap_ssh != 2 )); then
if (( _z4h_wrap_ssh )); then
if [[ ! -v functions[ssh] ]]; then
typeset -gi _z4h_wrap_ssh=2
elif [[ ! -v commands[ssh] ]]; then
unset _z4h_wrap_ssh
unfunction ssh
fi
else
if [[ -v functions[ssh] ]]; then
typeset -gi _z4h_wrap_ssh=2
elif [[ -v commands[ssh] ]]; then
function ssh() { z4h ssh "$@" }
typeset -gi _z4h_wrap_ssh=1
fi
fi
fi
if (( _z4h_wrap_sudo != 2 )); then
if (( _z4h_wrap_sudo )); then
if [[ ! -v functions[sudo] ]]; then
typeset -gi _z4h_wrap_sudo=2
elif [[ ! -v commands[sudo] ]]; then
unset _z4h_wrap_sudo
unfunction sudo
fi
else
if [[ -v functions[sudo] ]]; then
typeset -gi _z4h_wrap_sudo=2
elif [[ -v commands[sudo] ]]; then
function sudo() { z4h sudo "$@" }
typeset -gi _z4h_wrap_sudo=1
fi
fi
fi
if (( _z4h_wrap_docker != 2 )); then
if (( _z4h_wrap_docker )); then
if [[ ! -v functions[docker] ]]; then
typeset -gi _z4h_wrap_docker=2
elif [[ ! -v commands[docker] ]]; then
unset _z4h_wrap_docker
unfunction docker
fi
else
if [[ -v functions[docker] ]]; then
typeset -gi _z4h_wrap_docker=2
elif [[ -v commands[docker] ]]; then
function docker() { z4h docker "$@" }
typeset -gi _z4h_wrap_docker=1
fi
fi
fi
}
-z4h-wrap-commands
if [[ ! -e $Z4H/zsh4humans/fn/-z4h-compinit-impl ]]; then
-z4h-postinstall-self || return
fi
if (( _z4h_zle )); then
-z4h-init-zle || return
else
-z4h-cmd-bindkey() {}
function compdef() {}
function complete() {}
fi
function compinit() {}
function bashcompinit() {}
# Aliases.
if (( $+commands[dircolors] )); then # proxy for GNU coreutils vs BSD
# Don't define aliases for commands that point to busybox.
[[ ${${:-diff}:c:A:t} == busybox* ]] || alias diff='diff --color=auto'
[[ ${${:-ls}:c:A:t} == busybox* ]] || alias ls='ls --color=auto'
else
[[ ${${:-ls}:c:A:t} == busybox* ]] || alias ls='ls -G'
fi
[[ ${${:-grep}:c:A:t} == busybox* ]] || alias grep='grep --color=auto --exclude-dir={.bzr,CVS,.git,.hg,.svn}'

23
fn/-z4h-init-wsl Normal file
View file

@ -0,0 +1,23 @@
#!/usr/bin/env zsh
local cmd=${commands[cmd.exe]:-/mnt/c/Windows/System32/cmd.exe}
[[ -x $cmd ]] || return
case "$(</proc/version)" in
*Microsoft*) typeset -gi z4h_no_flock=1;;
*microsoft*) ;;
*) return ;;
esac
local lines=("${(@f)${$(cd -q -- ${cmd:h} && ./${cmd:t} /c set 2>/dev/null)//$'\r'}}")
local keys=(${lines%%=*}) vals=(${lines#*=})
typeset -grA z4h_win_env=(${keys:^vals})
local home=$z4h_win_env[USERPROFILE]
[[ -n $home ]] || return
if [[ $home != [a-zA-Z]':\'* ||
( ! -d ${home::=/mnt/${(L)home[1]}/${${home:3}//\\//}} &&
! -d ${home::=${home#/mnt}} ) ]]; then
home=$(command wslpath -- $z4h_win_env[USERPROFILE] 2>/dev/null) || return
[[ -d $home ]] || return
fi
typeset -gr z4h_win_home=$home

1103
fn/-z4h-init-zle Normal file

File diff suppressed because it is too large Load diff

19
fn/-z4h-insert-all Normal file
View file

@ -0,0 +1,19 @@
#!/usr/bin/env zsh
local hook=${widgets[zle-line-pre-redraw]-}
if [[ $hook == user:* ]]; then
hook=${hook#user:}
else
hook=
fi
{
if [[ -n $hook ]]; then
builtin zle -D zle-line-pre-redraw
fi
builtin zle -- -z4h-comp-insert-all
} always {
if [[ -n $hook ]]; then
zle -N -- zle-line-pre-redraw "$hook"
fi
}

125
fn/-z4h-install-many Normal file
View file

@ -0,0 +1,125 @@
#!/usr/bin/env zsh
local success
{
if (( ! $+_z4h_no_autoupdate && ! $+Z4H_SSH && !_z4h_dangerous_root && _z4h_zle )) &&
zstyle -t :z4h: auto-update ask && [[ -t 0 && -t 1 && -t 2 ]]; then
typeset -gri _z4h_no_autoupdate=1
local days
if zstyle -s :z4h: auto-update-days days && [[ $days == <-> ]]; then
# Check if update is required.
local -a last_update_ts
if zstat -A last_update_ts +mtime -- $Z4H/cache/last-update-ts 2>/dev/null &&
(( EPOCHSECONDS - last_update_ts[1] >= 86400 * days )) &&
[[ ! -e $Z4H/.updating ]]; then
local REPLY
{
read -q ${(%):-"?%F{3}z4h%f: update dependencies? [y/N]: "} && REPLY=y
} always {
print -u ${_z4h_tty_fd-2}
}
print -n >$Z4H/cache/last-update-ts || return
if [[ $REPLY == y ]]; then
z4h update && return
fi
print -Pru2 -- "%F{3}z4h%f: won't ask to update again for %B$days%b day(s)"
print -Pru2 -- ""
print -Pru2 -- "To update manually, type:"
print -Pru2 -- ""
print -Pru2 -- " %F{2}z4h%f %Bupdate%b"
print -Pru2 -- ""
fi
fi
fi
local -aU want=(${_z4h_install_queue%%@*})
local have=($Z4H/$^want(N))
have=(${have#$Z4H/})
local missing=(${want:|have})
(( $#missing )) || return 0
if [[ ! -v commands[uname] ]]; then
print -Pru2 -- '%F{3}z4h%f: command not found: %F{1}uname%f'
return 1
fi
local uname_sm
uname_sm=$(uname -sm) || return
case ${(L)uname_sm} in
'darwin arm64');;
'darwin x86_64');;
'linux aarch64');;
'linux armv6l');;
'linux armv7l');;
'linux armv8l');;
'linux x86_64');;
'linux i686');;
*)
print -Pru2 -- "%F{3}z4h%f: unsupported platform: %F{1}${uname_sm//\%/%%}%f"
return 1
;;
esac
local repo base queue=()
for repo in $_z4h_install_queue; do
base=${repo%%@*}
(( missing[(Ie)$base] )) || continue
missing=(${missing:#$base})
queue+=($repo)
done
if (( _z4h_dangerous_root )); then
for repo in $queue; do
print -Pru2 -- "%F{3}z4h%f: refusing to %Binstall%b as %F{1}root%f: %B${repo//\%/%%}%b"
done
return 1
fi
typeset -gi _z4h_installed_something=1
if (( $#queue == 1 )) || [[ -o interactive && ZSH_SUBSHELL -ne 0 ]] ||
! () { setopt localoptions monitor 2>/dev/null }; then
for repo in $queue; do
-z4h-install-one $repo || return
done
return
fi
if (( $+commands[mktemp] )); then
success="$(command mktemp -- $Z4H/tmp/install-many.XXXXXXXXXX)" || return
else
success=$Z4H/tmp/install-many.$$
zf_rm -rf -- $success || return
print -n >$success || return
fi
function -z4h-install-many-parallel() {
eval "$_z4h_opt"
local repo fd head=() tail=()
local omz=ohmyzsh/ohmyzsh
queue=(${(M)queue:#powerlevel10k} ${queue:#powerlevel10k})
queue=(${queue:#$omz} ${(M)queue:#$omz})
for repo in $queue; do
if (( $#head + $#tail == 8 )); then
fd=$head[1]
<&$fd >&2 || return
exec {fd}<&- || return
shift 1 head
fi
exec {fd}< <( (-z4h-install-one $repo 2>&1 ) || zf_rm -f -- $success ) || return
[[ $repo == powerlevel10k ]] && tail+=$fd || head+=$fd
done
for fd in $head $tail; do
<&$fd >&2 || return
exec {fd}<&- || return
done
}
-z4h-run-process-tree -z4h-install-many-parallel || return
[[ -e $success ]] || return
} always {
unset _z4h_install_queue
unset "functions[-z4h-install-many-parallel]"
[[ -z $success ]] || zf_rm -f -- $success
}

150
fn/-z4h-install-one Normal file
View file

@ -0,0 +1,150 @@
#!/usr/bin/env zsh
local url postinstall command
if [[ $1 == */* ]]; then
if [[ $1 == *@* ]]; then
url=https://github.com/${1%%@*}/archive/${1#*@}.tar.gz
1=${1%%@*}
else
url=https://github.com/$1/archive/master.tar.gz
fi
if ! zstyle -s :z4h:$1 postinstall postinstall; then
case $1 in
ohmyzsh/ohmyzsh)
postinstall=-z4h-postinstall-ohmyzsh
;;
MichaelAquilina/zsh-you-should-use)
postinstall=-z4h-postinstall-zsh-you-should-use
;;
wfxr/forgit)
postinstall=-z4h-postinstall-forgit
;;
changyuheng/fz)
postinstall=-z4h-postinstall-fz
;;
zsh-users/(zsh-syntax-highlighting|zsh-autosuggestions|zsh-history-substring-search))
postinstall=-z4h-postinstall-zsh-users
;;
*)
postinstall=
;;
esac
fi
else
local -a channel
zstyle -a :z4h:$1 channel channel || channel=(stable)
local tmux_cmd='sh -- '${(q)Z4H}/zsh4humans/sc/install-tmux' -d "${Z4H_PACKAGE_DIR}" -q'
tmux_cmd+=' && print -r -- "$EPOCHREALTIME" >"${Z4H_PACKAGE_DIR}"/stamp'
local brew_cmd='command brew tap --quiet homebrew/command-not-found && zf_mkdir -- "${Z4H_PACKAGE_DIR}"'
case $#channel-$channel[1] in
2-command) command=$channel[2];;
1-stable|1-testing)
case $1 in
tmux) command=$tmux_cmd;;
homebrew-command-not-found) command=$brew_cmd;;
terminfo) url=https://github.com/romkatv/terminfo/archive/v1.4.0.tar.gz;;
*) url=https://github.com/zsh4humans/$1/archive/z4h-$channel[1].tar.gz;;
esac
;;
1-dev)
case $1 in
fzf) url=https://github.com/junegunn/$1/archive/master.tar.gz;;
powerlevel10k) url=https://github.com/romkatv/$1/archive/master.tar.gz;;
systemd) url=https://github.com/systemd/$1/archive/master.tar.gz;;
zsh-completions) url=https://github.com/zsh-users/$1/archive/master.tar.gz;;
zsh-autosuggestions) url=https://github.com/zsh-users/$1/archive/master.tar.gz;;
zsh-syntax-highlighting) url=https://github.com/zsh-users/$1/archive/master.tar.gz;;
zsh-history-substring-search) url=https://github.com/zsh-users/$1/archive/master.tar.gz;;
terminfo) url=https://github.com/romkatv/terminfo/archive/v1.3.0.tar.gz;;
tmux) command=$tmux_cmd;;
homebrew-command-not-found) command=$brew_cmd;;
*)
print -Pru2 -- "%F{3}z4h%f: %F{1}internal error%f: unknown package: ${1//\%/%%}"
return 1
;;
esac
;;
1-none)
zf_mkdir -p -- $Z4H/$1 || return
return
;;
*)
print -Pru2 -- '%F{3}z4h%f: invalid zstyle'
print -Pru2 -- ''
print -Pru2 -- " %F{2}zstyle%f :z4h:${(q)1//\%/%%} channel %F{1}${(j: :)${(@q)channel//\%/%%}}%f"
print -Pru2 -- ''
print -Pru2 -- 'Supported values: %Bstable%b, %Btesting%b and %Bdev%b.'
return 1
;;
esac
(( $+functions[-z4h-postinstall-$1] )) && postinstall=-z4h-postinstall-$1
fi
local suf
[[ $1 == systemd ]] && suf=' completions'
if [[ -e $Z4H/.updating ]]; then
print -Pru2 -- "%F{3}z4h%f: updating %B${1//\%/%%}%b$suf"
else
print -Pru2 -- "%F{3}z4h%f: installing %B${1//\%/%%}%b$suf"
fi
local dst=$Z4H/$1
zf_mkdir -p -- ${dst:h} 2>/dev/null || zf_mkdir -p -- ${dst:h} || return
local old new
{
if (( $+commands[mktemp] )); then
old="$(command mktemp -d -- $dst.old.XXXXXXXXXX)" || return
new="$(command mktemp -d -- $dst.new.XXXXXXXXXX)" || return
else
old=$dst.old.$$
new=$dst.new.$$
zf_rm -rf -- $old $new || return
zf_mkdir -p -- $old $new || return
fi
local Z4H_PACKAGE_NAME=$1 Z4H_PACKAGE_DIR=$new/${1:t}
if [[ -n $command ]]; then
() { eval $command } || return 1
if [[ ! -d $Z4H_PACKAGE_DIR ]]; then
print -Pru2 -- "%F{3}z4h%f: custom command failed to install: %F{1}${Z4H_PACKAGE_DIR//\%/%%}%f"
return 1
fi
else
local err
if (( $+commands[curl] )); then
err="$(command curl -fsSL -- $url 2>&1 >$new/snapshot.tar.gz)"
elif (( $+commands[wget] )); then
err="$(command wget -O- -- $url 2>&1 >$new/snapshot.tar.gz)"
else
print -Pru2 -- "%F{3}z4h%f: please install %F{1}curl%f or %F{1}wget%f"
return 1
fi
if (( $? )); then
print -ru2 -- $err
print -Pru2 -- "%F{3}z4h%f: failed to download %F{1}${url//\%/%%}%f"
return 1
fi
command tar -C $new -xzf $new/snapshot.tar.gz || return
local dirs=($new/*-*(N/))
if (( $#dirs != 1 )); then
print -Pru2 -- "%F{3}z4h%f: invalid content: %F{1}${url//\%/%%}%f"
return 1
fi
if [[ $dirs[1] != $new/${1:t} ]]; then
-z4h-mv $dirs[1] $new/${1:t} || return
fi
fi
eval $postinstall || return
[[ ! -e $dst ]] || -z4h-mv $dst $old/${1:t} 2>/dev/null || zf_rm -rf -- $dst || return
-z4h-mv $new/${1:t} $dst || return
} always {
[[ -z $old && -z $new ]] || zf_rm -rf -- $old $new
}

23
fn/-z4h-is-valid-list Normal file
View file

@ -0,0 +1,23 @@
#!/usr/bin/env zsh
#
# Succeeds if $1 is a well-formed command.
# If it ends with an odd number of backslashes, it's malformed.
() {
builtin emulate -L zsh -o extended_glob
[[ $1 == (|*[^\\])(\\\\)#\\ ]]
} "$1" && builtin return 1
if [[ -v functions[-z4h-test-func] ]]; then
builtin unfunction -- -z4h-test-func
fi
functions[-z4h-test-func]="$1" 2>/dev/null || builtin return 1
[[ -v functions[-z4h-test-func] ]] || builtin return 1
builtin unfunction -- -z4h-test-func
# This suffix allows us to detect two tricky cases: "for x" and "<<END".
# Each of these on their own is a valid function body but neither can
# be executed as a command in interactive shell.
functions[-z4h-test-func]="$1"$'\ndo\ndone' 2>/dev/null || builtin return 0
[[ -v functions[-z4h-test-func] ]] || builtin return 0
builtin unfunction -- -z4h-test-func
builtin return 1

120
fn/-z4h-main-complete Normal file
View file

@ -0,0 +1,120 @@
#!/usr/bin/env zsh
# Based on _main_complete from Zsh 5.8.
local IFS=$' \t\n\0'
eval "$_comp_setup"
local func funcs ret=1 tmp _compskip format nm call match min max i num \
_completers _completer _completer_num curtag _comp_force_list \
_matchers _matcher _c_matcher _matcher_num _comp_tags _comp_mesg \
mesg str context state state_descr line opt_args val_args \
curcontext="$curcontext" \
_last_nmatches=-1 _last_menu_style _def_menu_style _menu_style sel \
_tags_level=0 \
_saved_exact="${compstate[exact]}" \
_saved_lastprompt="${compstate[last_prompt]}" \
_saved_list="${compstate[list]}" \
_saved_insert="${compstate[insert]}" \
_saved_colors="$ZLS_COLORS" \
_saved_colors_set=${+ZLS_COLORS} \
_ambiguous_color=
local _comp_priv_prefix ZLS_COLORS ZLS_COLOURS
unset _comp_priv_prefix ZLS_COLORS ZLS_COLOURS
local -a precommands
local -ar builtin_precommands=(- builtin eval exec nocorrect noglob time)
typeset -U _lastdescr _comp_ignore _comp_colors
[[ -z "$curcontext" ]] && curcontext=:::
if [[ -z "$compstate[quote]" ]]; then
if [[ -o equals ]] && compset -P 1 '='; then
compstate[context]=equal
elif [[ "$PREFIX" != */* && "$PREFIX[1]" = '~' ]]; then
compset -p 1
compstate[context]=tilde
fi
fi
compstate[list]=
compstate[exact]=
compstate[insert]=unambiguous
_completers=(_complete)
_completer_num=1
integer SECONDS=0
TRAPINT () {
zle -M "Killed by signal in ${funcstack[2]} after ${SECONDS}s"
zle -R
return 130
}
TRAPQUIT () {
zle -M "Killed by signal in ${funcstack[2]} after ${SECONDS}s"
zle -R
return 131
}
funcs=("$compprefuncs[@]")
compprefuncs=()
for func in "$funcs[@]"; do
"$func"
done
for tmp in "$_completers[@]"; do
if [[ -n "$call" ]]; then
_completer="${tmp}"
elif [[ "$tmp" = *:-* ]]; then
_completer="${${tmp%:*}[2,-1]//_/-}${tmp#*:}"
tmp="${tmp%:*}"
elif [[ $tmp = *:* ]]; then
_completer="${tmp#*:}"
tmp="${tmp%:*}"
else
_completer="${tmp[2,-1]//_/-}"
fi
curcontext="${curcontext/:[^:]#:/:${_completer}:}"
zstyle -a ":completion:${curcontext}:" matcher-list _matchers || _matchers=('')
_matcher_num=1
_matcher=
for _c_matcher in "$_matchers[@]"; do
if [[ "$_c_matcher" == +* ]]; then
_matcher="$_matcher $_c_matcher[2,-1]"
else
_matcher="$_c_matcher"
fi
_comp_mesg=
if [[ -n "$call" ]]; then
if "${(@)argv[3,-1]}"; then
ret=0
break 2
fi
elif "$tmp"; then
ret=0
break 2
fi
(( _matcher_num++ ))
done
[[ -n "$_comp_mesg" ]] && break
(( _completer_num++ ))
done
curcontext="${curcontext/:[^:]#:/::}"
nm=$compstate[nmatches]
if [[ -n $compstate[quote] ]]; then
typeset -g _z4h_in_quotes=1
fi
# typeset -pm '_z4h_words|_z4h_descrs|_z4h_scaffolds|compstate' >&2
funcs=("$comppostfuncs[@]")
comppostfuncs=()
for func in "$funcs[@]"; do
"$func"
done
return ret

26
fn/-z4h-move-and-kill Normal file
View file

@ -0,0 +1,26 @@
#!/usr/bin/env zsh
local -i cursor=CURSOR
"$@"
emulate -L zsh
local -i from to
if (( CURSOR < cursor )); then
from=CURSOR+1
to=cursor
else
from=cursor+1
to=CURSOR
CURSOR=$cursor
fi
if [[ $LASTWIDGET != ((z4h-|.|)(backward-|)kill-*|(.|)copy-region-as-kill) ]]; then
zle .copy-region-as-kill -- $BUFFER[from,to]
elif (( CURSOR < cursor )); then
CUTBUFFER=$BUFFER[from,to]$CUTBUFFER
else
CUTBUFFER+=$BUFFER[from,to]
fi
BUFFER[from,to]=
zle -f kill

21
fn/-z4h-mv Normal file
View file

@ -0,0 +1,21 @@
#!/usr/bin/env zsh
(( ARGC == 2 )) || return '_z4h_err()'
[[ $2 != */ ]] || return '_z4h_err()'
zf_mv -f -- "$1" "$2" 2>/dev/null && return
command mv -f -- "$1" "$2" 2>/dev/null && return
[[ -e $1 ]] || return '_z4h_err()'
[[ -d ${2:h} ]] || return '_z4h_err()'
if [[ -e $2 ]]; then
zf_rm -rf -- "$2" || return
fi
if ! command cp -r -- "$1" "$2"; then
[[ ! -e $2 ]] || zf_rm -rf -- "$2" || return
return 1
fi
zf_rm -rf -- "$1"

35
fn/-z4h-osc9 Normal file
View file

@ -0,0 +1,35 @@
#!/usr/bin/env zsh
#
# Docs:
#
# https://learn.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory#zsh
#
# The recommended code looks like this:
#
# keep_current_path() {
# printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"
# }
# precmd_functions+=(keep_current_path)
emulate -L zsh -o no_multi_byte
[[ -v commands[wslpath] ]] || return
if [[ $PWD == /* && $PWD -ef . ]]; then
local cwd=$PWD
else
local cwd=${${:-.}:a}
fi
[[ -n $cwd ]] || return
typeset -gA _z4h_lin2win_cwd
local win_cwd=${_z4h_lin2win_cwd[$cwd]-}
if [[ -z $win_cwd ]]; then
win_cwd="$(command wslpath -am . 2>/dev/null)x" || return
win_cwd=${win_cwd[1,-2]//$'\e'/$'\e\e'}
[[ -n $win_cwd ]] || return
_z4h_lin2win_cwd[$cwd]=$win_cwd
fi
-z4h-tmux-bypass '\e]9;9;%s\e\\' "$win_cwd"

View file

@ -0,0 +1,19 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local file=$Z4H_PACKAGE_DIR/forgit.plugin.zsh
[[ -e $file ]] || return 0
local code
code=$(<$file) || return
local orig="
set | awk -F '=' '{ print \$1 }' | grep FORGIT_ | while read -r var; do
if ! export | grep -q \"\\(^\$var=\\|^export \$var=\\)\"; then
"
local sub='
for var in "${(@)parameters[(I)FORGIT_*]}"; do
if [[ ${parameters[$var]} != *export* ]]; then
'
print -r -- ${code/$orig/$sub} >$file

18
fn/-z4h-postinstall-fz Normal file
View file

@ -0,0 +1,18 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local file=$Z4H_PACKAGE_DIR/fz.plugin.zsh
[[ -e $file ]] || return 0
local code
code=$(<$file) || return
local orig='
__fz_init_zsh_completion() {
'
local sub='
__fz_init_zsh_completion() {
[[ -n ${ZSH_SCRIPT+X}${ZSH_EXECUTION_STRING+X} ]] && return
'
print -r -- ${code/$orig/$sub} >$file

59
fn/-z4h-postinstall-fzf Normal file
View file

@ -0,0 +1,59 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
if [[ -e $Z4H/.updating ]]; then
print -ru2 -- ${(%):-"%F{3}z4h%f: updating %Bfzf%b binary"}
else
print -ru2 -- ${(%):-"%F{3}z4h%f: fetching %Bfzf%b binary"}
fi
local uname_sm
[[ ! -v commands[uname] ]] || uname_sm=$(uname -sm) || return
local -i installed
case $uname_sm in
'Darwin arm64')
local v=0.25.1
local url=https://github.com/zsh4humans/fzf/releases/download/$v/fzf-$v-darwin_arm8.tar.gz
;;
'Linux i686')
local v=0.22.0
local url=https://github.com/junegunn/fzf-bin/releases/download/$v/fzf-$v-linux_386.tgz
;;
*)
local BASH_SOURCE=($Z4H_PACKAGE_DIR/install) err
if ! err=$(local opt && emulate sh && set -- --bin &&
builtin source "${BASH_SOURCE[0]}" 2>&1); then
print -ru2 -- $err
return 1
fi
installed=1
;;
esac
if (( ! installed )); then
local err archive=$Z4H_PACKAGE_DIR/fzf.tar.gz
if (( $+commands[curl] )); then
err="$(command curl -fsSL -- $url 2>&1 >$archive)"
elif (( $+commands[wget] )); then
err="$(command wget -O- -- $url 2>&1 >$archive)"
else
print -Pru2 -- "%F{3}z4h%f: please install %F{1}curl%f or %F{1}wget%f"
return 1
fi
if (( $? )); then
print -ru2 -- $err
print -Pru2 -- "%F{3}z4h%f: failed to download %F{1}${url//\%/%%}%f"
return 1
fi
[[ -e $Z4H_PACKAGE_DIR/bin ]] || zf_mkdir -- $Z4H_PACKAGE_DIR/bin || return
command tar -C $Z4H_PACKAGE_DIR/bin -xzf $archive || return
zf_rm -- $archive || return
fi
if [[ -h $Z4H_PACKAGE_DIR/bin/fzf ]]; then
command cp -- $Z4H_PACKAGE_DIR/bin/fzf $Z4H_PACKAGE_DIR/bin/fzf.tmp || return
zf_mv -f -- $Z4H_PACKAGE_DIR/bin/fzf.tmp $Z4H_PACKAGE_DIR/bin/fzf || return
fi

View file

@ -0,0 +1,5 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
z4h compile -- $Z4H_PACKAGE_DIR/{oh-my-zsh.sh,**/*.zsh}(.N)

View file

@ -0,0 +1,21 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
zf_mkdir -p -- $Z4H/cache/powerlevel10k/p10k-root || return
if [[ $GITSTATUS_AUTO_INSTALL != 0 ]]; then
if [[ -e $Z4H/.updating ]]; then
print -ru2 -- ${(%):-"%F{3}z4h%f: updating %Bgitstatus%b binary"}
else
print -ru2 -- ${(%):-"%F{3}z4h%f: fetching %Bgitstatus%b binary"}
fi
(
unset -m 'GITSTATUS_*~GITSTATUS_CACHE_DIR'
export GITSTATUS_CACHE_DIR=$GITSTATUS_CACHE_DIR
$Z4H_PACKAGE_DIR/gitstatus/install -f
) || return
fi
z4h compile -- $Z4H_PACKAGE_DIR/{*.zsh-theme,internal/*.zsh,gitstatus/*.zsh,gitstatus/install}(N)

14
fn/-z4h-postinstall-self Normal file
View file

@ -0,0 +1,14 @@
#!/usr/bin/env zsh
z4h compile -- $Z4H/zsh4humans/{main.zsh,sc/exec-zsh-i,fn/(|-|_)z4h[^.]#~*.zwc} $Z4H/z4h.zsh || return
[[ -v functions[compinit] ]] && unfunction compinit
autoload -Uz +X compinit || return
local orig="bindkey '^i' | IFS=\$' \t' read -A _i_line"
local replacement="_i_line=( '\"^I\"' z4h-fzf-complete )"
print -r -- ${functions[compinit]/$orig/$replacement} >$Z4H/zsh4humans/fn/tmp.$$.compinit || return
zf_mv -- $Z4H/zsh4humans/fn/tmp.$$.compinit $Z4H/zsh4humans/fn/-z4h-compinit-impl || return
z4h compile -- $Z4H/zsh4humans/fn/-z4h-compinit-impl || return
autoload -Uz -- -z4h-compinit-impl
function compinit() {}

View file

@ -0,0 +1,30 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local comp=$Z4H_PACKAGE_DIR/shell-completion/zsh/_systemctl
[[ -e $comp.in ]] || return 0
[[ -v commands[systemd-path] ]] || return 0
local lib
lib=$(systemd-path system-library-private) || return
if [[ $lib != /* ]]; then
print -Pru2 -- '%F{3}z4h%f: unexpected command output: %F{1}systemd-path system-library-private%f'
return 1
fi
if [[ -x /usr/lib/systemd/systemd ]]; then
local systemd=/usr/lib/systemd
elif [[ -x /lib/systemd/systemd ]]; then
local systemd=/lib/systemd
else
print -Pru2 -- '%F{3}z4h%f: command not found: %F{1}systemd%f'
return 1
fi
local content
content=$(<$comp.in)
print -r -- ${${content//@rootlibexecdir@/$systemd}//\\@/@} >$comp
zf_rm -- $comp.in

View file

@ -0,0 +1,27 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
# Fork to avoid triggering https://www.zsh.org/mla/workers/2020/msg00588.html
(
# ${(L):-I} is ı in Turkish locale.
LC_ALL=C
local pat hex char
for pat in "[^A-Z]" "[A-Z]"; do
for hex in $Z4H_PACKAGE_DIR/[[:xdigit:]][[:xdigit:]](:t); do
printf -v char "\\x$hex"
[[ $char == $~pat ]] || continue
[[ -e ~/.terminfo/$hex ]] || zf_mkdir -p -- ~/.terminfo/$hex || return
cp -- $Z4H_PACKAGE_DIR/$hex/* ~/.terminfo/$hex/ || return
if [[ $char == [a-z] || ! ~/.terminfo/$char -ef ~/.terminfo/${(L)char}] ]]; then
[[ -e ~/.terminfo/$char ]] ||
zf_ln -s -- $hex ~/.terminfo/$char 2>/dev/null ||
zf_mkdir -p -- ~/.terminfo/$char ||
return
cp -- $Z4H_PACKAGE_DIR/$hex/* ~/.terminfo/$char/ || return
fi
zf_rm -rf -- $Z4H_PACKAGE_DIR/$hex || return
done
done
)

View file

@ -0,0 +1,5 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
z4h compile -- $Z4H_PACKAGE_DIR/{zsh-autosuggestions.zsh,src/**/*.zsh}(N)

View file

@ -0,0 +1,5 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
z4h compile -- $Z4H_PACKAGE_DIR/zsh-history-substring-search.zsh

View file

@ -0,0 +1,5 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
z4h compile -- $Z4H_PACKAGE_DIR/{zsh-syntax-highlighting.zsh,highlighters/*/*.zsh}(N)

View file

@ -0,0 +1,19 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local file=$Z4H_PACKAGE_DIR/${Z4H_PACKAGE_NAME:t}.zsh
[[ -e $file ]] || return 0
local code
code=$(<$file) || return
local orig='
'
local sub='
[[ -n ${ZSH_SCRIPT+X}${ZSH_EXECUTION_STRING+X} ]] && return
'
print -r -- ${code/$orig/$sub} >$file

View file

@ -0,0 +1,25 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local file=$Z4H_PACKAGE_DIR/zsh-you-should-use.plugin.zsh
[[ -e $file ]] || return 0
local code
code=$(<$file) || return
local orig='
NONE="$(tput sgr0)"
BOLD="$(tput bold)"
RED="$(tput setaf 1)"
YELLOW="$(tput setaf 3)"
PURPLE="$(tput setaf 5)"
'
local sub="
NONE=\$'\\e[0m'
BOLD=\$'\\e[1m'
RED=\$'\\e[31m'
YELLOW=\$'\\e[33m'
PURPLE=\$'\\e[35m'
"
print -r -- ${code/$orig/$sub} >$file

148
fn/-z4h-present-files Normal file
View file

@ -0,0 +1,148 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
setopt octalzeroes
local -i list_colors=$1
local -i list_types=$2
local -i tilde_unexpand=$3
[[ $_z4h_mode_colors[ln] != target ]]
local -i ln_target=$?
local -r nil=$'\0'
local -r or=$_z4h_mode_colors[or]
local -r ln=$_z4h_mode_colors[ln]
local -r suf=('|' '|' '' '' '' '' '/' '/' '' '' '' '' '' '' '' '*' '' '' '@' '@' '' '' '=' '=')
local -i10 m i
local buf file style
local -a files modes link link_mode
local -i MATCH
local MBEGIN MEND
while true; do
while [[ $buf != *$'\n'* ]]; do
sysread -s 4096 'buf[$#buf+1]' && continue
(( $? == 5 )) || return
return
done
files=("${(@f)buf}")
buf=$files[-1]
files[-1]=()
if (( ! list_colors && ! list_types && ! tilde_unexpand )) || ! zstat -L -A modes +mode -- $files; then
printf '%1$s\0%1$q\n' $files
continue
fi
if (( ! list_colors && ! tilde_unexpand )); then
printf '%2$s\0%2$q%1$s\n' \
${"${(@)modes/(#m)*/$suf[$((((MATCH & 61440) >> 11) | !(MATCH & 73)))]}":^files}
continue
fi
# This doesn't work the same way as GNU ls. See get_color_indicator in
# https://git.savannah.gnu.org/cgit/coreutils.git/tree/src/ls.c.
#
# TODO: fix it.
# TODO: see if this can be made faster by invoking `find` with `-printf '%Y\0%m\0%P\n'`,
# invoking `zstat -A links +link -- ${files*$'\0'*$'\0'}` and then applying some kind of
# crazy expansion.
#
# Types:
#
# ? unknown
# p fifo
# c chardev
# d directory
# b blockdev
# - normal
# s socket
# w whiteout
# l symlink (good)
# L symlink (loop)
# N symlink (nonexistent)
if (( tilde_unexpand )); then
# This implementation is the same as below except that $file in the second output field
# is replaced with ${(D)file}.
for file m in ${files:^modes}; do
if [[ ${style::=${${_z4h_mode_codes[$((m & 64075))]:-$'\0'}/%$'\0'/$'\0'$_z4h_name_colors[(ke)$file:t]}} \
== $'@\0.' ]]; then
if ! zstat -L -A link +link -- $file; then
printf '%1$s\0\e[%2$sm%3$s\e[0m\n' $file "${or:-$_z4h_name_colors[$file:t]}" ${(D)file}
elif ! zstat -A link_mode +mode -- $file; then
printf '%1$s\0\e[%2$sm%5$s\e[0m -> \e[%4$sm%3$q\e[0m\n' \
$file "${or:-$_z4h_name_colors[$file:t]}" \
$link "${or:-$_z4h_name_colors[$link:t]}" \
${(D)file}
elif (( ln_target )); then
printf '%1$s\0\e[%4$sm%5$s\e[0m -> \e[%4$sm%2$q\e[0m%3$s\n' \
$file $link \
"${(@0)${${_z4h_mode_codes[$((link_mode & 64075))]:-$nil}/%$nil/$nil$_z4h_name_colors[(ke)$link:t]}}" \
${(D)file}
else
printf '%1$s\0\e[%3$sm%6$s\e[0m -> \e[%5$sm%2$q\e[0m%4$s\n' \
$file $link "${ln:-$_z4h_name_colors[$link:t]}" \
"${(@0)${${_z4h_mode_codes[$((link_mode & 64075))]:-$nil}/%$nil/$nil$_z4h_name_colors[(ke)$link:t]}}" \
${(D)file}
fi
else
printf '%1$s\0\e[%3$sm%4$s\e[0m%2$s\n' $file "${(@0)style}" ${(D)file}
fi
done
elif (( $#_z4h_name_colors )); then
# This implementation works whether _z4h_name_colors is empty or not. It's about 30%
# slower than the alternative implementation below, which only works if _z4h_name_colors
# is empty.
for file m in ${files:^modes}; do
if [[ ${style::=${${_z4h_mode_codes[$((m & 64075))]:-$'\0'}/%$'\0'/$'\0'$_z4h_name_colors[(ke)$file:t]}} \
== $'@\0.' ]]; then
if ! zstat -L -A link +link -- $file; then
printf '%1$s\0\e[%2$sm%1$q\e[0m\n' $file "${or:-$_z4h_name_colors[$file:t]}"
elif ! zstat -A link_mode +mode -- $file; then
printf '%1$s\0\e[%2$sm%1$q\e[0m -> \e[%4$sm%3$q\e[0m\n' \
$file "${or:-$_z4h_name_colors[$file:t]}" \
$link "${or:-$_z4h_name_colors[$link:t]}"
elif (( ln_target )); then
printf '%1$s\0\e[%4$sm%1$q\e[0m -> \e[%4$sm%2$q\e[0m%3$s\n' \
$file $link \
"${(@0)${${_z4h_mode_codes[$((link_mode & 64075))]:-$nil}/%$nil/$nil$_z4h_name_colors[(ke)$link:t]}}"
else
printf '%1$s\0\e[%3$sm%1$q\e[0m -> \e[%5$sm%2$q\e[0m%4$s\n' \
$file $link "${ln:-$_z4h_name_colors[$link:t]}" \
"${(@0)${${_z4h_mode_codes[$((link_mode & 64075))]:-$nil}/%$nil/$nil$_z4h_name_colors[(ke)$link:t]}}"
fi
else
printf '%1$s\0\e[%3$sm%1$q\e[0m%2$s\n' $file "${(@0)style}"
fi
done
else
modes=("${(@)modes:/(#m)*/${_z4h_mode_codes[$((MATCH & 64075))]:-$nil}}")
while true; do
i=${modes[(i)@*]}
if (( i == $#modes + 1 )); then
printf '%3$s\0\e[%2$sm%3$q\e[0m%1$s\n' "${(@0)${(@)modes:^files}}"
break
elif (( i != 1 )); then
printf '%3$s\0\e[%2$sm%3$q\e[0m%1$s\n' "${(@0)${(@)modes[1,i-1]:^files}}"
shift $((i-1)) modes files
fi
file=$files[1]
shift modes files
if ! zstat -L -A link +link -- $file; then
printf '%1$s\0\e['$or'm%1$q\e[0m\n' $file
elif ! zstat -A link_mode +mode -- $file; then
printf '%1$s\0\e['$or'm%1$q\e[0m -> \e['$or'm%2$q\e[0m\n' $file $link
elif (( ln_target )); then
printf '%1$s\0\e[%4$sm%1$q\e[0m -> \e[%4$sm%2$q\e[0m%3$s\n' \
$file $link "${(@0)${_z4h_mode_codes[$((link_mode & 64075))]:-$nil}}"
else
printf '%1$s\0\e['$ln'm%1$q\e[0m -> \e[%4$sm%2$q\e[0m%3$s\n' \
$file $link "${(@0)${_z4h_mode_codes[$((link_mode & 64075))]:-$nil}}"
fi
done
fi
done

15
fn/-z4h-prompt-length Normal file
View file

@ -0,0 +1,15 @@
#!/usr/bin/env zsh
local -i COLUMNS=1024
local -i x y=${#1} m
if (( y )); then
while (( ${${(%):-$1%$y(l.1.0)}[-1]} )); do
x=y
(( y *= 2 ))
done
while (( y > x + 1 )); do
(( m = x + (y - x) / 2 ))
(( ${${(%):-$1%$m(l.x.y)}[-1]} = m ))
done
fi
typeset -g REPLY=$x

9
fn/-z4h-read-dir-history Normal file
View file

@ -0,0 +1,9 @@
#!/usr/bin/env zsh
local content
local file=$Z4H/stickycache/dir-history-$EUID
if [[ -r $file ]] && content=$(<$file); then
typeset -ga _z4h_dir_history=(${(f)content})
else
typeset -ga _z4h_dir_history=()
fi

13
fn/-z4h-redraw-buffer Normal file
View file

@ -0,0 +1,13 @@
#!/usr/bin/env zsh
if (( ${+_z4h_redraw_fd} )); then
zle -F "$_z4h_redraw_fd"
exec {_z4h_redraw_fd}>&-
unset _z4h_redraw_fd
fi
if [[ -v region_highlight &&
( ${LASTWIDGET-} != accept-line || ${WIDGET-} != zle-line-pre-redraw ) ]]; then
_zsh_highlight
-z4h-autosuggest-fetch
fi

18
fn/-z4h-redraw-prompt Normal file
View file

@ -0,0 +1,18 @@
#!/usr/bin/env zsh
{
-z4h-cursor-hide
local f
for f in chpwd "${chpwd_functions[@]}" precmd "${(@)precmd_functions:#-z4h-direnv-hook}"; do
[[ "${+functions[$f]}" == 0 ]] || "$f" &>/dev/null || true
done
if (( _z4h_use[zsh-syntax-highlighting] )); then
typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER=
typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=0
fi
zle .reset-prompt
(( ${1:-0} )) || zle -R
} always {
(( ${1:-0} )) || -z4h-cursor-show
-z4h-update-dir-history
}

40
fn/-z4h-replace-buf Normal file
View file

@ -0,0 +1,40 @@
#!/usr/bin/env zsh
#
# Usage: -z4h-replace-buf START END REPLACEMENT
#
# Replaces BUFFER[START,END] with REPLACEMENT while keeping the cursor
# pointing to the same content as before.
emulate -L zsh
local -i start=$1 end=$2
local orig_word=$BUFFER[start,end] new_word=$3
local reply
if (( $#orig_word * $#new_word <= 10000 )); then
-z4h-string-diff "$orig_word" "$new_word"
else
reply=("$orig_word" "$new_word")
fi
local -i orig_cur='CURSOR - start + 1' cur new_cur
local src dst
for src dst in "${reply[@]}"; do
(( cur += $#src ))
if (( cur < orig_cur )); then
(( new_cur += $#dst - $#src ))
elif (( cur == orig_cur )); then
(( cur == $#orig_word )) && break
(( new_cur += $#dst - $#src ))
else
if (( orig_cur - (cur - $#src) > $#dst )); then
(( new_cur -= orig_cur - (cur - $#src) - $#dst ))
fi
break
fi
done
(( new_cur += CURSOR ))
BUFFER[start,end]=$new_word
(( CURSOR = new_cur ))
return 0

14
fn/-z4h-restore-screen Normal file
View file

@ -0,0 +1,14 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
[[ -v _z4h_tty_fd ]] || return
if [[ -n $_Z4H_TMUX ]]; then
(( ${+_z4h_saved_screen} )) || return
print -rnu $_z4h_tty_fd -- "$_z4h_saved_screen"
elif [[ -n $Z4H_SSH && -n $_Z4H_SSH_MARKER ]]; then
printf '\001z4h.%s%s' "$_Z4H_SSH_MARKER" 'restore-screen ' >&$_z4h_tty_fd
else
return 1
fi

42
fn/-z4h-run-process-tree Normal file
View file

@ -0,0 +1,42 @@
#!/usr/bin/env zsh
#
# Based on https://github.com/romkatv/run-process-tree but without
# the preservation of options, patterns, etc.
emulate -L zsh || return
setopt monitor traps_async pipe_fail no_unset no_bg_nice || return
zmodload zsh/system || return
local stdout REPLY
exec {stdout}>&1 || return
{
{
local -i pipe
local sig=(EXIT HUP ILL INT PIPE QUIT TERM ZERR)
local trap=(trap "trap - $sig; kill -- -$sysparams[pid]" $sig)
exec {pipe}>&1 1>&$stdout || return
$trap
{
$trap
while command sleep 1 && print -u $pipe .; do; done
} 2>/dev/null &
local -i watchdog=$!
{
trap - ZERR
exec {pipe}>&- || return
() { "$@" } "$@"
} &
local -i ret
wait $! || ret=$?
trap "exit $ret" TERM
kill $watchdog || return
wait $watchdog || return
return ret
} | while read; do; done || return
} always {
exec {stdout}>&-
}

View file

@ -0,0 +1,12 @@
#!/usr/bin/env zsh
() {
emulate -L zsh -o extended_glob
[[ $_z4h_word_prefix != *('$'|'\') ]] || return
if [[ $_z4h_word_prefix == *[A-Z]* ]]; then
[[ -z ${(@)*:#$_z4h_word_prefix*} ]] || return
else
[[ -z ${(@)*:#(#i)$_z4h_word_prefix*} ]] || return
fi
} "$@" || _z4h_word_prefix=
_z4h_word_prefix=${_z4h_word_prefix// /\\ }

13
fn/-z4h-save-screen Normal file
View file

@ -0,0 +1,13 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
if [[ -n $_Z4H_TMUX ]]; then
local pane
pane="$(TMUX=$_Z4H_TMUX TMUX_PANE=$_Z4H_TMUX_PANE $_Z4H_TMUX_CMD capture-pane -p -e && print -n x)" || return
typeset -g _z4h_saved_screen=$'\e[0m\e[H'${${pane//$'\n'/$'\e[49m\e[K\r\n'}%$'\r\nx'}
elif [[ -n $Z4H_SSH && -n $_Z4H_SSH_MARKER && -v _z4h_tty_fd ]]; then
printf '\001z4h.%s%s' "$_Z4H_SSH_MARKER" 'save-screen ' >&$_z4h_tty_fd
else
return 1
fi

57
fn/-z4h-set-list-colors Normal file
View file

@ -0,0 +1,57 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
setopt octalzeroes
local curcontext=$1
local list_types=$2
local -a list_colors
zstyle -a :completion:$curcontext:default list-colors list_colors || return
(( $#list_colors )) || return
if [[ ${list_types}${(pj:\0:)list_colors} != $_z4h_last_list_colors ]]; then
# This takes ~20ms. Can be easily optimized.
typeset -g _z4h_last_list_colors=${list_types}${(pj:\0:)list_colors}
typeset -gA _z4h_name_colors=(${(@s:=:)${(@s.:.)list_colors}:#[[:alpha:]][[:alpha:]]=*})
typeset -gA _z4h_mode_colors=(${(@Ms:=:)${(@s.:.)list_colors}:#[[:alpha:]][[:alpha:]]=*})
typeset -gA _z4h_mode_codes=()
() {
local -i8 a b c d
local -a codes
local suf
for a in 0140000 0120000 0100000 0060000 0040000 0020000 0010000; do
for b in 0 02000 04000 06000; do
for c in 0 01000 00002 01002; do
for d in 0 0001 0010 0011 0100 0101 0110 0111; do
suf=
codes=()
if (( a == 0120000 )); then
_z4h_mode_codes[$((a|b|c|d))]=$'@\0.'
continue
fi
if (( a == 0100000 )); then
(( d )) && suf='*'
else
if (( a == 0140000 )); then codes+=($_z4h_mode_colors[so]); suf='=';
elif (( a == 0060000 )); then codes+=($_z4h_mode_colors[bd]); suf='' ;
elif (( a == 0040000 )); then codes+=($_z4h_mode_colors[di]); suf='/';
elif (( a == 0020000 )); then codes+=($_z4h_mode_colors[cd]); suf='' ;
elif (( a == 0010000 )); then codes+=($_z4h_mode_colors[pi]); suf='|'; fi
if (( c == 01000 )); then codes+=($_z4h_mode_colors[st]);
elif (( c == 00002 )); then codes+=($_z4h_mode_colors[ow]);
elif (( c == 01002 )); then codes+=($_z4h_mode_colors[tw]); fi
fi
(( b & 04000 )) && codes+=($modecolors[su])
(( b & 02000 )) && codes+=($modecolors[sg])
(( $#codes || a != 0100000 || !d )) || codes+=($_z4h_mode_colors[ex])
(( list_types )) || suf=
_z4h_mode_codes[$((a|b|c|d))]=$suf$'\0'${(j:;:)codes}
done
done
done
done
}
fi
return 0

14
fn/-z4h-set-term-title Normal file
View file

@ -0,0 +1,14 @@
#!/usr/bin/env zsh
emulate -L zsh -o no_prompt_bang -o prompt_subst -o prompt_percent
local title=$1
shift
print -Prnv title -- $title
printf -v title '\e]0;%s\a' "${(V)title}"
if [[ -t 1 ]]; then
print -rn -- $title
elif [[ -v _z4h_tty_fd ]]; then
print -rnu $_z4h_tty_fd -- $title
fi

27
fn/-z4h-show-dots Normal file
View file

@ -0,0 +1,27 @@
#!/usr/bin/env zsh
local -i cursor=CURSOR
local postdisplay=$POSTDISPLAY
local buffer=$BUFFER
BUFFER=$1
POSTDISPLAY=..
if [[ -n $ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE ]]; then
local style=$ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE
elif (( terminfo[colors] >= 256 )); then
local style='fg=244'
else
local style='fg=black,bold'
fi
region_highlight+=("$#BUFFER $(($#BUFFER + $#POSTDISPLAY)) $style")
typeset -gi CURSOR='_z4h_cursor_max()'
-z4h-cursor-hide
zle -R
BUFFER=$buffer
CURSOR=cursor
POSTDISPLAY=$postdisplay
region_highlight[-1]=()

18
fn/-z4h-ssh-maybe-update Normal file
View file

@ -0,0 +1,18 @@
#!/usr/bin/env zsh
# Requires: [[ $Z4H_SSH == <1->:* ]]
eval "$_z4h_opt"
local min_version=${Z4H_SSH%%:*}
local got_version
got_version=${$(<$Z4H/zsh4humans/version)%$'\r'} &&
[[ $got_version == <-> ]] &&
(( got_version >= min_version )) &&
return
print -Pru2 -- "%F{3}z4h%f: %Binitiating update%b (cached version too old)"
Z4H_SSH=0:${Z4H_SSH#*:}
-z4h-cmd-update

25
fn/-z4h-start-ssh-agent Normal file
View file

@ -0,0 +1,25 @@
#!/usr/bin/env zsh
[[ -v commands[ssh-agent] ]] || return 0
function -z4h-ssh-agent-running() {
[[ -w $SSH_AUTH_SOCK ]] && builtin kill -0 -- $SSH_AGENT_PID 2>/dev/null
}
{
-z4h-ssh-agent-running && return
unset SSH_AGENT_PID SSH_AUTH_SOCK
local env_file=$Z4H/stickycache/ssh-agent-$EUID
[[ -r $env_file ]] && builtin source $env_file >/dev/null && -z4h-ssh-agent-running && return
local tmp=$env_file.tmp.$$
local -a args
zstyle -a :z4h:ssh-agent: extra-args args
command ssh-agent -s $args >$tmp || return
builtin source $tmp >/dev/null || return
-z4h-ssh-agent-running || return
zf_mv -f -- $tmp $env_file || return
} always {
builtin unfunction -- -z4h-ssh-agent-running
}

84
fn/-z4h-string-diff Normal file
View file

@ -0,0 +1,84 @@
#!/usr/bin/env zsh
#
# Finds the difference between two strings using Levenshtein distance.
# Sets array reply to an even number of elements. The concatenation of odd
# elements (one-based) is equal to the first string; even elements -- second
# string.
#
# Example:
#
# % -z4h-string-diff 'sunday!' 'saturday'
# % printf '%-5s => %s\n' ${(qq)reply}
# 's' => 's'
# '' => 'at'
# 'u' => 'u'
# 'n' => 'r'
# 'day' => 'day'
# '!' => ''
#
# Time and memory complexity in a decent language would be O($#1 * $#2). In Zsh
# it's even worse than that. It's a good idea to check the value of $#1 * $#2
# before invoking this function. It takes about 0.2s if this multiple is 10000.
#
# Note: This is Wagner-Fischer algorithm.
emulate -L zsh -o no_unset -o ksh_arrays
local s=$1 t=$2
local -i m=$#s n=$#t w=$(($#t + 1)) i j p q r x y z e
local -a d=({1..$(((m + 1) * (n + 1)))})
d=(${d[@]//*/0})
local -a b=(${d[@]})
for ((i = 1; i <= m; ++i)); do
(( d[i*w] = i, b[i*w] = 1 ))
done
for ((j = 1; j <= n; ++j)); do
(( d[j] = j, b[j] = 2 ))
done
for ((i = 1; i <= m; ++i)); do
(( p = ${d[(i-1)*w]} ))
(( q = ${d[i*w]} ))
for ((j = 1; j <= n; ++j)); do
if [[ ${s[i-1]} == ${t[j-1]} ]]; then
(( z = p, e = 3 ))
else
(( z = p + 1, e = 7 ))
fi
(( y = q + 1 ))
# Half the time is spent executing the next line.
(( x = (p = ${d[(i-1)*w+j]}) + 1 ))
if (( x <= y )); then
if (( x <= z )); then
(( d[i*w+j] = q = x, b[i*w+j] = 1 ))
else
(( d[i*w+j] = q = z, b[i*w+j] = e ))
fi
elif (( y <= z )); then
(( d[i*w+j] = q = y, b[i*w+j] = 2 ))
else
(( d[i*w+j] = q = z, b[i*w+j] = e ))
fi
done
done
local -i k kind=-1 s1=m s2=m t1=n t2=n
local res=()
(( i = m, j = n ))
while (( i || j )); do
if (( (k = b[i*w+j]) != kind )); then
if (( s2 > s1 || t2 > t1 )); then
res+=("${t:$t1:$((t2-t1))}" "${s:$s1:$((s2-s1))}")
(( s1 = s2 = i, t1 = t2 = j ))
fi
(( kind = k ))
fi
(( i -= k & 1, s1 -= k & 1, j -= (k >> 1 ) & 1, t1 -= (k >> 1 ) & 1 ))
done
if (( s2 > s1 || t2 > t1 )); then
res+=("${t:$t1:$((t2-t1))}" "${s:$s1:$((s2-s1))}")
fi
typeset -g reply=("${(Oa)res[@]}")

12
fn/-z4h-tmux-bypass Normal file
View file

@ -0,0 +1,12 @@
#!/usr/bin/env zsh
local x
builtin printf -v x "$@"
(( _z4h_can_save_restore_screen )) && x+=$'\ePtmux;'${x//$'\e'/$'\e\e'}$'\e\\'
if [[ -t 1 ]]; then
print -rn -- "$x"
elif [[ -v _z4h_tty_fd ]]; then
print -rnu $_z4h_tty_fd -- "$x"
fi

View file

@ -0,0 +1,52 @@
#!/usr/bin/env zsh
if (( ${+_z4h_dir_hist_fd} )); then
zle -F "$_z4h_dir_hist_fd"
exec {_z4h_dir_hist_fd}>&-
unset _z4h_dir_hist_fd
fi
local dir
zstyle -s :z4h:dir-history: cwd dir || dir=${(%):-%~}
[[ -z $dir || $dir == ${_z4h_last_dir-} ]] && return
eval "$_z4h_opt"
typeset -g _z4h_last_dir=$dir
[[ $dir != ('~'|/)* ]] && return
-z4h-read-dir-history || return
if (( ! $#dirstack && (DIRSTACKSIZE || ! $+DIRSTACKSIZE) )); then
local d stack=()
for d in $_z4h_dir_history; do
{
if [[ ($#stack -ne 0 || $d != $dir) ]]; then
d=${~d}
if [[ -d ${d::=${(g:oce:)d}} ]]; then
stack+=($d)
(( $+DIRSTACKSIZE && $#stack >= DIRSTACKSIZE - 1 )) && break
fi
fi
} always {
TRY_BLOCK_ERROR=0
}
done 2>/dev/null
dirstack=($stack)
fi
local -i pos=$_z4h_dir_history[(ie)$dir]
_z4h_dir_history[pos]=()
_z4h_dir_history[1,0]=($dir)
local max_size
zstyle -s :z4h:dir-history: max-size max_size
if [[ $max_size != -<-> ]]; then
[[ $max_size == <-> ]] || max_size=10000
local -i drop=$(($#_z4h_dir_history - max_size))
if (( drop > 0 )); then
_z4h_dir_history[-drop,-1]=()
fi
fi
-z4h-write-dir-history

26
fn/-z4h-vte-osc7 Normal file
View file

@ -0,0 +1,26 @@
#!/usr/bin/env zsh
#
# The original __vte_osc7 looks like this:
#
# __vte_osc7 () {
# printf "\033]7;file://%s%s\033\\" "${HOSTNAME}" "$(/usr/libexec/vte-urlencode-cwd)"
# }
#
# It runs on precmd.
emulate -L zsh -o no_multi_byte -o extended_glob
if [[ $PWD == /* && $PWD -ef . ]]; then
local cwd=$PWD
else
local cwd=${${:-.}:a}
fi
local host=$HOST
[[ -n $cwd && $host != *$'\e'* ]] || return
if [[ $cwd != $_z4h_vte_last_cwd ]]; then
local MATCH MBEGIN MEND
typeset -g _z4h_vte_last_encoded_cwd=${cwd//(#m)[^a-zA-Z0-9"\/:_.-!'()~"]/%${(l:2::0:)$(([##16]#MATCH))}}
fi
-z4h-tmux-bypass '\e]7;file://%s%s\e\' "$host" "$_z4h_vte_last_encoded_cwd"

96
fn/-z4h-welcome Normal file
View file

@ -0,0 +1,96 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
add-zsh-hook -d -- precmd -z4h-welcome
[[ -e $Z4H/welcome && -e $POWERLEVEL9K_CONFIG_FILE ]] || return 0
local backup_dir
backup_dir=$(<$Z4H/welcome) || return
zf_rm -f -- $Z4H/welcome
() {
[[ $POWERLEVEL9K_CONFIG_FILE != ~/.p10k.zsh ]] && return
[[ $POWERLEVEL9K_ICON_PADDING == none ]] || return
[[ $POWERLEVEL9K_MODE == nerdfont-complete ]] && return
[[ $POWERLEVEL9K_MODE == ascii ]] || return
local cfg
cfg=$(<~/.p10k.zsh) || return
[[ $cfg == *'nerdfont-complete + powerline'* ]] || return
}
local -i suggest_font=$?
local bash_rcs=(~/.profile(N) ~/.bash_profile(N) ~/.bashrc(N))
if [[ ! -t 2 ]]; then
(( $+functions[p10k] )) && p10k clear-instant-prompt
fi
{
print
-z4h-flowing -i0 -- %F{3}Zsh For Humans%f installed successfully!
print
-z4h-flowing -i0 -- Next steps:
print
-z4h-flowing -i4 -- ' - Your' new personal Zsh config is in %U~/.zshrc%u. Edit this file to \
export environment variables, define aliases, etc. There are plenty of \
examples and comments to get you started.
print
if [[ -e $backup_dir && $backup_dir == ~/zsh-backup/[0-9.-]## ]]; then
-z4h-flowing -i4 -- ' - Your' previous Zsh config files are in \
%U~/zsh-backup/${backup_dir:t}%u. They are no longer read when you start \
%2Fzsh%f. You might want to copy bits and pieces from them to the new \
%U~/.zshrc%u.
print
fi
if [[ /$_z4h_orig_shell == */bash ]] && (( $+commands[bash] && $#bash_rcs )); then
-z4h-flowing -i4 -- ' - 'Zsh does not read startup files used by Bash. You might want to copy \
bits and pieces from them to %U~/.zshrc%u. Here are the files:
print
local rc
for rc in $bash_rcs; do
-z4h-flowing -i4 -- ' '%U~/${${rc:t}//\%/%%}%u
done
print
fi
if [[ -n $TMUX && $TERM == screen && ! -e ~/.tmux.conf ]]; then
-z4h-flowing -i4 -- ' - You' are using %2Ftmux%f but don\'t have %U~/.tmux.conf%u. This is \
limiting the number of colors your terminal can display. You might want \
to create this file and restart Zsh to enable more colors:
print
-z4h-flowing -i4 -- " %3F>%f%U~/.tmux.conf%u %3F<<<'set -g default-terminal screen-256color'%f"
-z4h-flowing -i4 -- ' TERM=screen-256color %U%2Fexec%u%f %2Fzsh%f'
print
-z4h-flowing -i4 -- ' You' will see %4FPowerlevel10k%f wizard once again, this time with \
more choices.
print
fi
if (( suggest_font )); then
-z4h-flowing -i4 -- ' - Install' the recommended font from %4FPowerlevel10k%f to enable \
additional glyphs in the terminal:
print
local url=https://github.com/romkatv/powerlevel10k/blob/master/font.md
url=${${url//\%/%%}//\\/\\\\}
if (( _p9k_term_has_href )); then
url='%{\e]8;;'$url'\a%}'$url'%{\e]8;;\a%}'
fi
-z4h-flowing -i4 -- ' '$url
print
-z4h-flowing -i4 -- ' Then' choose a new prompt style through the %4FPowerlevel10k%f wizard:
print
-z4h-flowing -i4 -- ' '%2Fp10k%f %Bconfigure%b
print
else
-z4h-flowing -i4 -- ' - Prompt' config from %4FPowerlevel10k%f is in \
%U~/${${POWERLEVEL9K_CONFIG_FILE:t}//\%/%%}%u. To customize prompt, you \
can either manually edit this file or generate a new version through the \
wizard:
print
-z4h-flowing -i4 -- ' '%2Fp10k%f %Bconfigure%b
print
fi
-z4h-flowing -i0 -- Enjoy %F{3}Zsh For Humans%f!
print
} >&2

View file

@ -0,0 +1,13 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
local last=$LASTWIDGET
zle .set-local-history -n $1
shift
{
() { local -h LASTWIDGET=$last; "$@" } "$@"
} always {
zle .set-local-history -n 0
}
return 0

View file

@ -0,0 +1,6 @@
#!/usr/bin/env zsh
local file=$Z4H/stickycache/dir-history-$EUID
local tmp=$file.tmp.$$
print -rC1 -- $_z4h_dir_history >$tmp
zf_mv -f -- $tmp $file

26
fn/-z4h-zle-line-finish Normal file
View file

@ -0,0 +1,26 @@
#!/usr/bin/env zsh
local -i ret
if [[ -v widgets[-z4h-orig-zle-line-finish] ]]; then
zle -- -z4h-orig-zle-line-finish "$@" || ret=$?
fi
if [[ -v _z4h_redraw_fd ]]; then
zle -F "$_z4h_redraw_fd"
exec {_z4h_redraw_fd}>&-
unset _z4h_redraw_fd
fi
if [[ $BUFFER == *' ' ]] &&
! zstyle -t :z4h:history preserve-trailing-whitespace &&
-z4h-is-valid-list "$PREBUFFER$BUFFER"; then
BUFFER=${BUFFER%% #}
fi
unset POSTDISPLAY _z4h_autosuggest_buffer _z4h_autosuggestion
if [[ -v region_highlight ]]; then
_zsh_highlight
fi
return ret

39
fn/-z4h-zle-line-init Normal file
View file

@ -0,0 +1,39 @@
#!/usr/bin/env zsh
local -i ret
if [[ ${CONTEXT-} != start || -v _z4h_transient_rprompt ]]; then
if [[ ${CONTEXT} == start ]]; then
unsetopt transient_rprompt
unset _z4h_transient_rprompt
elif [[ ! -o transient_rprompt ]]; then
setopt transient_rprompt
typeset -g _z4h_transient_rprompt=
fi
fi
if (( ${+widgets[-z4h-orig-zle-line-init]} )); then
zle -- -z4h-orig-zle-line-init "$@" || ret=$?
fi
if (( ${+_z4h_redraw_fd} )); then
zle -F "$_z4h_redraw_fd"
exec {_z4h_redraw_fd}>&-
unset _z4h_redraw_fd
fi
unset POSTDISPLAY _z4h_autosuggest_buffer _z4h_autosuggestion _zsh_highlight__highlighter_${^ZSH_HIGHLIGHT_HIGHLIGHTERS}_cache
typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER=
typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=CURSOR
region_highlight=()
if [[ ${(%):-%~} != ${_z4h_last_dir-} && ! -v _z4h_dir_hist_fd ]]; then
typeset -gi _z4h_dir_hist_fd
if sysopen -o cloexec -ru _z4h_dir_hist_fd /dev/null; then
zle -F $_z4h_dir_hist_fd -z4h-update-dir-history
else
unset _z4h_dir_hist_fd
fi
fi
return ret

View file

@ -0,0 +1,40 @@
#!/usr/bin/env zsh
local -i ret
if (( ${+widgets[-z4h-orig-zle-line-pre-redraw]} )); then
zle -- -z4h-orig-zle-line-pre-redraw "$@" || ret=$?
fi
if (( ${+_z4h_substring_search_highlight} )) &&
[[ ${_history_substring_search_cursor-} != $CURSOR ||
${_history_substring_search_result-} != $BUFFER ]]; then
typeset -g _history_substring_search_result=
typeset -g _history_substring_search_query_highlight=
unset _z4h_substring_search_highlight _history_substring_search_cursor
fi
if (( PENDING || KEYS_QUEUED_COUNT )); then
if (( ! ${+_z4h_redraw_fd} )); then
typeset -gi _z4h_redraw_fd
if sysopen -o cloexec -ru _z4h_redraw_fd /dev/null; then
zle -F $_z4h_redraw_fd -z4h-redraw-buffer
else
unset _z4h_redraw_fd
fi
fi
if [[ -n "${POSTDISPLAY-}" &&
"${#BUFFER}" -ne "${#_z4h_autosuggest_buffer}" &&
-v region_highlight ]]; then
POSTDISPLAY=${_z4h_autosuggestion:${#BUFFER}}
if [[ -n "$POSTDISPLAY" ]]; then
region_highlight[-1]="${#BUFFER} $((${#BUFFER} + ${#POSTDISPLAY})) $ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE"
else
unset POSTDISPLAY _z4h_autosuggest_buffer _z4h_autosuggestion
fi
fi
else
-z4h-redraw-buffer
fi
return ret

9
fn/_z4h_cursor_max Normal file
View file

@ -0,0 +1,9 @@
#!/usr/bin/env zsh
eval "$_z4h_opt"
if [[ $KEYMAP == vicmd && -n ${BUFFER##*$'\n'} ]]; then
return $(( ${#BUFFER} - 1 ))
else
return ${#BUFFER}
fi

Some files were not shown because too many files have changed in this diff Show more