From ac5294ae7aaa8668f0a74e32c1786a25adbbb80f Mon Sep 17 00:00:00 2001 From: Adam Hovorka Date: Sun, 6 Aug 2017 16:12:32 -0600 Subject: Add ZSH config based on changs/slim-zsh --- base/.zsh/aliases.zsh | 16 + base/.zsh/async | 493 ++++++++++++++ base/.zsh/colors.zsh | 3 + base/.zsh/completion.zsh | 81 +++ base/.zsh/correction.zsh | 7 + base/.zsh/fancy-man.zsh | 7 + base/.zsh/fasd.zsh | 3 + base/.zsh/fast-syntax-highlighting/fast-highlight | 715 +++++++++++++++++++++ .../fast-syntax-highlighting.plugin.zsh | 272 ++++++++ base/.zsh/functions.zsh | 10 + base/.zsh/history.zsh | 15 + base/.zsh/prompt.zsh | 2 + base/.zsh/prompt_pure_setup | 385 +++++++++++ base/.zsh/stack.zsh | 3 + 14 files changed, 2012 insertions(+) create mode 100644 base/.zsh/aliases.zsh create mode 100644 base/.zsh/async create mode 100644 base/.zsh/colors.zsh create mode 100644 base/.zsh/completion.zsh create mode 100644 base/.zsh/correction.zsh create mode 100644 base/.zsh/fancy-man.zsh create mode 100644 base/.zsh/fasd.zsh create mode 100644 base/.zsh/fast-syntax-highlighting/fast-highlight create mode 100644 base/.zsh/fast-syntax-highlighting/fast-syntax-highlighting.plugin.zsh create mode 100644 base/.zsh/functions.zsh create mode 100644 base/.zsh/history.zsh create mode 100644 base/.zsh/prompt.zsh create mode 100644 base/.zsh/prompt_pure_setup create mode 100644 base/.zsh/stack.zsh (limited to 'base/.zsh') diff --git a/base/.zsh/aliases.zsh b/base/.zsh/aliases.zsh new file mode 100644 index 0000000..9f1d2a1 --- /dev/null +++ b/base/.zsh/aliases.zsh @@ -0,0 +1,16 @@ +# UTILITY + +alias ls="ls --color=auto" +alias less='less -R' +alias grep='grep --color=auto' +alias ..='cd ../' + +# GIT + +alias gd='git diff' +alias gco='git checkout' +alias gs='git status' +alias gl='git pull' +alias gp='git push' +alias gpp='git pull; git push' +alias gwc='git whatchanged -p --abbrev-commit --pretty=medium' diff --git a/base/.zsh/async b/base/.zsh/async new file mode 100644 index 0000000..d11a99a --- /dev/null +++ b/base/.zsh/async @@ -0,0 +1,493 @@ +#!/usr/bin/env zsh + +# +# zsh-async +# +# version: 1.5.0 +# author: Mathias Fredriksson +# url: https://github.com/mafredri/zsh-async +# + +# Produce debug output from zsh-async when set to 1. +ASYNC_DEBUG=${ASYNC_DEBUG:-0} + +# Wrapper for jobs executed by the async worker, gives output in parseable format with execution time +_async_job() { + # Disable xtrace as it would mangle the output. + setopt localoptions noxtrace + + # Store start time as double precision (+E disables scientific notation) + float -F duration=$EPOCHREALTIME + + # Run the command and capture both stdout (`eval`) and stderr (`cat`) in + # separate subshells. When the command is complete, we grab write lock + # (mutex token) and output everything except stderr inside the command + # block, after the command block has completed, the stdin for `cat` is + # closed, causing stderr to be appended with a $'\0' at the end to mark the + # end of output from this job. + local stdout stderr ret tok + { + stdout=$(eval "$@") + ret=$? + duration=$(( EPOCHREALTIME - duration )) # Calculate duration. + + # Grab mutex lock, stalls until token is available. + read -r -k 1 -p tok || exit 1 + + # Return output ( ). + print -r -n - ${(q)1} $ret ${(q)stdout} $duration + } 2> >(stderr=$(cat) && print -r -n - " "${(q)stderr}$'\0') + + # Unlock mutex by inserting a token. + print -n -p $tok +} + +# The background worker manages all tasks and runs them without interfering with other processes +_async_worker() { + # Reset all options to defaults inside async worker. + emulate -R zsh + + # Make sure monitor is unset to avoid printing the + # pids of child processes. + unsetopt monitor + + # Redirect stderr to `/dev/null` in case unforseen errors produced by the + # worker. For example: `fork failed: resource temporarily unavailable`. + # Some older versions of zsh might also print malloc errors (know to happen + # on at least zsh 5.0.2 and 5.0.8) likely due to kill signals. + exec 2>/dev/null + + # When a zpty is deleted (using -d) all the zpty instances created before + # the one being deleted receive a SIGHUP, unless we catch it, the async + # worker would simply exit (stop working) even though visible in the list + # of zpty's (zpty -L). + TRAPHUP() { + return 0 # Return 0, indicating signal was handled. + } + + local -A storage + local unique=0 + local notify_parent=0 + local parent_pid=0 + local coproc_pid=0 + local processing=0 + + local -a zsh_hooks zsh_hook_functions + zsh_hooks=(chpwd periodic precmd preexec zshexit zshaddhistory) + zsh_hook_functions=(${^zsh_hooks}_functions) + unfunction $zsh_hooks &>/dev/null # Deactivate all zsh hooks inside the worker. + unset $zsh_hook_functions # And hooks with registered functions. + unset zsh_hooks zsh_hook_functions # Cleanup. + + child_exit() { + local -a pids + pids=(${${(v)jobstates##*:*:}%\=*}) + + # If coproc (cat) is the only child running, we close it to avoid + # leaving it running indefinitely and cluttering the process tree. + if (( ! processing )) && [[ $#pids = 1 ]] && [[ $coproc_pid = $pids[1] ]]; then + coproc : + coproc_pid=0 + fi + + # On older version of zsh (pre 5.2) we notify the parent through a + # SIGWINCH signal because `zpty` did not return a file descriptor (fd) + # prior to that. + if (( notify_parent )); then + # We use SIGWINCH for compatibility with older versions of zsh + # (pre 5.1.1) where other signals (INFO, ALRM, USR1, etc.) could + # cause a deadlock in the shell under certain circumstances. + kill -WINCH $parent_pid + fi + } + + # Register a SIGCHLD trap to handle the completion of child processes. + trap child_exit CHLD + + # Process option parameters passed to worker + while getopts "np:u" opt; do + case $opt in + n) notify_parent=1;; + p) parent_pid=$OPTARG;; + u) unique=1;; + esac + done + + killjobs() { + local tok + local -a pids + pids=(${${(v)jobstates##*:*:}%\=*}) + + # No need to send SIGHUP if no jobs are running. + (( $#pids == 0 )) && continue + (( $#pids == 1 )) && [[ $coproc_pid = $pids[1] ]] && continue + + # Grab lock to prevent half-written output in case a child + # process is in the middle of writing to stdin during kill. + (( coproc_pid )) && read -r -k 1 -p tok + + kill -HUP -$$ # Send to entire process group. + coproc : # Quit coproc. + coproc_pid=0 # Reset pid. + } + + local request + local -a cmd + while :; do + # Wait for jobs sent by async_job. + read -r -d $'\0' request || { + # Since we handle SIGHUP above (and thus do not know when `zpty -d`) + # occurs, a failure to read probably indicates that stdin has + # closed. This is why we propagate the signal to all children and + # exit manually. + kill -HUP -$$ # Send SIGHUP to all jobs. + exit 0 + } + + # Check for non-job commands sent to worker + case $request in + _unset_trap) notify_parent=0; continue;; + _killjobs) killjobs; continue;; + esac + + # Parse the request using shell parsing (z) to allow commands + # to be parsed from single strings and multi-args alike. + cmd=("${(z)request}") + + # Name of the job (first argument). + local job=$cmd[1] + + # If worker should perform unique jobs + if (( unique )); then + # Check if a previous job is still running, if yes, let it finnish + for pid in ${${(v)jobstates##*:*:}%\=*}; do + if [[ ${storage[$job]} == $pid ]]; then + continue 2 + fi + done + fi + + # Guard against closing coproc from trap before command has started. + processing=1 + + # Because we close the coproc after the last job has completed, we must + # recreate it when there are no other jobs running. + if (( ! coproc_pid )); then + # Use coproc as a mutex for synchronized output between children. + coproc cat + coproc_pid="$!" + # Insert token into coproc + print -n -p "t" + fi + + # Run job in background, completed jobs are printed to stdout. + _async_job $cmd & + # Store pid because zsh job manager is extremely unflexible (show jobname as non-unique '$job')... + storage[$job]="$!" + + processing=0 # Disable guard. + done +} + +# +# Get results from finnished jobs and pass it to the to callback function. This is the only way to reliably return the +# job name, return code, output and execution time and with minimal effort. +# +# usage: +# async_process_results +# +# callback_function is called with the following parameters: +# $1 = job name, e.g. the function passed to async_job +# $2 = return code +# $3 = resulting stdout from execution +# $4 = execution time, floating point e.g. 2.05 seconds +# $5 = resulting stderr from execution +# +async_process_results() { + setopt localoptions noshwordsplit + + local worker=$1 + local callback=$2 + local caller=$3 + local -a items + local null=$'\0' data + integer -l len pos num_processed + + typeset -gA ASYNC_PROCESS_BUFFER + + # Read output from zpty and parse it if available. + while zpty -r -t $worker data 2>/dev/null; do + ASYNC_PROCESS_BUFFER[$worker]+=$data + len=${#ASYNC_PROCESS_BUFFER[$worker]} + pos=${ASYNC_PROCESS_BUFFER[$worker][(i)$null]} # Get index of NULL-character (delimiter). + + # Keep going until we find a NULL-character. + if (( ! len )) || (( pos > len )); then + continue + fi + + while (( pos <= len )); do + # Take the content from the beginning, until the NULL-character and + # perform shell parsing (z) and unquoting (Q) as an array (@). + items=("${(@Q)${(z)ASYNC_PROCESS_BUFFER[$worker][1,$pos-1]}}") + + # Remove the extracted items from the buffer. + ASYNC_PROCESS_BUFFER[$worker]=${ASYNC_PROCESS_BUFFER[$worker][$pos+1,$len]} + + if (( $#items == 5 )); then + $callback "${(@)items}" # Send all parsed items to the callback. + else + # In case of corrupt data, invoke callback with *async* as job + # name, non-zero exit status and an error message on stderr. + $callback "async" 1 "" 0 "$0:$LINENO: error: bad format, got ${#items} items (${(@q)items})" + fi + + (( num_processed++ )) + + len=${#ASYNC_PROCESS_BUFFER[$worker]} + if (( len > 1 )); then + pos=${ASYNC_PROCESS_BUFFER[$worker][(i)$null]} # Get index of NULL-character (delimiter). + fi + done + done + + (( num_processed )) && return 0 + + # Avoid printing exit value when `setopt printexitvalue` is active.` + [[ $caller = trap || $caller = watcher ]] && return 0 + + # No results were processed + return 1 +} + +# Watch worker for output +_async_zle_watcher() { + setopt localoptions noshwordsplit + typeset -gA ASYNC_PTYS ASYNC_CALLBACKS + local worker=$ASYNC_PTYS[$1] + local callback=$ASYNC_CALLBACKS[$worker] + + if [[ -n $callback ]]; then + async_process_results $worker $callback watcher + fi +} + +# +# Start a new asynchronous job on specified worker, assumes the worker is running. +# +# usage: +# async_job [] +# +async_job() { + setopt localoptions noshwordsplit + + local worker=$1; shift + + local -a cmd + cmd=("$@") + if (( $#cmd > 1 )); then + cmd=(${(q)cmd}) # Quote special characters in multi argument commands. + fi + + zpty -w $worker $cmd$'\0' +} + +# This function traps notification signals and calls all registered callbacks +_async_notify_trap() { + setopt localoptions noshwordsplit + + for k in ${(k)ASYNC_CALLBACKS}; do + async_process_results $k ${ASYNC_CALLBACKS[$k]} trap + done +} + +# +# Register a callback for completed jobs. As soon as a job is finnished, async_process_results will be called with the +# specified callback function. This requires that a worker is initialized with the -n (notify) option. +# +# usage: +# async_register_callback +# +async_register_callback() { + setopt localoptions noshwordsplit nolocaltraps + + typeset -gA ASYNC_CALLBACKS + local worker=$1; shift + + ASYNC_CALLBACKS[$worker]="$*" + + # Enable trap when the ZLE watcher is unavailable, allows + # workers to notify (via -n) when a job is done. + if [[ ! -o interactive ]] || [[ ! -o zle ]]; then + trap '_async_notify_trap' WINCH + fi +} + +# +# Unregister the callback for a specific worker. +# +# usage: +# async_unregister_callback +# +async_unregister_callback() { + typeset -gA ASYNC_CALLBACKS + + unset "ASYNC_CALLBACKS[$1]" +} + +# +# Flush all current jobs running on a worker. This will terminate any and all running processes under the worker, use +# with caution. +# +# usage: +# async_flush_jobs +# +async_flush_jobs() { + setopt localoptions noshwordsplit + + local worker=$1; shift + + # Check if the worker exists + zpty -t $worker &>/dev/null || return 1 + + # Send kill command to worker + async_job $worker "_killjobs" + + # Clear the zpty buffer. + local junk + if zpty -r -t $worker junk '*'; then + (( ASYNC_DEBUG )) && print -n "async_flush_jobs $worker: ${(V)junk}" + while zpty -r -t $worker junk '*'; do + (( ASYNC_DEBUG )) && print -n "${(V)junk}" + done + (( ASYNC_DEBUG )) && print + fi + + # Finally, clear the process buffer in case of partially parsed responses. + typeset -gA ASYNC_PROCESS_BUFFER + unset "ASYNC_PROCESS_BUFFER[$worker]" +} + +# +# Start a new async worker with optional parameters, a worker can be told to only run unique tasks and to notify a +# process when tasks are complete. +# +# usage: +# async_start_worker [-u] [-n] [-p ] +# +# opts: +# -u unique (only unique job names can run) +# -n notify through SIGWINCH signal +# -p pid to notify (defaults to current pid) +# +async_start_worker() { + setopt localoptions noshwordsplit + + local worker=$1; shift + zpty -t $worker &>/dev/null && return + + typeset -gA ASYNC_PTYS + typeset -h REPLY + typeset has_xtrace=0 + + # Make sure async worker is started without xtrace + # (the trace output interferes with the worker). + [[ -o xtrace ]] && { + has_xtrace=1 + unsetopt xtrace + } + + if (( ! ASYNC_ZPTY_RETURNS_FD )) && [[ -o interactive ]] && [[ -o zle ]]; then + # When zpty doesn't return a file descriptor (on older versions of zsh) + # we try to guess it anyway. + integer -l zptyfd + exec {zptyfd}>&1 # Open a new file descriptor (above 10). + exec {zptyfd}>&- # Close it so it's free to be used by zpty. + fi + + zpty -b $worker _async_worker -p $$ $@ || { + async_stop_worker $worker + return 1 + } + + # Re-enable it if it was enabled, for debugging. + (( has_xtrace )) && setopt xtrace + + if [[ $ZSH_VERSION < 5.0.8 ]]; then + # For ZSH versions older than 5.0.8 we delay a bit to give + # time for the worker to start before issuing commands, + # otherwise it will not be ready to receive them. + sleep 0.001 + fi + + if [[ -o interactive ]] && [[ -o zle ]]; then + if (( ! ASYNC_ZPTY_RETURNS_FD )); then + REPLY=$zptyfd # Use the guessed value for the file desciptor. + fi + + ASYNC_PTYS[$REPLY]=$worker # Map the file desciptor to the worker. + zle -F $REPLY _async_zle_watcher # Register the ZLE handler. + + # Disable trap in favor of ZLE handler when notify is enabled (-n). + async_job $worker _unset_trap + fi +} + +# +# Stop one or multiple workers that are running, all unfetched and incomplete work will be lost. +# +# usage: +# async_stop_worker [] +# +async_stop_worker() { + setopt localoptions noshwordsplit + + local ret=0 + for worker in $@; do + # Find and unregister the zle handler for the worker + for k v in ${(@kv)ASYNC_PTYS}; do + if [[ $v == $worker ]]; then + zle -F $k + unset "ASYNC_PTYS[$k]" + fi + done + async_unregister_callback $worker + zpty -d $worker 2>/dev/null || ret=$? + + # Clear any partial buffers. + typeset -gA ASYNC_PROCESS_BUFFER + unset "ASYNC_PROCESS_BUFFER[$worker]" + done + + return $ret +} + +# +# Initialize the required modules for zsh-async. To be called before using the zsh-async library. +# +# usage: +# async_init +# +async_init() { + (( ASYNC_INIT_DONE )) && return + ASYNC_INIT_DONE=1 + + zmodload zsh/zpty + zmodload zsh/datetime + + # Check if zsh/zpty returns a file descriptor or not, + # shell must also be interactive with zle enabled. + ASYNC_ZPTY_RETURNS_FD=0 + [[ -o interactive ]] && [[ -o zle ]] && { + typeset -h REPLY + zpty _async_test : + (( REPLY )) && ASYNC_ZPTY_RETURNS_FD=1 + zpty -d _async_test + } +} + +async() { + async_init +} + +async "$@" diff --git a/base/.zsh/colors.zsh b/base/.zsh/colors.zsh new file mode 100644 index 0000000..9c8e32b --- /dev/null +++ b/base/.zsh/colors.zsh @@ -0,0 +1,3 @@ +export CLICOLOR=1 + +source `dirname $0`/fast-syntax-highlighting/fast-syntax-highlighting.plugin.zsh diff --git a/base/.zsh/completion.zsh b/base/.zsh/completion.zsh new file mode 100644 index 0000000..f9e452d --- /dev/null +++ b/base/.zsh/completion.zsh @@ -0,0 +1,81 @@ +autoload -U compinit +compinit + +setopt extendedglob +setopt NO_NOMATCH + +unsetopt menu_complete # do not autoselect the first completion entry +unsetopt flowcontrol +setopt auto_menu # show completion menu on succesive tab press +setopt complete_in_word +setopt always_to_end + +WORDCHARS='' + +zmodload -i zsh/complist + +## case-insensitive (all),partial-word and then substring completion +if [ "x$CASE_SENSITIVE" = "xtrue" ]; then + zstyle ':completion:*' matcher-list 'r:|[._-]=* r:|=*' 'l:|=* r:|=*' + unset CASE_SENSITIVE +else + zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*' +fi + +zstyle ':completion:*' list-colors '' + +# should this be in keybindings? +bindkey -M menuselect '^o' accept-and-infer-next-history + +zstyle ':completion:*:*:*:*:*' menu select +zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;34=0=01' +zstyle ':completion:*:*:*:*:processes' command "ps -u `whoami` -o pid,user,comm -w -w" + +# disable named-directories autocompletion +zstyle ':completion:*:cd:*' tag-order local-directories directory-stack path-directories +cdpath=(.) + +# use /etc/hosts and known_hosts for hostname completion +[ -r /etc/ssh/ssh_known_hosts ] && _global_ssh_hosts=(${${${${(f)"$(/dev/null 2>&1; then + eval "$(fasd --init zsh-hook zsh-ccomp zsh-ccomp-install zsh-wcomp zsh-wcomp-install posix-alias)" +fi diff --git a/base/.zsh/fast-syntax-highlighting/fast-highlight b/base/.zsh/fast-syntax-highlighting/fast-highlight new file mode 100644 index 0000000..70c8867 --- /dev/null +++ b/base/.zsh/fast-syntax-highlighting/fast-highlight @@ -0,0 +1,715 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2016 zsh-syntax-highlighting contributors +# Copyright (c) 2016-2017 Sebastian Gniazdowski (modifications) +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- + +typeset -gA __fast_highlight_main__command_type_cache + +# Define default styles. You can set this after loading the plugin in +# Zshrc and use 256 via numbers, like: fg=150 +typeset -gA FAST_HIGHLIGHT_STYLES +: ${FAST_HIGHLIGHT_STYLES[default]:=none} +: ${FAST_HIGHLIGHT_STYLES[unknown-token]:=fg=red,bold} +: ${FAST_HIGHLIGHT_STYLES[reserved-word]:=fg=yellow} +: ${FAST_HIGHLIGHT_STYLES[alias]:=fg=green} +: ${FAST_HIGHLIGHT_STYLES[suffix-alias]:=fg=green} +: ${FAST_HIGHLIGHT_STYLES[builtin]:=fg=green} +: ${FAST_HIGHLIGHT_STYLES[function]:=fg=green} +: ${FAST_HIGHLIGHT_STYLES[command]:=fg=green} +: ${FAST_HIGHLIGHT_STYLES[precommand]:=fg=green} +: ${FAST_HIGHLIGHT_STYLES[commandseparator]:=none} +: ${FAST_HIGHLIGHT_STYLES[hashed-command]:=fg=green} +: ${FAST_HIGHLIGHT_STYLES[path]:=fg=magenta} +: ${FAST_HIGHLIGHT_STYLES[path_pathseparator]:=} +: ${FAST_HIGHLIGHT_STYLES[globbing]:=fg=blue,bold} +: ${FAST_HIGHLIGHT_STYLES[history-expansion]:=fg=blue,bold} +: ${FAST_HIGHLIGHT_STYLES[single-hyphen-option]:=fg=cyan} +: ${FAST_HIGHLIGHT_STYLES[double-hyphen-option]:=fg=cyan} +: ${FAST_HIGHLIGHT_STYLES[back-quoted-argument]:=none} +: ${FAST_HIGHLIGHT_STYLES[single-quoted-argument]:=fg=yellow} +: ${FAST_HIGHLIGHT_STYLES[double-quoted-argument]:=fg=yellow} +: ${FAST_HIGHLIGHT_STYLES[dollar-quoted-argument]:=fg=yellow} +: ${FAST_HIGHLIGHT_STYLES[back-or-dollar-double-quoted-argument]:=fg=cyan} +: ${FAST_HIGHLIGHT_STYLES[back-dollar-quoted-argument]:=fg=cyan} +: ${FAST_HIGHLIGHT_STYLES[assign]:=none} +: ${FAST_HIGHLIGHT_STYLES[redirection]:=none} +: ${FAST_HIGHLIGHT_STYLES[comment]:=fg=black,bold} +: ${FAST_HIGHLIGHT_STYLES[variable]:=none} + + +typeset -gA __FAST_HIGHLIGHT_TOKEN_TYPES + +__FAST_HIGHLIGHT_TOKEN_TYPES=( + + # Precommand + + 'builtin' 1 + 'command' 1 + 'exec' 1 + 'nocorrect' 1 + 'noglob' 1 + 'pkexec' 1 # immune to #121 because it's usually not passed --option flags + + # Control flow + # Tokens that, at (naively-determined) "command position", are followed by + # a de jure command position. All of these are reserved words. + + $'\x7b' 2 # block + $'\x28' 2 # subshell + '()' 2 # anonymous function + 'while' 2 + 'until' 2 + 'if' 2 + 'then' 2 + 'elif' 2 + 'else' 2 + 'do' 2 + 'time' 2 + 'coproc' 2 + '!' 2 # reserved word; unrelated to $histchars[1] + + # Command separators + + '|' 3 + '||' 3 + ';' 3 + '&' 3 + '&&' 3 + '|&' 3 + '&!' 3 + '&|' 3 + # ### 'case' syntax, but followed by a pattern, not by a command + # ';;' ';&' ';|' +) + +# A hash instead of multiple globals +typeset -gA FAST_HIGHLIGHT + +# Get the type of a command. +# +# Uses the zsh/parameter module if available to avoid forks, and a +# wrapper around 'type -w' as fallback. +# +# Takes a single argument. +# +# The result will be stored in REPLY. +-fast-highlight-main-type() { + REPLY=$__fast_highlight_main__command_type_cache[(e)$1] + [[ -z "$REPLY" ]] && { + + if zmodload -e zsh/parameter; then + if (( $+aliases[(e)$1] )); then + REPLY=alias + elif (( $+functions[(e)$1] )); then + REPLY=function + elif (( $+builtins[(e)$1] )); then + REPLY=builtin + elif (( $+commands[(e)$1] )); then + REPLY=command + elif (( $+saliases[(e)${1##*.}] )); then + REPLY='suffix alias' + elif (( $reswords[(Ie)$1] )); then + REPLY=reserved + # zsh 5.2 and older have a bug whereby running 'type -w ./sudo' implicitly + # runs 'hash ./sudo=/usr/local/bin/./sudo' (assuming /usr/local/bin/sudo + # exists and is in $PATH). Avoid triggering the bug, at the expense of + # falling through to the $() below, incurring a fork. (Issue #354.) + # + # The second disjunct mimics the isrelative() C call from the zsh bug. + elif [[ $1 != */* || "${+ZSH_ARGZERO}" = "1" ]] && ! builtin type -w -- $1 >/dev/null 2>&1; then + REPLY=none + fi + fi + + [[ -z "$REPLY" ]] && REPLY="${$(LC_ALL=C builtin type -w -- $1 2>/dev/null)##*: }" + + [[ "$REPLY" = "none" ]] && { + [[ -d "$1" ]] && REPLY="dirpath" || { + for cdpath_dir in $cdpath; do + [[ -d "$cdpath_dir/$1" ]] && { REPLY="dirpath"; break; } + done + } + } + + __fast_highlight_main__command_type_cache[(e)$1]=$REPLY + + } +} + +# Below are variables that must be defined in outer +# scope so that they are reachable in *-process() +-fast-highlight-fill-option-variables() { + if [[ -o ignore_braces ]] || eval '[[ -o ignore_close_braces ]] 2>/dev/null'; then + FAST_HIGHLIGHT[right_brace_is_recognised_everywhere]=0 + else + FAST_HIGHLIGHT[right_brace_is_recognised_everywhere]=1 + fi + + if [[ -o path_dirs ]]; then + FAST_HIGHLIGHT[path_dirs_was_set]=1 + else + FAST_HIGHLIGHT[path_dirs_was_set]=0 + fi + + if [[ -o multi_func_def ]]; then + FAST_HIGHLIGHT[multi_func_def]=1 + else + FAST_HIGHLIGHT[multi_func_def]=0 + fi + + if [[ -o interactive_comments ]]; then + FAST_HIGHLIGHT[ointeractive_comments]=1 + else + FAST_HIGHLIGHT[ointeractive_comments]=0 + fi +} + +# Main syntax highlighting function. +-fast-highlight-process() +{ + emulate -L zsh + setopt extendedglob bareglobqual nonomatch noksharrays + + [[ $CONTEXT == "select" ]] && return 1 + [[ ${#BUFFER} -gt 10000 ]] && return 1 # Limit based on n-history length + + (( FAST_HIGHLIGHT[path_dirs_was_set] )) && setopt PATH_DIRS + (( FAST_HIGHLIGHT[ointeractive_comments] )) && local interactive_comments= # _set_ to empty + + # Variable declarations and initializations + # in_array_assignment true between 'a=(' and the matching ')' + # braces_stack: "R" for round, "Q" for square, "Y" for curly + # mybuf, cdpath_dir are used in sub-functions + local start_pos=0 end_pos start end highlight_glob=1 arg style in_array_assignment=0 MATCH expanded_path braces_stack buf="$PREBUFFER$BUFFER" mybuf cdpath_dir cur_cmd alias_target + # arg_type can be 0, 1, 2 or 3, i.e. precommand, control flow, command separator + # idx and end_idx are used in sub-functions + # for this_word and next_word look below at commented integers and at state machine description + integer arg_type=0 MBEGIN MEND in_redirection len=${#buf} already_added offset idx end_idx this_word=1 next_word=0 insane_alias pos + local -a match mbegin mend + + # integer BIT_start=1 BIT_regular=2 BIT_sudo_opt=4 BIT_sudo_arg=8 BIT_always=16 + + # State machine + # + # The states are: + # - :start: Command word + # - :sudo_opt: A leading-dash option to sudo (such as "-u" or "-i") + # - :sudo_arg: The argument to a sudo leading-dash option that takes one, + # when given as a separate word; i.e., "foo" in "-u foo" (two + # words) but not in "-ufoo" (one word). + # - :regular: "Not a command word", and command delimiters are permitted. + # Mainly used to detect premature termination of commands. + # - :always: The word 'always' in the «{ foo } always { bar }» syntax. + # + # When the kind of a word is not yet known, $this_word / $next_word may contain + # multiple states. For example, after "sudo -i", the next word may be either + # another --flag or a command name, hence the state would include both :start: + # and :sudo_opt:. + # + # The tokens are always added with both leading and trailing colons to serve as + # word delimiters (an improvised array); [[ $x == *:foo:* ]] and x=${x//:foo:/} + # will DTRT regardless of how many elements or repetitions $x has.. + # + # Handling of redirections: upon seeing a redirection token, we must stall + # the current state --- that is, the value of $this_word --- for two iterations + # (one for the redirection operator, one for the word following it representing + # the redirection target). Therefore, we set $in_redirection to 2 upon seeing a + # redirection operator, decrement it each iteration, and stall the current state + # when it is non-zero. Thus, upon reaching the next word (the one that follows + # the redirection operator and target), $this_word will still contain values + # appropriate for the word immediately following the word that preceded the + # redirection operator. + # + # The "the previous word was a redirection operator" state is not communicated + # to the next iteration via $next_word/$this_word as usual, but via + # $in_redirection. The value of $next_word from the iteration that processed + # the operator is discarded. + # + + # Processing buffer + local proc_buf="$buf" needle + for arg in ${interactive_comments-${(z)buf}} \ + ${interactive_comments+${(zZ+c+)buf}}; do + # Initialize $next_word to its default value? + (( in_redirection )) && (( --in_redirection )) + (( in_redirection == 0 )) && next_word=2 # else Stall $next_word. + + # Initialize per-"simple command" [zshmisc(1)] variables: + # + # $already_added (see next paragraph) + # $style how to highlight $arg + # $in_array_assignment boolean flag for "between '(' and ')' of array assignment" + # $highlight_glob boolean flag for "'noglob' is in effect" + # + # $already_added is set to 1 to disable adding an entry to region_highlight + # for this iteration. Currently, that is done for "" and $'' strings, + # which add the entry early so escape sequences within the string override + # the string's color. + already_added=0 + style=unknown-token + if (( this_word & 1 )); then + in_array_assignment=0 + [[ $arg == 'noglob' ]] && highlight_glob=0 + fi + + # Compute the new $start_pos and $end_pos, skipping over whitespace in $buf. + if [[ $arg == ';' ]] ; then + # We're looking for either a semicolon or a newline, whichever comes + # first. Both of these are rendered as a ";" (SEPER) by the ${(z)..} + # flag. + # + # We can't use the (Z+n+) flag because that elides the end-of-command + # token altogether, so 'echo foo\necho bar' (two commands) becomes + # indistinguishable from 'echo foo echo bar' (one command with three + # words for arguments). + needle=$'[;\n]' + offset=$(( ${proc_buf[(i)$needle]} - 1 )) + (( start_pos += offset )) + (( end_pos = start_pos + $#arg )) + + # Do not run default code for case when there is a new line + # It shouldn't be treated as ';', i.e. shouldn't be highlighted + # as unknown-token when appears after command-starting arg like "{" + if [[ "${proc_buf[offset+1]}" = $'\n' ]]; then + (( in_array_assignment )) && (( this_word = 2 )) || { (( this_word = 1 )); highlight_glob=1; } + in_redirection=0 + proc_buf="${proc_buf[offset + $#arg + 1,len]}" + start_pos=$end_pos + continue + else + # One more short path – for ';' command separator + (( in_array_assignment )) && (( this_word = 2 )) || { (( this_word = 1 )); highlight_glob=1; } + in_redirection=0 + [[ "${FAST_HIGHLIGHT_STYLES[commandseparator]}" != "none" ]] && (( start=start_pos-${#PREBUFFER}, end=end_pos-${#PREBUFFER}, start >= 0 )) && reply+=("$start $end ${FAST_HIGHLIGHT_STYLES[commandseparator]}") + proc_buf="${proc_buf[offset + $#arg + 1,len]}" + start_pos=$end_pos + continue + fi + + arg_type=3 + else + offset=0 + if [[ "$proc_buf" = (#b)(#s)(([[:space:]]|\\[[:space:]])##)* ]]; then + # The first, outer parenthesis + offset="${mend[1]}" + fi + ((start_pos+=offset)) + ((end_pos=start_pos+${#arg})) + + # No-hit will result in value 0 + arg_type=${__FAST_HIGHLIGHT_TOKEN_TYPES[$arg]} + fi + + proc_buf="${proc_buf[offset + $#arg + 1,len]}" + + # Handle the INTERACTIVE_COMMENTS option. + # + # We use the (Z+c+) flag so the entire comment is presented as one token in $arg. + if [[ -n ${interactive_comments+'set'} && $arg[1] == $histchars[3] ]]; then + if (( this_word & 3 )); then + style=comment + else + style=unknown-token # prematurely terminated + fi + # ADD + (( start=start_pos-${#PREBUFFER}, end=end_pos-${#PREBUFFER}, start >= 0 )) && reply+=("$start $end ${FAST_HIGHLIGHT_STYLES[$style]}") + start_pos=$end_pos + continue + fi + + # Analyse the current word. + if [[ $arg == (<0-9>|)(\<|\>)* ]] && [[ $arg != (\<|\>)$'\x28'* ]]; then + # A '<' or '>', possibly followed by a digit + in_redirection=2 + fi + + # Special-case the first word after 'sudo'. + if (( ! in_redirection )); then + if (( this_word & 4 )) && [[ $arg != -* ]]; then + (( this_word = this_word ^ 4 )) + fi + + # Parse the sudo command line + if (( this_word & 4 )); then + case "$arg" in + # Flag that requires an argument + '-'[Cgprtu]) + (( this_word & 1 )) && (( this_word = this_word ^ 1 )) + (( next_word = 8 )) + ;; + # This prevents misbehavior with sudo -u -otherargument + '-'*) + (( this_word & 1 )) && (( this_word = this_word ^ 1 )) + (( next_word = next_word | 1 )) + (( next_word = next_word | 4 )) + ;; + *) ;; + esac + elif (( this_word & 8 )); then + (( next_word = next_word | 4 )) + (( next_word = next_word | 1 )) + fi + fi + + expanded_path="" + + # The Great Fork: is this a command word? Is this a non-command word? + if (( this_word & 16 )) && [[ $arg == 'always' ]]; then + # try-always construct + style=reserved-word # de facto a reserved word, although not de jure + (( next_word = 1 )) + elif (( this_word & 1 )) && (( in_redirection == 0 )); then # $arg is the command word + cur_cmd="$arg" + if (( arg_type == 1 )); then + style=precommand + elif [[ "$arg" = "sudo" ]]; then + style=precommand + (( next_word & 2 )) && (( next_word = next_word ^ 2 )) + (( next_word = next_word | 4 )) + (( next_word = next_word | 1 )) + else + # Special-case: command word is '$foo', like that, without braces or anything. + # + # That's not entirely correct --- if the parameter's value happens to be a reserved + # word, the parameter expansion will be highlighted as a reserved word --- but that + # incorrectness is outweighed by the usability improvement of permitting the use of + # parameters that refer to commands, functions, and builtins. + if [[ ${arg[1]} == \$ ]] && (( ${+parameters} )) && [[ ${arg:1} = (#m)([a-zA-Z_][a-zA-Z0-9_]#|[0-9]##) ]] && (( ${+parameters[${MATCH}]} )); then + -fast-highlight-main-type ${(P)MATCH} + else + : ${expanded_path::=${(Q)~arg}} + -fast-highlight-main-type $expanded_path + fi + + case $REPLY in + reserved) # reserved word + style=reserved-word + if [[ $arg == $'\x7b' ]]; then + braces_stack='Y'"$braces_stack" + elif [[ $arg == $'\x7d' && $braces_stack[1] == "Y" ]]; then + # We're at command word, so no need to check right_brace_is_recognised_everywhere + braces_stack[1]="" + style=reserved-word + (( next_word = next_word | 16 )) + elif [[ $arg == "[[" ]]; then + braces_stack='A'"$braces_stack" + fi + ;; + 'suffix alias') style=suffix-alias;; + alias) + insane_alias=0 + case $arg in + # Issue #263: aliases with '=' on their LHS. + # + # There are three cases: + # + # - Unsupported, breaks 'alias -L' output, but invokable: + ('='*) :;; + # - Unsupported, not invokable: + (*'='*) insane_alias=1;; + # - The common case: + (*) :;; + esac + if (( insane_alias )); then + style=unknown-token + else + style=alias + zmodload -e zsh/parameter && alias_target=${aliases[$arg]} || alias_target="${"$(alias -- $arg)"#*=}" + [[ ${__FAST_HIGHLIGHT_TOKEN_TYPES[$alias_target]} = "1" && "$arg_type" != "1" ]] && __FAST_HIGHLIGHT_TOKEN_TYPES[$arg]="1" + fi + ;; + builtin) style=builtin;; + function) style=function;; + command) style=command;; + hashed) style=hashed-command;; + dirpath) style=path;; + none) # Assign? + if [[ $arg == [[:alpha:]_][[:alnum:]_]#(|\[[^\]]#\])(|[+])=* ]] || [[ $arg == [0-9]##(|[+])=* ]]; then + style=assign + # Assignment to a scalar parameter or to array + # (For array assignments, the command doesn't start until the ")" token.) + [[ $arg[-1] == '(' ]] && in_array_assignment=1 || (( next_word = next_word | 1 )) + elif [[ $arg[1] = $histchars[1] && -n "${arg[2]}" ]]; then + style=history-expansion + elif [[ $arg[1] == $histchars[2] ]]; then + style=history-expansion + elif (( arg_type == 3 )); then + # This highlights empty commands (semicolon follows nothing) as an error. + # Zsh accepts them, though. + (( this_word & 2 )) && style=commandseparator + elif [[ $arg[1,2] == '((' ]]; then + # Arithmetic evaluation. + # + # Note: prior to zsh-5.1.1-52-g4bed2cf (workers/36669), the ${(z)...} + # splitter would only output the '((' token if the matching '))' had + # been typed. Therefore, under those versions of zsh, BUFFER="(( 42" + # would be highlighted as an error until the matching "))" are typed. + # + # We highlight just the opening parentheses, as a reserved word; this + # is how [[ ... ]] is highlighted, too. + + # ADD + (( start=start_pos-${#PREBUFFER}, end=end_pos-${#PREBUFFER}, start >= 0 )) && reply+=("$start $(( start + 2 )) ${FAST_HIGHLIGHT_STYLES[reserved-word]}") + already_added=1 + # ADD + [[ $arg[-2,-1] == '))' ]] && (( start=start_pos-${#PREBUFFER}, end=end_pos-${#PREBUFFER}, start >= 0 )) && reply+=("$(( end - 2 )) $end ${FAST_HIGHLIGHT_STYLES[reserved-word]}") + elif [[ $arg == '()' ]]; then + # anonymous function + style=reserved-word + elif [[ $arg == $'\x28' ]]; then + # subshell + style=reserved-word + braces_stack='R'"$braces_stack" + elif [[ $arg == $'\x29' ]]; then + [[ $braces_stack[1] == "R" ]] && { braces_stack[1]=""; style=reserved-word; } + elif (( this_word & 14 )); then + style=default + fi + ;; + *) + # ADD + # (( start=start_pos-${#PREBUFFER}, end=end_pos-${#PREBUFFER}, start >= 0 )) && reply+=("$start $end commandtypefromthefuture-$REPLY") + already_added=1 + ;; + esac + fi + # in_redirection || BIT_regular || BIT_sudo_opt || BIT_sudo_arg + elif (( in_redirection + this_word & 14 )) + then # $arg is a non-command word + case $arg in + ']]') + style=reserved-word + [[ $braces_stack[1] == "A" ]] && braces_stack[1]="" + ;; + ']') + style=builtin + ;; + $'\x28') + # '(' inside [[ + style=reserved-word + braces_stack='R'"$braces_stack" + ;; + $'\x29') # subshell or end of array assignment + if (( in_array_assignment )); then + style=assign + in_array_assignment=0 + (( next_word = next_word | 1 )) + elif [[ $braces_stack[1] == "R" ]]; then + braces_stack[1]="" + style=reserved-word + fi;; + $'\x28\x29') # possibly a function definition + # || false # TODO: or if the previous word was a command word + (( FAST_HIGHLIGHT[multi_func_def] )) && (( next_word = next_word | 1 )) + style=reserved-word + # Remove possible annoying unknown-token style, or misleading function style + reply[-1]=() + ;; + '--'*) style=double-hyphen-option;; + '-'*) style=single-hyphen-option;; + "'"*) style=single-quoted-argument;; + '"'*) + # ADD + (( start=start_pos-${#PREBUFFER}, end=end_pos-${#PREBUFFER}, start >= 0 )) && reply+=("$start $end ${FAST_HIGHLIGHT_STYLES[double-quoted-argument]}") + -fast-highlight-string + already_added=1 + ;; + \$\'*) + # ADD + (( start=start_pos-${#PREBUFFER}, end=end_pos-${#PREBUFFER}, start >= 0 )) && reply+=("$start $end ${FAST_HIGHLIGHT_STYLES[dollar-quoted-argument]}") + -fast-highlight-dollar-string + already_added=1 + ;; + \$[^\(]*) + style=variable + ;; + '`'*) style=back-quoted-argument;; + [*?]*|*[^\\][*?]*) + (( highlight_glob )) && style=globbing || style=default;; + *) if [[ $arg = $'\x7d' && $braces_stack[1] == "Y" && "$FAST_HIGHLIGHT[right_brace_is_recognised_everywhere]" = "1" ]]; then + # right brace + # Parsing rule: # { + # + # Additionally, `tt(})' is recognized in any position if neither the + # tt(IGNORE_BRACES) option nor the tt(IGNORE_CLOSE_BRACES) option is set.""" + braces_stack[1]="" + style=reserved-word + (( next_word = next_word | 16 )) + elif [[ $arg[1] = $histchars[1] && -n "${arg[2]}" ]]; then + style=history-expansion + elif (( arg_type == 3 )); then + style=commandseparator + elif (( in_redirection == 2 )); then + style=redirection + else + if [[ -z "${FAST_HIGHLIGHT[no_check_paths]}" ]] && -fast-highlight-check-path; then + # ADD + (( start=start_pos-${#PREBUFFER}, end=end_pos-${#PREBUFFER}, start >= 0 )) && reply+=("$start $end ${FAST_HIGHLIGHT_STYLES[path]}") + already_added=1 + + [[ -n "$FAST_HIGHLIGHT_STYLES[path_pathseparator]" && "$FAST_HIGHLIGHT_STYLES[path]" != "$FAST_HIGHLIGHT_STYLES[path_pathseparator]" ]] && { + for (( pos = start_pos; pos <= end_pos; pos++ )) ; do + # ADD + [[ ${buf[pos]} == "/" ]] && (( start=pos-${#PREBUFFER}, start >= 0 )) && reply+=("$(( start - 1 )) $start ${FAST_HIGHLIGHT_STYLES[path_pathseparator]}") + done + } + else + style=default + fi + fi + ;; + esac + fi + + # ADD + (( already_added == 0 )) && [[ "${FAST_HIGHLIGHT_STYLES[$style]}" != "none" ]] && (( start=start_pos-${#PREBUFFER}, end=end_pos-${#PREBUFFER}, start >= 0 )) && reply+=("$start $end ${FAST_HIGHLIGHT_STYLES[$style]}") + + if (( arg_type == 3 )); then + if [[ $arg == ';' ]] && (( in_array_assignment )); then + # literal newline inside an array assignment + (( next_word = 2 )) + elif [[ -n "${braces_stack[(r)A]}" ]]; then + (( next_word = 2 )) + else + (( next_word = 1 )) + highlight_glob=1 + fi + elif (( arg_type == 1 || arg_type == 2 )) && (( this_word & 1 )); then + (( next_word = 1 )) + elif [[ $arg == "repeat" ]] && (( this_word & 1 )); then + # skip the repeat-count word + in_redirection=2 + # The redirection mechanism assumes $this_word describes the word + # following the redirection. Make it so. + # + # That word can be a command word with shortloops (`repeat 2 ls`) + # or a command separator (`repeat 2; ls` or `repeat 2; do ls; done`). + # + # The repeat-count word will be handled like a redirection target. + (( this_word = 3 )) + fi + start_pos=$end_pos + # This is the default/common codepath. + (( in_redirection == 0 )) && (( this_word = next_word )) #else # Stall $this_word. + done + + return 0 +} + +# Check if $arg is a path. +# If yes, return 0 and in $REPLY the style to use. +# Else, return non-zero (and the contents of $REPLY is undefined). +-fast-highlight-check-path() +{ + : ${expanded_path:=${(Q)~arg}} + + [[ -z $expanded_path ]] && return 1 + [[ -e $expanded_path ]] && return 0 + + # Search the path in CDPATH, only for CD command + [[ "$cur_cmd" = "cd" ]] && for cdpath_dir in $cdpath ; do + [[ -e "$cdpath_dir/$expanded_path" ]] && return 0 + done + + # It's not a path. + return 1 +} + +# Highlight special chars inside double-quoted strings +-fast-highlight-string() +{ + mybuf="$arg" + idx=start_pos + + while [[ "$mybuf" = (#b)[^\$\\]#((\$(#B)([a-zA-Z_:][a-zA-Z0-9_:]#|[0-9]##)(#b)(\[[^\]]#\])(#c0,1))|(\$[{](\([a-zA-Z0@%#]##\))(#c0,1)[a-zA-Z0-9_:#]##(\[[^\]]#\])(#c0,1)[}])|[\\][\'\"\$]|[\\](*))(*) ]]; do + [[ -n "${match[7]}" ]] && { + # Skip following char – it is quoted. Choice is + # made to not highlight such quoting + idx+=${mbegin[1]}+1 + mybuf="${match[7]:1}" + } || { + idx+=${mbegin[1]}-1 + end_idx=idx+${mend[1]}-${mbegin[1]}+1 + mybuf="${match[8]}" + + # ADD + (( start=idx-${#PREBUFFER}, end=end_idx-${#PREBUFFER}, start >= 0 )) && reply+=("$start $end ${FAST_HIGHLIGHT_STYLES[back-or-dollar-double-quoted-argument]}") + + idx=end_idx + } + done +} + +# Highlight special chars inside dollar-quoted strings +-fast-highlight-dollar-string() +{ + local i j k style + local AA + integer c + # Starting dollar-quote is at 1:2, so start parsing at offset 3 in the string. + for (( i = 3 ; i < end_pos - start_pos ; i += 1 )) ; do + (( j = i + start_pos - 1 )) + (( k = j + 1 )) + case "$arg[$i]" in + "\\") style=back-dollar-quoted-argument + for (( c = i + 1 ; c <= end_pos - start_pos ; c += 1 )); do + [[ "$arg[$c]" != ([0-9xXuUa-fA-F]) ]] && break + done + AA=$arg[$i+1,$c-1] + # Matching for HEX and OCT values like \0xA6, \xA6 or \012 + if [[ "$AA" =~ "^(x|X)[0-9a-fA-F]{1,2}" + || "$AA" =~ "^[0-7]{1,3}" + || "$AA" =~ "^u[0-9a-fA-F]{1,4}" + || "$AA" =~ "^U[0-9a-fA-F]{1,8}" + ]]; then + (( k += $#MATCH )) + (( i += $#MATCH )) + else + if (( $#arg > $i+1 )) && [[ $arg[$i+1] == [xXuU] ]]; then + # \x not followed by hex digits is probably an error + style=unknown-token + fi + (( k += 1 )) # Color following char too. + (( i += 1 )) # Skip parsing the escaped char. + fi + ;; + *) continue ;; + + esac + # ADD + (( start=j-${#PREBUFFER}, end=k-${#PREBUFFER}, start >= 0 )) && reply+=("$start $end ${FAST_HIGHLIGHT_STYLES[$style]}") + done +} + +# ------------------------------------------------------------------------------------------------- +# Main highlighter initialization +# ------------------------------------------------------------------------------------------------- + +-fast-highlight-init() { + __fast_highlight_main__command_type_cache=() +} + +# vim:ft=zsh:sw=2:sts=2 +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- diff --git a/base/.zsh/fast-syntax-highlighting/fast-syntax-highlighting.plugin.zsh b/base/.zsh/fast-syntax-highlighting/fast-syntax-highlighting.plugin.zsh new file mode 100644 index 0000000..235d425 --- /dev/null +++ b/base/.zsh/fast-syntax-highlighting/fast-syntax-highlighting.plugin.zsh @@ -0,0 +1,272 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2016 zsh-syntax-highlighting contributors +# Copyright (c) 2017 Sebastian Gniazdowski (modifications) +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + + +# Set $ZERO to the expected value, regardless of functionargzero. +typeset -g ZERO=${(%):-%N} + +# Invokes each highlighter that needs updating. +# This function is supposed to be called whenever the ZLE state changes. +_zsh_highlight() +{ + # Store the previous command return code to restore it whatever happens. + local ret=$? + + # Remove all highlighting in isearch, so that only the underlining done by zsh itself remains. + # For details see FAQ entry 'Why does syntax highlighting not work while searching history?'. + if [[ $WIDGET == zle-isearch-update ]] && ! (( $+ISEARCHMATCH_ACTIVE )); then + region_highlight=() + return $ret + fi + + setopt localoptions warncreateglobal noksharrays + local REPLY # don't leak $REPLY into global scope + local -a reply + + # Do not highlight if there are more than 300 chars in the buffer. It's most + # likely a pasted command or a huge list of files in that case.. + [[ -n ${ZSH_HIGHLIGHT_MAXLENGTH:-} ]] && [[ $#BUFFER -gt $ZSH_HIGHLIGHT_MAXLENGTH ]] && return $ret + + # Do not highlight if there are pending inputs (copy/paste). + [[ $PENDING -gt 0 ]] && return $ret + + # Reset region highlight to build it from scratch + # may need to remove path_prefix highlighting when the line ends + if [[ $WIDGET == zle-line-finish ]] || _zsh_highlight_buffer_modified; then + -fast-highlight-init + -fast-highlight-process && region_highlight=( $reply ) || region_highlight=() + fi + + { + local cache_place + local -a region_highlight_copy + + # Re-apply zle_highlight settings + + # region + if (( REGION_ACTIVE == 1 )); then + _zsh_highlight_apply_zle_highlight region standout "$MARK" "$CURSOR" + elif (( REGION_ACTIVE == 2 )); then + () { + local needle=$'\n' + integer min max + if (( MARK > CURSOR )) ; then + min=$CURSOR max=$MARK + else + min=$MARK max=$CURSOR + fi + (( min = ${${BUFFER[1,$min]}[(I)$needle]} )) + (( max += ${${BUFFER:($max-1)}[(i)$needle]} - 1 )) + _zsh_highlight_apply_zle_highlight region standout "$min" "$max" + } + fi + + # yank / paste (zsh-5.1.1 and newer) + (( $+YANK_ACTIVE )) && (( YANK_ACTIVE )) && _zsh_highlight_apply_zle_highlight paste standout "$YANK_START" "$YANK_END" + + # isearch + (( $+ISEARCHMATCH_ACTIVE )) && (( ISEARCHMATCH_ACTIVE )) && _zsh_highlight_apply_zle_highlight isearch underline "$ISEARCHMATCH_START" "$ISEARCHMATCH_END" + + # suffix + (( $+SUFFIX_ACTIVE )) && (( SUFFIX_ACTIVE )) && _zsh_highlight_apply_zle_highlight suffix bold "$SUFFIX_START" "$SUFFIX_END" + + return $ret + + } always { + typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER="$BUFFER" + typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=$CURSOR + } +} + +# Apply highlighting based on entries in the zle_highlight array. +# This function takes four arguments: +# 1. The exact entry (no patterns) in the zle_highlight array: +# region, paste, isearch, or suffix +# 2. The default highlighting that should be applied if the entry is unset +# 3. and 4. Two integer values describing the beginning and end of the +# range. The order does not matter. +_zsh_highlight_apply_zle_highlight() { + local entry="$1" default="$2" + integer first="$3" second="$4" + + # read the relevant entry from zle_highlight + local region="${zle_highlight[(r)${entry}:*]}" + + if [[ -z "$region" ]]; then + # entry not specified at all, use default value + region=$default + else + # strip prefix + region="${region#${entry}:}" + + # no highlighting when set to the empty string or to 'none' + if [[ -z "$region" ]] || [[ "$region" == none ]]; then + return + fi + fi + + integer start end + if (( first < second )); then + start=$first end=$second + else + start=$second end=$first + fi + region_highlight+=("$start $end $region") +} + + +# ------------------------------------------------------------------------------------------------- +# API/utility functions for highlighters +# ------------------------------------------------------------------------------------------------- + +# Whether the command line buffer has been modified or not. +# +# Returns 0 if the buffer has changed since _zsh_highlight was last called. +_zsh_highlight_buffer_modified() +{ + [[ "${_ZSH_HIGHLIGHT_PRIOR_BUFFER:-}" != "$BUFFER" ]] +} + +# Whether the cursor has moved or not. +# +# Returns 0 if the cursor has moved since _zsh_highlight was last called. +_zsh_highlight_cursor_moved() +{ + [[ -n $CURSOR ]] && [[ -n ${_ZSH_HIGHLIGHT_PRIOR_CURSOR-} ]] && (($_ZSH_HIGHLIGHT_PRIOR_CURSOR != $CURSOR)) +} + +# ------------------------------------------------------------------------------------------------- +# Setup functions +# ------------------------------------------------------------------------------------------------- + +# Helper for _zsh_highlight_bind_widgets +# $1 is name of widget to call +_zsh_highlight_call_widget() +{ + builtin zle "$@" && _zsh_highlight +} + +# Rebind all ZLE widgets to make them invoke _zsh_highlights. +_zsh_highlight_bind_widgets() +{ + setopt localoptions noksharrays + typeset -F SECONDS + local prefix=orig-s$SECONDS-r$RANDOM # unique each time, in case we're sourced more than once + + # Load ZSH module zsh/zleparameter, needed to override user defined widgets. + zmodload zsh/zleparameter 2>/dev/null || { + print -r -- >&2 'zsh-syntax-highlighting: failed loading zsh/zleparameter.' + return 1 + } + + # Override ZLE widgets to make them invoke _zsh_highlight. + local -U widgets_to_bind + widgets_to_bind=(${${(k)widgets}:#(.*|run-help|which-command|beep|set-local-history|yank)}) + + # Always wrap special zle-line-finish widget. This is needed to decide if the + # current line ends and special highlighting logic needs to be applied. + # E.g. remove cursor imprint, don't highlight partial paths, ... + widgets_to_bind+=(zle-line-finish) + + # Always wrap special zle-isearch-update widget to be notified of updates in isearch. + # This is needed because we need to disable highlighting in that case. + widgets_to_bind+=(zle-isearch-update) + + local cur_widget + for cur_widget in $widgets_to_bind; do + case $widgets[$cur_widget] in + + # Already rebound event: do nothing. + user:_zsh_highlight_widget_*);; + + # The "eval"'s are required to make $cur_widget a closure: the value of the parameter at function + # definition time is used. + # + # We can't use ${0/_zsh_highlight_widget_} because these widgets are always invoked with + # NO_function_argzero, regardless of the option's setting here. + + # User defined widget: override and rebind old one with prefix "orig-". + user:*) zle -N $prefix-$cur_widget ${widgets[$cur_widget]#*:} + eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }" + zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;; + + # Completion widget: override and rebind old one with prefix "orig-". + completion:*) zle -C $prefix-$cur_widget ${${(s.:.)widgets[$cur_widget]}[2,3]} + eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }" + zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;; + + # Builtin widget: override and make it call the builtin ".widget". + builtin) eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget .${(q)cur_widget} -- \"\$@\" }" + zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;; + + # Incomplete or nonexistent widget: Bind to z-sy-h directly. + *) + if [[ $cur_widget == zle-* ]] && [[ -z $widgets[$cur_widget] ]]; then + _zsh_highlight_widget_${cur_widget}() { :; _zsh_highlight } + zle -N $cur_widget _zsh_highlight_widget_$cur_widget + else + # Default: unhandled case. + print -r -- >&2 "zsh-syntax-highlighting: unhandled ZLE widget ${(qq)cur_widget}" + fi + esac + done +} + +# ------------------------------------------------------------------------------------------------- +# Setup +# ------------------------------------------------------------------------------------------------- + +# Try binding widgets. +_zsh_highlight_bind_widgets || { + print -r -- >&2 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.' + return 1 +} + +# Reset scratch variables when commandline is done. +_zsh_highlight_preexec_hook() +{ + typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER= + typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=0 +} + +autoload -U add-zsh-hook +add-zsh-hook preexec _zsh_highlight_preexec_hook 2>/dev/null || { + print -r -- >&2 'zsh-syntax-highlighting: failed loading add-zsh-hook.' +} + +# Load zsh/parameter module if available +zmodload zsh/parameter 2>/dev/null + +autoload -U is-at-least +source "${ZERO:h}/fast-highlight" + +[[ "${+termcap[Co]}" = 1 && "${termcap[Co]}" = "256" ]] && FAST_HIGHLIGHT_STYLES[variable]="fg=112" + +-fast-highlight-fill-option-variables diff --git a/base/.zsh/functions.zsh b/base/.zsh/functions.zsh new file mode 100644 index 0000000..7c405f0 --- /dev/null +++ b/base/.zsh/functions.zsh @@ -0,0 +1,10 @@ +todo () { + a="" + for i; do a="$a,$i"; done + a="{$(echo "$a" | cut -d',' -f2-)}" + echo "grep -R --exclude-dir=$a TODO | sed -e 's/.*TODO //;s/ \*\/$//;s/ -->//' | LC_ALL=C sort -u" | zsh +} + +which () { + (alias; declare -f) | /usr/bin/which --tty-only --read-alias --read-functions --show-tilde --show-dot $@ +} #export -f which diff --git a/base/.zsh/history.zsh b/base/.zsh/history.zsh new file mode 100644 index 0000000..f21023d --- /dev/null +++ b/base/.zsh/history.zsh @@ -0,0 +1,15 @@ +if [ -z $HISTFILE ]; then + HISTFILE=$HOME/.zsh_history +fi +HISTSIZE=100000 +SAVEHIST=100000 +HISTCONTROL=ignoredups + +setopt append_history +setopt extended_history +setopt hist_expire_dups_first +setopt hist_ignore_dups # ignore duplication command history list +setopt hist_ignore_space +setopt hist_verify +setopt inc_append_history + diff --git a/base/.zsh/prompt.zsh b/base/.zsh/prompt.zsh new file mode 100644 index 0000000..2789a38 --- /dev/null +++ b/base/.zsh/prompt.zsh @@ -0,0 +1,2 @@ +autoload -U promptinit && promptinit +prompt pure diff --git a/base/.zsh/prompt_pure_setup b/base/.zsh/prompt_pure_setup new file mode 100644 index 0000000..d9b7f2d --- /dev/null +++ b/base/.zsh/prompt_pure_setup @@ -0,0 +1,385 @@ +# Quickref +# git: +# %b => current branch +# %a => current action (rebase/merge) +# prompt: +# %F => color dict +# %f => reset color +# %~ => current path +# %* => time +# %n => username +# %m => shortname host +# %(?..) => prompt conditional - %(condition.true.false) +# terminal codes: +# \e7 => save cursor position +# \e[2A => move cursor 2 lines up +# \e[1G => go to position 1 in terminal +# \e8 => restore cursor position +# \e[K => clears everything after the cursor on the current line +# \e[2K => clear everything on the current line + +PURER_PROMPT_COMMAND_COUNT=0 +STATUS_COLOR=6 + +# turns seconds into human readable time +# 165392 => 1d 21h 56m 32s +# https://github.com/sindresorhus/pretty-time-zsh +prompt_pure_human_time_to_var() { + local human=" [" total_seconds=$1 var=$2 + local days=$(( total_seconds / 60 / 60 / 24 )) + local hours=$(( total_seconds / 60 / 60 % 24 )) + local minutes=$(( total_seconds / 60 % 60 )) + local seconds=$(( total_seconds % 60 )) + (( days > 0 )) && human+="${days}d " + (( hours > 0 )) && human+="${hours}h " + (( minutes > 0 )) && human+="${minutes}m " + human+="${seconds}s]" + + # store human readable time in variable as specified by caller + typeset -g "${var}"="${human}" +} + +# stores (into prompt_pure_cmd_exec_time) the exec time of the last command if set threshold was exceeded +prompt_pure_check_cmd_exec_time() { + integer elapsed + (( elapsed = EPOCHSECONDS - ${prompt_pure_cmd_timestamp:-$EPOCHSECONDS} )) + prompt_pure_cmd_exec_time= + (( elapsed > ${PURE_CMD_MAX_EXEC_TIME:=15} )) && { + prompt_pure_human_time_to_var $elapsed "prompt_pure_cmd_exec_time" + } +} + +prompt_pure_clear_screen() { + # enable output to terminal + zle -I + # clear screen and move cursor to (0, 0) + print -n '\e[2J\e[0;0H' + # reset command count to zero so we don't start with a blank line + PURER_PROMPT_COMMAND_COUNT=0 + # print preprompt + prompt_pure_preprompt_render precmd +} + +# set STATUS_COLOR: cyan for "insert", green for "normal" mode. +prompt_purer_vim_mode() { + STATUS_COLOR="${${KEYMAP/vicmd/16}/(main|viins)/6}" + prompt_pure_preprompt_render +} + +prompt_pure_set_title() { + # emacs terminal does not support settings the title + (( ${+EMACS} )) && return + + # tell the terminal we are setting the title + print -n '\e]0;' + # show hostname if connected through ssh + [[ -n $SSH_CONNECTION ]] && print -Pn '(%m) ' + case $1 in + expand-prompt) + print -Pn $2;; + ignore-escape) + print -rn $2;; + esac + # end set title + print -n '\a' +} + +prompt_pure_preexec() { + # attempt to detect and prevent prompt_pure_async_git_fetch from interfering with user initiated git or hub fetch + [[ $2 =~ (git|hub)\ .*(pull|fetch) ]] && async_flush_jobs 'prompt_pure' + + prompt_pure_cmd_timestamp=$EPOCHSECONDS + + # shows the current dir and executed command in the title while a process is active + prompt_pure_set_title 'ignore-escape' "$PWD:t: $2" +} + +# string length ignoring ansi escapes +prompt_pure_string_length_to_var() { + local str=$1 var=$2 length + # perform expansion on str and check length + length=$(( ${#${(S%%)str//(\%([KF1]|)\{*\}|\%[Bbkf])}} )) + + # store string length in variable as specified by caller + typeset -g "${var}"="${length}" +} + +prompt_pure_preprompt_render() { + # store the current prompt_subst setting so that it can be restored later + local prompt_subst_status=$options[prompt_subst] + + # make sure prompt_subst is unset to prevent parameter expansion in preprompt + setopt local_options no_prompt_subst + + # check that no command is currently running, the preprompt will otherwise be rendered in the wrong place + [[ -n ${prompt_pure_cmd_timestamp+x} && "$1" != "precmd" ]] && return + + # set color for git branch/dirty status, change color if dirty checking has been delayed + local git_color=20 + [[ -n ${prompt_pure_git_last_dirty_check_timestamp+x} ]] && git_color=1 + + # construct preprompt + local preprompt="" + + # add a newline between commands + FIRST_COMMAND_THRESHOLD=1 + if [[ "$PURER_PROMPT_COMMAND_COUNT" -gt "$FIRST_COMMAND_THRESHOLD" ]]; then + preprompt+=$'\n' + fi + + # host ID + if [[ "$PROMPT_HOST_COLOR" ]]; then + preprompt+="%b%F{black}%K{$PROMPT_HOST_COLOR} " + [[ "$PROMPT_SHORT_HOSTNAME" ]] && preprompt+="$PROMPT_SHORT_HOSTNAME " + preprompt+="%F{$PROMPT_HOST_COLOR}%K{18}%f" + fi + preprompt+="%K{18} " + # directory, colored by vim status + preprompt+="%B%F{$STATUS_COLOR}%c%f%b" + # git info + preprompt+="%F{$git_color}${vcs_info_msg_0_}${prompt_pure_git_dirty}%f" + # git pull/push arrows + preprompt+="%F{cyan}${prompt_pure_git_arrows}%f" + # username and machine if applicable + #preprompt+=$prompt_pure_username + # execution time + preprompt+="%F{20}${prompt_pure_cmd_exec_time}%f" + # end with symbol, colored by previous command exit code + # local symbol_color="%(?.${PURE_PROMPT_SYMBOL_COLOR:-magenta}.red)" + # preprompt+=" %F{$symbol_color}${PURE_PROMPT_SYMBOL:-❯}%f" + preprompt+=" %F{18}%(?.%k.%K{1}%F{1}%k)%f" + #  + + preprompt+=" " + + # make sure prompt_pure_last_preprompt is a global array + typeset -g -a prompt_pure_last_preprompt + + PROMPT="$preprompt" + + # if executing through precmd, do not perform fancy terminal editing + if [[ "$1" != "precmd" ]]; then + # only redraw if the expanded preprompt has changed + # [[ "${prompt_pure_last_preprompt[2]}" != "${(S%%)preprompt}" ]] || return + + # redraw prompt (also resets cursor position) + zle && zle .reset-prompt + + setopt no_prompt_subst + fi + + # store both unexpanded and expanded preprompt for comparison + prompt_pure_last_preprompt=("$preprompt" "${(S%%)preprompt}") +} + +prompt_pure_precmd() { + # check exec time and store it in a variable + prompt_pure_check_cmd_exec_time + + # by making sure that prompt_pure_cmd_timestamp is defined here the async functions are prevented from interfering + # with the initial preprompt rendering + prompt_pure_cmd_timestamp= + + # shows the full path in the title + prompt_pure_set_title 'expand-prompt' '%~' + + # get vcs info + vcs_info + + # preform async git dirty check and fetch + prompt_pure_async_tasks + + # Increment command counter + PURER_PROMPT_COMMAND_COUNT=$((PURER_PROMPT_COMMAND_COUNT+1)) + + # print the preprompt + prompt_pure_preprompt_render "precmd" + + # remove the prompt_pure_cmd_timestamp, indicating that precmd has completed + unset prompt_pure_cmd_timestamp +} + +# fastest possible way to check if repo is dirty +prompt_pure_async_git_dirty() { + setopt localoptions noshwordsplit + local untracked_dirty=$1 dir=$2 + + # use cd -q to avoid side effects of changing directory, e.g. chpwd hooks + builtin cd -q $dir + + if [[ $untracked_dirty = 0 ]]; then + command git diff --no-ext-diff --quiet --exit-code + else + test -z "$(command git status --porcelain --ignore-submodules -unormal)" + fi + + return $? +} + +prompt_pure_async_git_fetch() { + setopt localoptions noshwordsplit + # use cd -q to avoid side effects of changing directory, e.g. chpwd hooks + builtin cd -q $1 + + # set GIT_TERMINAL_PROMPT=0 to disable auth prompting for git fetch (git 2.3+) + export GIT_TERMINAL_PROMPT=0 + # set ssh BachMode to disable all interactive ssh password prompting + export GIT_SSH_COMMAND=${GIT_SSH_COMMAND:-"ssh -o BatchMode=yes"} + + command git -c gc.auto=0 fetch &>/dev/null || return 1 + + # check arrow status after a successful git fetch + prompt_pure_async_git_arrows $1 +} + +prompt_pure_async_git_arrows() { + setopt localoptions noshwordsplit + builtin cd -q $1 + command git rev-list --left-right --count HEAD...@'{u}' +} + +prompt_pure_async_tasks() { + setopt localoptions noshwordsplit + + # initialize async worker + ((!${prompt_pure_async_init:-0})) && { + async_start_worker "prompt_pure" -u -n + async_register_callback "prompt_pure" prompt_pure_async_callback + prompt_pure_async_init=1 + } + + # store working_tree without the "x" prefix + local working_tree="${vcs_info_msg_1_#x}" + + # check if the working tree changed (prompt_pure_current_working_tree is prefixed by "x") + if [[ ${prompt_pure_current_working_tree#x} != $working_tree ]]; then + # stop any running async jobs + async_flush_jobs "prompt_pure" + + # reset git preprompt variables, switching working tree + unset prompt_pure_git_dirty + unset prompt_pure_git_last_dirty_check_timestamp + prompt_pure_git_arrows= + + # set the new working tree and prefix with "x" to prevent the creation of a named path by AUTO_NAME_DIRS + prompt_pure_current_working_tree="x${working_tree}" + fi + + # only perform tasks inside git working tree + [[ -n $working_tree ]] || return + + async_job "prompt_pure" prompt_pure_async_git_arrows $working_tree + + # do not preform git fetch if it is disabled or working_tree == HOME + if (( ${PURE_GIT_PULL:-1} )) && [[ $working_tree != $HOME ]]; then + # tell worker to do a git fetch + async_job "prompt_pure" prompt_pure_async_git_fetch $working_tree + fi + + # if dirty checking is sufficiently fast, tell worker to check it again, or wait for timeout + integer time_since_last_dirty_check=$(( EPOCHSECONDS - ${prompt_pure_git_last_dirty_check_timestamp:-0} )) + if (( time_since_last_dirty_check > ${PURE_GIT_DELAY_DIRTY_CHECK:-1800} )); then + unset prompt_pure_git_last_dirty_check_timestamp + # check check if there is anything to pull + async_job "prompt_pure" prompt_pure_async_git_dirty ${PURE_GIT_UNTRACKED_DIRTY:-1} $working_tree + fi +} + +prompt_pure_check_git_arrows() { + setopt localoptions noshwordsplit + local arrows left=${1:-0} right=${2:-0} + + (( right > 0 )) && arrows+=${PURE_GIT_DOWN_ARROW:-⇣} + (( left > 0 )) && arrows+=${PURE_GIT_UP_ARROW:-⇡} + + [[ -n $arrows ]] || return + typeset -g REPLY=" $arrows" +} + +prompt_pure_async_callback() { + setopt localoptions noshwordsplit + local job=$1 code=$2 output=$3 exec_time=$4 + + case $job in + prompt_pure_async_git_dirty) + local prev_dirty=$prompt_pure_git_dirty + if (( code == 0 )); then + prompt_pure_git_dirty= + else + prompt_pure_git_dirty="*" + fi + + [[ $prev_dirty != $prompt_pure_git_dirty ]] && prompt_pure_preprompt_render + + # When prompt_pure_git_last_dirty_check_timestamp is set, the git info is displayed in a different color. + # To distinguish between a "fresh" and a "cached" result, the preprompt is rendered before setting this + # variable. Thus, only upon next rendering of the preprompt will the result appear in a different color. + (( $exec_time > 2 )) && prompt_pure_git_last_dirty_check_timestamp=$EPOCHSECONDS + ;; + prompt_pure_async_git_fetch|prompt_pure_async_git_arrows) + # prompt_pure_async_git_fetch executes prompt_pure_async_git_arrows + # after a successful fetch. + if (( code == 0 )); then + local REPLY + prompt_pure_check_git_arrows ${(ps:\t:)output} + if [[ $prompt_pure_git_arrows != $REPLY ]]; then + prompt_pure_git_arrows=$REPLY + prompt_pure_preprompt_render + fi + fi + ;; + esac +} + +prompt_pure_setup() { + # prevent percentage showing up + # if output doesn't end with a newline + export PROMPT_EOL_MARK='' + + # prompt_opts=(subst percent) + + # borrowed from promptinit, sets the prompt options in case pure was not + # initialized via promptinit. + # setopt noprompt{bang,cr,percent,subst} "prompt${^prompt_opts[@]}" + + zmodload zsh/datetime + zmodload zsh/zle + zmodload zsh/parameter + + autoload -Uz add-zsh-hook + autoload -Uz vcs_info + autoload -Uz async && async + + add-zsh-hook precmd prompt_pure_precmd + add-zsh-hook preexec prompt_pure_preexec + + zstyle ':vcs_info:*' enable git + zstyle ':vcs_info:*' use-simple true + # only export two msg variables from vcs_info + zstyle ':vcs_info:*' max-exports 2 + # vcs_info_msg_0_ = ' %b' (for branch) + # vcs_info_msg_1_ = 'x%R' git top level (%R), x-prefix prevents creation of a named path (AUTO_NAME_DIRS) + zstyle ':vcs_info:git*' formats ' %b' 'x%R' + zstyle ':vcs_info:git*' actionformats ' %b|%a' 'x%R' + + # if the user has not registered a custom zle widget for clear-screen, + # override the builtin one so that the preprompt is displayed correctly when + # ^L is issued. + if [[ $widgets[clear-screen] == 'builtin' ]]; then + zle -N clear-screen prompt_pure_clear_screen + fi + + # register custom function for vim-mode + zle -N zle-keymap-select prompt_purer_vim_mode + + # show username@host if logged in through SSH + [[ "$SSH_CONNECTION" != '' ]] && prompt_pure_username=' %F{242}%n@%m%f' + + # show username@host if root, with username in white + [[ $UID -eq 0 ]] && prompt_pure_username=' %F{white}%n%f%F{242}@%m%f' + + # create prompt + prompt_pure_preprompt_render 'precmd' +} + +prompt_pure_setup "$@" diff --git a/base/.zsh/stack.zsh b/base/.zsh/stack.zsh new file mode 100644 index 0000000..444b88d --- /dev/null +++ b/base/.zsh/stack.zsh @@ -0,0 +1,3 @@ +DIRSTACKSIZE=8 +setopt autocd autopushd pushdminus pushdsilent pushdtohome +alias dh='dirs -v' -- cgit v1.2.3-70-g09d2