├── .editorconfig ├── .gitattributes ├── .github └── issue_template.md ├── arch └── PKGBUILD ├── async.zsh ├── license ├── package-lock.json ├── package.json ├── pure.plugin.zsh ├── pure.zsh ├── readme.md ├── screenshot-title-cmd.png └── screenshot.png /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [package.json] 11 | indent_style = space 12 | indent_size = 2 13 | 14 | [*.md] 15 | trim_trailing_whitespace = false 16 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | -------------------------------------------------------------------------------- /.github/issue_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ### General information 4 | 5 | - Pure version: 1.x.x 6 | - ZSH version: 5.x.x 7 | - Terminal program & version: 8 | - Operating system: 9 | - ZSH framework: 10 | 11 | I have: 12 | - [ ] Tested with another terminal program and can reproduce the issue: 13 | - [ ] Followed the [Integration](https://github.com/sindresorhus/pure#integration) instructions for my framework 14 | 15 | ### Problem description 16 | 17 | 18 | ### Reproduction steps 19 | 20 | 1. 21 | 2. 22 | 3. 23 | 24 | ### My `.zshrc`: 25 | 26 | 30 | 31 | ```shell 32 | autoload -U promptinit; promptinit 33 | prompt pure 34 | ``` 35 | -------------------------------------------------------------------------------- /arch/PKGBUILD: -------------------------------------------------------------------------------- 1 | # Author: Sindre Sorhus 2 | # Maintainer: Pat Brisbin 3 | # Contributor: Emil Falk 4 | pkgname=zsh-pure-prompt-git 5 | pkgver=r61.7d3b317 6 | pkgrel=1 7 | pkgdesc='A minimal and pure prompt for zsh.' 8 | arch=('any') 9 | url='https://github.com/sindresorhus/pure' 10 | license=('MIT') 11 | depends=('zsh' 'git') 12 | source=("$pkgname::git://github.com/sindresorhus/pure.git") 13 | sha256sums=('SKIP') 14 | 15 | pkgver() { 16 | cd $srcdir/$pkgname 17 | printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)" 18 | } 19 | 20 | package() { 21 | cd $srcdir/$pkgname 22 | install -Dm644 pure.zsh \ 23 | "$pkgdir/usr/share/zsh/functions/Prompts/prompt_pure_setup" 24 | install -Dm644 async.zsh \ 25 | "$pkgdir/usr/share/zsh/functions/async" 26 | } 27 | -------------------------------------------------------------------------------- /async.zsh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env zsh 2 | 3 | # 4 | # zsh-async 5 | # 6 | # version: 1.5.0 7 | # author: Mathias Fredriksson 8 | # url: https://github.com/mafredri/zsh-async 9 | # 10 | 11 | # Produce debug output from zsh-async when set to 1. 12 | ASYNC_DEBUG=${ASYNC_DEBUG:-0} 13 | 14 | # Wrapper for jobs executed by the async worker, gives output in parseable format with execution time 15 | _async_job() { 16 | # Disable xtrace as it would mangle the output. 17 | setopt localoptions noxtrace 18 | 19 | # Store start time as double precision (+E disables scientific notation) 20 | float -F duration=$EPOCHREALTIME 21 | 22 | # Run the command and capture both stdout (`eval`) and stderr (`cat`) in 23 | # separate subshells. When the command is complete, we grab write lock 24 | # (mutex token) and output everything except stderr inside the command 25 | # block, after the command block has completed, the stdin for `cat` is 26 | # closed, causing stderr to be appended with a $'\0' at the end to mark the 27 | # end of output from this job. 28 | local stdout stderr ret tok 29 | { 30 | stdout=$(eval "$@") 31 | ret=$? 32 | duration=$(( EPOCHREALTIME - duration )) # Calculate duration. 33 | 34 | # Grab mutex lock, stalls until token is available. 35 | read -r -k 1 -p tok || exit 1 36 | 37 | # Return output ( ). 38 | print -r -n - ${(q)1} $ret ${(q)stdout} $duration 39 | } 2> >(stderr=$(cat) && print -r -n - " "${(q)stderr}$'\0') 40 | 41 | # Unlock mutex by inserting a token. 42 | print -n -p $tok 43 | } 44 | 45 | # The background worker manages all tasks and runs them without interfering with other processes 46 | _async_worker() { 47 | # Reset all options to defaults inside async worker. 48 | emulate -R zsh 49 | 50 | # Make sure monitor is unset to avoid printing the 51 | # pids of child processes. 52 | unsetopt monitor 53 | 54 | # Redirect stderr to `/dev/null` in case unforseen errors produced by the 55 | # worker. For example: `fork failed: resource temporarily unavailable`. 56 | # Some older versions of zsh might also print malloc errors (know to happen 57 | # on at least zsh 5.0.2 and 5.0.8) likely due to kill signals. 58 | exec 2>/dev/null 59 | 60 | # When a zpty is deleted (using -d) all the zpty instances created before 61 | # the one being deleted receive a SIGHUP, unless we catch it, the async 62 | # worker would simply exit (stop working) even though visible in the list 63 | # of zpty's (zpty -L). 64 | TRAPHUP() { 65 | return 0 # Return 0, indicating signal was handled. 66 | } 67 | 68 | local -A storage 69 | local unique=0 70 | local notify_parent=0 71 | local parent_pid=0 72 | local coproc_pid=0 73 | local processing=0 74 | 75 | local -a zsh_hooks zsh_hook_functions 76 | zsh_hooks=(chpwd periodic precmd preexec zshexit zshaddhistory) 77 | zsh_hook_functions=(${^zsh_hooks}_functions) 78 | unfunction $zsh_hooks &>/dev/null # Deactivate all zsh hooks inside the worker. 79 | unset $zsh_hook_functions # And hooks with registered functions. 80 | unset zsh_hooks zsh_hook_functions # Cleanup. 81 | 82 | child_exit() { 83 | local -a pids 84 | pids=(${${(v)jobstates##*:*:}%\=*}) 85 | 86 | # If coproc (cat) is the only child running, we close it to avoid 87 | # leaving it running indefinitely and cluttering the process tree. 88 | if (( ! processing )) && [[ $#pids = 1 ]] && [[ $coproc_pid = $pids[1] ]]; then 89 | coproc : 90 | coproc_pid=0 91 | fi 92 | 93 | # On older version of zsh (pre 5.2) we notify the parent through a 94 | # SIGWINCH signal because `zpty` did not return a file descriptor (fd) 95 | # prior to that. 96 | if (( notify_parent )); then 97 | # We use SIGWINCH for compatibility with older versions of zsh 98 | # (pre 5.1.1) where other signals (INFO, ALRM, USR1, etc.) could 99 | # cause a deadlock in the shell under certain circumstances. 100 | kill -WINCH $parent_pid 101 | fi 102 | } 103 | 104 | # Register a SIGCHLD trap to handle the completion of child processes. 105 | trap child_exit CHLD 106 | 107 | # Process option parameters passed to worker 108 | while getopts "np:u" opt; do 109 | case $opt in 110 | n) notify_parent=1;; 111 | p) parent_pid=$OPTARG;; 112 | u) unique=1;; 113 | esac 114 | done 115 | 116 | killjobs() { 117 | local tok 118 | local -a pids 119 | pids=(${${(v)jobstates##*:*:}%\=*}) 120 | 121 | # No need to send SIGHUP if no jobs are running. 122 | (( $#pids == 0 )) && continue 123 | (( $#pids == 1 )) && [[ $coproc_pid = $pids[1] ]] && continue 124 | 125 | # Grab lock to prevent half-written output in case a child 126 | # process is in the middle of writing to stdin during kill. 127 | (( coproc_pid )) && read -r -k 1 -p tok 128 | 129 | kill -HUP -$$ # Send to entire process group. 130 | coproc : # Quit coproc. 131 | coproc_pid=0 # Reset pid. 132 | } 133 | 134 | local request 135 | local -a cmd 136 | while :; do 137 | # Wait for jobs sent by async_job. 138 | read -r -d $'\0' request || { 139 | # Since we handle SIGHUP above (and thus do not know when `zpty -d`) 140 | # occurs, a failure to read probably indicates that stdin has 141 | # closed. This is why we propagate the signal to all children and 142 | # exit manually. 143 | kill -HUP -$$ # Send SIGHUP to all jobs. 144 | exit 0 145 | } 146 | 147 | # Check for non-job commands sent to worker 148 | case $request in 149 | _unset_trap) notify_parent=0; continue;; 150 | _killjobs) killjobs; continue;; 151 | esac 152 | 153 | # Parse the request using shell parsing (z) to allow commands 154 | # to be parsed from single strings and multi-args alike. 155 | cmd=("${(z)request}") 156 | 157 | # Name of the job (first argument). 158 | local job=$cmd[1] 159 | 160 | # If worker should perform unique jobs 161 | if (( unique )); then 162 | # Check if a previous job is still running, if yes, let it finnish 163 | for pid in ${${(v)jobstates##*:*:}%\=*}; do 164 | if [[ ${storage[$job]} == $pid ]]; then 165 | continue 2 166 | fi 167 | done 168 | fi 169 | 170 | # Guard against closing coproc from trap before command has started. 171 | processing=1 172 | 173 | # Because we close the coproc after the last job has completed, we must 174 | # recreate it when there are no other jobs running. 175 | if (( ! coproc_pid )); then 176 | # Use coproc as a mutex for synchronized output between children. 177 | coproc cat 178 | coproc_pid="$!" 179 | # Insert token into coproc 180 | print -n -p "t" 181 | fi 182 | 183 | # Run job in background, completed jobs are printed to stdout. 184 | _async_job $cmd & 185 | # Store pid because zsh job manager is extremely unflexible (show jobname as non-unique '$job')... 186 | storage[$job]="$!" 187 | 188 | processing=0 # Disable guard. 189 | done 190 | } 191 | 192 | # 193 | # Get results from finnished jobs and pass it to the to callback function. This is the only way to reliably return the 194 | # job name, return code, output and execution time and with minimal effort. 195 | # 196 | # usage: 197 | # async_process_results 198 | # 199 | # callback_function is called with the following parameters: 200 | # $1 = job name, e.g. the function passed to async_job 201 | # $2 = return code 202 | # $3 = resulting stdout from execution 203 | # $4 = execution time, floating point e.g. 2.05 seconds 204 | # $5 = resulting stderr from execution 205 | # 206 | async_process_results() { 207 | setopt localoptions noshwordsplit 208 | 209 | local worker=$1 210 | local callback=$2 211 | local caller=$3 212 | local -a items 213 | local null=$'\0' data 214 | integer -l len pos num_processed 215 | 216 | typeset -gA ASYNC_PROCESS_BUFFER 217 | 218 | # Read output from zpty and parse it if available. 219 | while zpty -r -t $worker data 2>/dev/null; do 220 | ASYNC_PROCESS_BUFFER[$worker]+=$data 221 | len=${#ASYNC_PROCESS_BUFFER[$worker]} 222 | pos=${ASYNC_PROCESS_BUFFER[$worker][(i)$null]} # Get index of NULL-character (delimiter). 223 | 224 | # Keep going until we find a NULL-character. 225 | if (( ! len )) || (( pos > len )); then 226 | continue 227 | fi 228 | 229 | while (( pos <= len )); do 230 | # Take the content from the beginning, until the NULL-character and 231 | # perform shell parsing (z) and unquoting (Q) as an array (@). 232 | items=("${(@Q)${(z)ASYNC_PROCESS_BUFFER[$worker][1,$pos-1]}}") 233 | 234 | # Remove the extracted items from the buffer. 235 | ASYNC_PROCESS_BUFFER[$worker]=${ASYNC_PROCESS_BUFFER[$worker][$pos+1,$len]} 236 | 237 | if (( $#items == 5 )); then 238 | $callback "${(@)items}" # Send all parsed items to the callback. 239 | else 240 | # In case of corrupt data, invoke callback with *async* as job 241 | # name, non-zero exit status and an error message on stderr. 242 | $callback "async" 1 "" 0 "$0:$LINENO: error: bad format, got ${#items} items (${(@q)items})" 243 | fi 244 | 245 | (( num_processed++ )) 246 | 247 | len=${#ASYNC_PROCESS_BUFFER[$worker]} 248 | if (( len > 1 )); then 249 | pos=${ASYNC_PROCESS_BUFFER[$worker][(i)$null]} # Get index of NULL-character (delimiter). 250 | fi 251 | done 252 | done 253 | 254 | (( num_processed )) && return 0 255 | 256 | # Avoid printing exit value when `setopt printexitvalue` is active.` 257 | [[ $caller = trap || $caller = watcher ]] && return 0 258 | 259 | # No results were processed 260 | return 1 261 | } 262 | 263 | # Watch worker for output 264 | _async_zle_watcher() { 265 | setopt localoptions noshwordsplit 266 | typeset -gA ASYNC_PTYS ASYNC_CALLBACKS 267 | local worker=$ASYNC_PTYS[$1] 268 | local callback=$ASYNC_CALLBACKS[$worker] 269 | 270 | if [[ -n $callback ]]; then 271 | async_process_results $worker $callback watcher 272 | fi 273 | } 274 | 275 | # 276 | # Start a new asynchronous job on specified worker, assumes the worker is running. 277 | # 278 | # usage: 279 | # async_job [] 280 | # 281 | async_job() { 282 | setopt localoptions noshwordsplit 283 | 284 | local worker=$1; shift 285 | 286 | local -a cmd 287 | cmd=("$@") 288 | if (( $#cmd > 1 )); then 289 | cmd=(${(q)cmd}) # Quote special characters in multi argument commands. 290 | fi 291 | 292 | zpty -w $worker $cmd$'\0' 293 | } 294 | 295 | # This function traps notification signals and calls all registered callbacks 296 | _async_notify_trap() { 297 | setopt localoptions noshwordsplit 298 | 299 | for k in ${(k)ASYNC_CALLBACKS}; do 300 | async_process_results $k ${ASYNC_CALLBACKS[$k]} trap 301 | done 302 | } 303 | 304 | # 305 | # Register a callback for completed jobs. As soon as a job is finnished, async_process_results will be called with the 306 | # specified callback function. This requires that a worker is initialized with the -n (notify) option. 307 | # 308 | # usage: 309 | # async_register_callback 310 | # 311 | async_register_callback() { 312 | setopt localoptions noshwordsplit nolocaltraps 313 | 314 | typeset -gA ASYNC_CALLBACKS 315 | local worker=$1; shift 316 | 317 | ASYNC_CALLBACKS[$worker]="$*" 318 | 319 | # Enable trap when the ZLE watcher is unavailable, allows 320 | # workers to notify (via -n) when a job is done. 321 | if [[ ! -o interactive ]] || [[ ! -o zle ]]; then 322 | trap '_async_notify_trap' WINCH 323 | fi 324 | } 325 | 326 | # 327 | # Unregister the callback for a specific worker. 328 | # 329 | # usage: 330 | # async_unregister_callback 331 | # 332 | async_unregister_callback() { 333 | typeset -gA ASYNC_CALLBACKS 334 | 335 | unset "ASYNC_CALLBACKS[$1]" 336 | } 337 | 338 | # 339 | # Flush all current jobs running on a worker. This will terminate any and all running processes under the worker, use 340 | # with caution. 341 | # 342 | # usage: 343 | # async_flush_jobs 344 | # 345 | async_flush_jobs() { 346 | setopt localoptions noshwordsplit 347 | 348 | local worker=$1; shift 349 | 350 | # Check if the worker exists 351 | zpty -t $worker &>/dev/null || return 1 352 | 353 | # Send kill command to worker 354 | async_job $worker "_killjobs" 355 | 356 | # Clear the zpty buffer. 357 | local junk 358 | if zpty -r -t $worker junk '*'; then 359 | (( ASYNC_DEBUG )) && print -n "async_flush_jobs $worker: ${(V)junk}" 360 | while zpty -r -t $worker junk '*'; do 361 | (( ASYNC_DEBUG )) && print -n "${(V)junk}" 362 | done 363 | (( ASYNC_DEBUG )) && print 364 | fi 365 | 366 | # Finally, clear the process buffer in case of partially parsed responses. 367 | typeset -gA ASYNC_PROCESS_BUFFER 368 | unset "ASYNC_PROCESS_BUFFER[$worker]" 369 | } 370 | 371 | # 372 | # Start a new async worker with optional parameters, a worker can be told to only run unique tasks and to notify a 373 | # process when tasks are complete. 374 | # 375 | # usage: 376 | # async_start_worker [-u] [-n] [-p ] 377 | # 378 | # opts: 379 | # -u unique (only unique job names can run) 380 | # -n notify through SIGWINCH signal 381 | # -p pid to notify (defaults to current pid) 382 | # 383 | async_start_worker() { 384 | setopt localoptions noshwordsplit 385 | 386 | local worker=$1; shift 387 | zpty -t $worker &>/dev/null && return 388 | 389 | typeset -gA ASYNC_PTYS 390 | typeset -h REPLY 391 | typeset has_xtrace=0 392 | 393 | # Make sure async worker is started without xtrace 394 | # (the trace output interferes with the worker). 395 | [[ -o xtrace ]] && { 396 | has_xtrace=1 397 | unsetopt xtrace 398 | } 399 | 400 | if (( ! ASYNC_ZPTY_RETURNS_FD )) && [[ -o interactive ]] && [[ -o zle ]]; then 401 | # When zpty doesn't return a file descriptor (on older versions of zsh) 402 | # we try to guess it anyway. 403 | integer -l zptyfd 404 | exec {zptyfd}>&1 # Open a new file descriptor (above 10). 405 | exec {zptyfd}>&- # Close it so it's free to be used by zpty. 406 | fi 407 | 408 | zpty -b $worker _async_worker -p $$ $@ || { 409 | async_stop_worker $worker 410 | return 1 411 | } 412 | 413 | # Re-enable it if it was enabled, for debugging. 414 | (( has_xtrace )) && setopt xtrace 415 | 416 | if [[ $ZSH_VERSION < 5.0.8 ]]; then 417 | # For ZSH versions older than 5.0.8 we delay a bit to give 418 | # time for the worker to start before issuing commands, 419 | # otherwise it will not be ready to receive them. 420 | sleep 0.001 421 | fi 422 | 423 | if [[ -o interactive ]] && [[ -o zle ]]; then 424 | if (( ! ASYNC_ZPTY_RETURNS_FD )); then 425 | REPLY=$zptyfd # Use the guessed value for the file desciptor. 426 | fi 427 | 428 | ASYNC_PTYS[$REPLY]=$worker # Map the file desciptor to the worker. 429 | zle -F $REPLY _async_zle_watcher # Register the ZLE handler. 430 | 431 | # Disable trap in favor of ZLE handler when notify is enabled (-n). 432 | async_job $worker _unset_trap 433 | fi 434 | } 435 | 436 | # 437 | # Stop one or multiple workers that are running, all unfetched and incomplete work will be lost. 438 | # 439 | # usage: 440 | # async_stop_worker [] 441 | # 442 | async_stop_worker() { 443 | setopt localoptions noshwordsplit 444 | 445 | local ret=0 446 | for worker in $@; do 447 | # Find and unregister the zle handler for the worker 448 | for k v in ${(@kv)ASYNC_PTYS}; do 449 | if [[ $v == $worker ]]; then 450 | zle -F $k 451 | unset "ASYNC_PTYS[$k]" 452 | fi 453 | done 454 | async_unregister_callback $worker 455 | zpty -d $worker 2>/dev/null || ret=$? 456 | 457 | # Clear any partial buffers. 458 | typeset -gA ASYNC_PROCESS_BUFFER 459 | unset "ASYNC_PROCESS_BUFFER[$worker]" 460 | done 461 | 462 | return $ret 463 | } 464 | 465 | # 466 | # Initialize the required modules for zsh-async. To be called before using the zsh-async library. 467 | # 468 | # usage: 469 | # async_init 470 | # 471 | async_init() { 472 | (( ASYNC_INIT_DONE )) && return 473 | ASYNC_INIT_DONE=1 474 | 475 | zmodload zsh/zpty 476 | zmodload zsh/datetime 477 | 478 | # Check if zsh/zpty returns a file descriptor or not, 479 | # shell must also be interactive with zle enabled. 480 | ASYNC_ZPTY_RETURNS_FD=0 481 | [[ -o interactive ]] && [[ -o zle ]] && { 482 | typeset -h REPLY 483 | zpty _async_test : 484 | (( REPLY )) && ASYNC_ZPTY_RETURNS_FD=1 485 | zpty -d _async_test 486 | } 487 | } 488 | 489 | async() { 490 | async_init 491 | } 492 | 493 | async "$@" 494 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Sindre Sorhus (sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "purer-prompt", 3 | "version": "1.6.1", 4 | "lockfileVersion": 1 5 | } 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "purer-prompt", 3 | "version": "1.6.1", 4 | "description": "A pretty one-line ZSH prompt based on Pure.", 5 | "license": "MIT", 6 | "repository": "dfurnes/purer", 7 | "author": { 8 | "name": "David Furnes", 9 | "email": "david@dfurnes.com", 10 | "url": "dfurnes.com" 11 | }, 12 | "engines": { 13 | "node": ">=0.10.0" 14 | }, 15 | "scripts": { 16 | "postinstall": "PURER_DEST=/usr/local/share/zsh/site-functions npm run --silent postinstall-link && exit 0; PURER_DEST=\"$PWD/functions\" npm run postinstall-link && npm run postinstall-fail-instructions", 17 | "postinstall-link": "mkdir -p \"$PURER_DEST\" && ln -sf \"$PWD/pure.zsh\" \"$PURER_DEST/prompt_purer_setup\" && ln -sf \"$PWD/async.zsh\" \"$PURER_DEST/async\"", 18 | "postinstall-fail-instructions": "echo \"ERROR: Could not automagically symlink the prompt. Either:\\n1. Check out the readme on how to do it manually: https://github.com/sindresorhus/pure#manually\\n2. Or add the following to your \\`.zshrc\\`:\\n\\n fpath+=(\\$fpath '$PWD/functions')\"" 19 | }, 20 | "files": [ 21 | "pure.zsh", 22 | "async.zsh" 23 | ], 24 | "keywords": [ 25 | "zsh", 26 | "zshell", 27 | "sh", 28 | "shell", 29 | "bash", 30 | "pure", 31 | "prompt", 32 | "theme", 33 | "git", 34 | "async", 35 | "fast", 36 | "minimal", 37 | "pretty" 38 | ] 39 | } 40 | -------------------------------------------------------------------------------- /pure.plugin.zsh: -------------------------------------------------------------------------------- 1 | pure.zsh -------------------------------------------------------------------------------- /pure.zsh: -------------------------------------------------------------------------------- 1 | # Pure 2 | # by Sindre Sorhus 3 | # https://github.com/sindresorhus/pure 4 | # MIT License 5 | 6 | # For my own and others sanity 7 | # git: 8 | # %b => current branch 9 | # %a => current action (rebase/merge) 10 | # prompt: 11 | # %F => color dict 12 | # %f => reset color 13 | # %~ => current path 14 | # %* => time 15 | # %n => username 16 | # %m => shortname host 17 | # %(?..) => prompt conditional - %(condition.true.false) 18 | # terminal codes: 19 | # \e7 => save cursor position 20 | # \e[2A => move cursor 2 lines up 21 | # \e[1G => go to position 1 in terminal 22 | # \e8 => restore cursor position 23 | # \e[K => clears everything after the cursor on the current line 24 | # \e[2K => clear everything on the current line 25 | 26 | PURER_PROMPT_COMMAND_COUNT=0 27 | STATUS_COLOR='cyan' 28 | 29 | # turns seconds into human readable time 30 | # 165392 => 1d 21h 56m 32s 31 | # https://github.com/sindresorhus/pretty-time-zsh 32 | prompt_pure_human_time_to_var() { 33 | local human=" [" total_seconds=$1 var=$2 34 | local days=$(( total_seconds / 60 / 60 / 24 )) 35 | local hours=$(( total_seconds / 60 / 60 % 24 )) 36 | local minutes=$(( total_seconds / 60 % 60 )) 37 | local seconds=$(( total_seconds % 60 )) 38 | (( days > 0 )) && human+="${days}d " 39 | (( hours > 0 )) && human+="${hours}h " 40 | (( minutes > 0 )) && human+="${minutes}m " 41 | human+="${seconds}s]" 42 | 43 | # store human readable time in variable as specified by caller 44 | typeset -g "${var}"="${human}" 45 | } 46 | 47 | # stores (into prompt_pure_cmd_exec_time) the exec time of the last command if set threshold was exceeded 48 | prompt_pure_check_cmd_exec_time() { 49 | integer elapsed 50 | (( elapsed = EPOCHSECONDS - ${prompt_pure_cmd_timestamp:-$EPOCHSECONDS} )) 51 | prompt_pure_cmd_exec_time= 52 | (( elapsed > ${PURE_CMD_MAX_EXEC_TIME:=5} )) && { 53 | prompt_pure_human_time_to_var $elapsed "prompt_pure_cmd_exec_time" 54 | } 55 | } 56 | 57 | prompt_pure_clear_screen() { 58 | # enable output to terminal 59 | zle -I 60 | # clear screen and move cursor to (0, 0) 61 | print -n '\e[2J\e[0;0H' 62 | # reset command count to zero so we don't start with a blank line 63 | PURER_PROMPT_COMMAND_COUNT=0 64 | # print preprompt 65 | prompt_pure_preprompt_render precmd 66 | } 67 | 68 | # set STATUS_COLOR: cyan for "insert", green for "normal" mode. 69 | prompt_purer_vim_mode() { 70 | STATUS_COLOR="${${KEYMAP/vicmd/green}/(main|viins)/cyan}" 71 | prompt_pure_preprompt_render 72 | } 73 | 74 | prompt_pure_set_title() { 75 | # emacs terminal does not support settings the title 76 | (( ${+EMACS} )) && return 77 | 78 | # tell the terminal we are setting the title 79 | print -n '\e]0;' 80 | # show hostname if connected through ssh 81 | [[ -n $SSH_CONNECTION ]] && print -Pn '(%m) ' 82 | case $1 in 83 | expand-prompt) 84 | print -Pn $2;; 85 | ignore-escape) 86 | print -rn $2;; 87 | esac 88 | # end set title 89 | print -n '\a' 90 | } 91 | 92 | prompt_pure_preexec() { 93 | # attempt to detect and prevent prompt_pure_async_git_fetch from interfering with user initiated git or hub fetch 94 | [[ $2 =~ (git|hub)\ .*(pull|fetch) ]] && async_flush_jobs 'prompt_pure' 95 | 96 | prompt_pure_cmd_timestamp=$EPOCHSECONDS 97 | 98 | # shows the current dir and executed command in the title while a process is active 99 | prompt_pure_set_title 'ignore-escape' "$PWD:t: $2" 100 | 101 | # Disallow python virtualenv from updating the prompt, set it to 12 if 102 | # untouched by the user to indicate that Pure modified it. Here we use 103 | # magic number 12, same as in psvar. 104 | export VIRTUAL_ENV_DISABLE_PROMPT=${VIRTUAL_ENV_DISABLE_PROMPT:-12} 105 | } 106 | 107 | # string length ignoring ansi escapes 108 | prompt_pure_string_length_to_var() { 109 | local str=$1 var=$2 length 110 | # perform expansion on str and check length 111 | length=$(( ${#${(S%%)str//(\%([KF1]|)\{*\}|\%[Bbkf])}} )) 112 | 113 | # store string length in variable as specified by caller 114 | typeset -g "${var}"="${length}" 115 | } 116 | 117 | prompt_pure_preprompt_render() { 118 | # store the current prompt_subst setting so that it can be restored later 119 | local prompt_subst_status=$options[prompt_subst] 120 | 121 | # make sure prompt_subst is unset to prevent parameter expansion in preprompt 122 | setopt local_options no_prompt_subst 123 | 124 | # check that no command is currently running, the preprompt will otherwise be rendered in the wrong place 125 | [[ -n ${prompt_pure_cmd_timestamp+x} && "$1" != "precmd" ]] && return 126 | 127 | # set color for git branch/dirty status, change color if dirty checking has been delayed 128 | local git_color=242 129 | [[ -n ${prompt_pure_git_last_dirty_check_timestamp+x} ]] && git_color=red 130 | 131 | # construct preprompt 132 | local preprompt="" 133 | 134 | 135 | # add a newline between commands 136 | FIRST_COMMAND_THRESHOLD=1 137 | if [[ "$PURER_PROMPT_COMMAND_COUNT" -gt "$FIRST_COMMAND_THRESHOLD" ]]; then 138 | preprompt+=$'\n' 139 | fi 140 | 141 | local symbol_color="%(?.${PURE_PROMPT_SYMBOL_COLOR:-magenta}.red)" 142 | local path_formatting="${PURE_PROMPT_PATH_FORMATTING:-%c}" 143 | 144 | # show background jobs 145 | preprompt+="%(1j.%F{242}%j %f.)" 146 | # show virtual env 147 | preprompt+="%(12V.%F{242}%12v%f .)" 148 | # begin with symbol, colored by previous command exit code 149 | preprompt+="%F{$symbol_color}${PURE_PROMPT_SYMBOL:-❯}%f " 150 | # directory, colored by vim status 151 | preprompt+="%B%F{$STATUS_COLOR}$path_formatting%f%b" 152 | # git info 153 | preprompt+="%F{$git_color}${vcs_info_msg_0_}${prompt_pure_git_dirty}%f" 154 | # git pull/push arrows 155 | preprompt+="%F{cyan}${prompt_pure_git_arrows}%f" 156 | # username and machine if applicable 157 | preprompt+=$prompt_pure_username 158 | # execution time 159 | preprompt+="%B%F{242}${prompt_pure_cmd_exec_time}%f%b" 160 | 161 | preprompt+=" " 162 | 163 | # make sure prompt_pure_last_preprompt is a global array 164 | typeset -g -a prompt_pure_last_preprompt 165 | 166 | PROMPT="$preprompt" 167 | 168 | # if executing through precmd, do not perform fancy terminal editing 169 | if [[ "$1" != "precmd" ]]; then 170 | # only redraw if the expanded preprompt has changed 171 | # [[ "${prompt_pure_last_preprompt[2]}" != "${(S%%)preprompt}" ]] || return 172 | 173 | # redraw prompt (also resets cursor position) 174 | zle && zle .reset-prompt 175 | 176 | setopt no_prompt_subst 177 | fi 178 | 179 | # store both unexpanded and expanded preprompt for comparison 180 | prompt_pure_last_preprompt=("$preprompt" "${(S%%)preprompt}") 181 | } 182 | 183 | prompt_pure_precmd() { 184 | # check exec time and store it in a variable 185 | prompt_pure_check_cmd_exec_time 186 | 187 | # by making sure that prompt_pure_cmd_timestamp is defined here the async functions are prevented from interfering 188 | # with the initial preprompt rendering 189 | prompt_pure_cmd_timestamp= 190 | 191 | # shows the full path in the title 192 | prompt_pure_set_title 'expand-prompt' '%~' 193 | 194 | # get vcs info 195 | vcs_info 196 | 197 | # preform async git dirty check and fetch 198 | prompt_pure_async_tasks 199 | 200 | # Check if we should display the virtual env, we use a sufficiently high 201 | # index of psvar (12) here to avoid collisions with user defined entries. 202 | psvar[12]= 203 | # When VIRTUAL_ENV_DISABLE_PROMPT is empty, it was unset by the user and 204 | # Pure should take back control. 205 | if [[ -n $VIRTUAL_ENV ]] && [[ -z $VIRTUAL_ENV_DISABLE_PROMPT || $VIRTUAL_ENV_DISABLE_PROMPT = 12 ]]; then 206 | psvar[12]="${VIRTUAL_ENV:t}" 207 | export VIRTUAL_ENV_DISABLE_PROMPT=12 208 | fi 209 | 210 | # print the preprompt 211 | prompt_pure_preprompt_render "precmd" 212 | 213 | # Increment command counter 214 | PURER_PROMPT_COMMAND_COUNT=$((PURER_PROMPT_COMMAND_COUNT+1)) 215 | 216 | # print the preprompt 217 | prompt_pure_preprompt_render "precmd" 218 | 219 | # remove the prompt_pure_cmd_timestamp, indicating that precmd has completed 220 | unset prompt_pure_cmd_timestamp 221 | } 222 | 223 | # fastest possible way to check if repo is dirty 224 | prompt_pure_async_git_dirty() { 225 | setopt localoptions noshwordsplit 226 | local untracked_dirty=$1 dir=$2 227 | 228 | # use cd -q to avoid side effects of changing directory, e.g. chpwd hooks 229 | builtin cd -q $dir 230 | 231 | if [[ $untracked_dirty = 0 ]]; then 232 | command git diff --no-ext-diff --quiet --exit-code 233 | else 234 | test -z "$(command git status --porcelain --ignore-submodules -unormal)" 235 | fi 236 | 237 | return $? 238 | } 239 | 240 | prompt_pure_async_git_fetch() { 241 | setopt localoptions noshwordsplit 242 | # use cd -q to avoid side effects of changing directory, e.g. chpwd hooks 243 | builtin cd -q $1 244 | 245 | # set GIT_TERMINAL_PROMPT=0 to disable auth prompting for git fetch (git 2.3+) 246 | export GIT_TERMINAL_PROMPT=0 247 | # set ssh BachMode to disable all interactive ssh password prompting 248 | export GIT_SSH_COMMAND=${GIT_SSH_COMMAND:-"ssh -o BatchMode=yes"} 249 | 250 | command git -c gc.auto=0 fetch &>/dev/null || return 1 251 | 252 | # check arrow status after a successful git fetch 253 | prompt_pure_async_git_arrows $1 254 | } 255 | 256 | prompt_pure_async_git_arrows() { 257 | setopt localoptions noshwordsplit 258 | builtin cd -q $1 259 | command git rev-list --left-right --count HEAD...@'{u}' 260 | } 261 | 262 | prompt_pure_async_tasks() { 263 | setopt localoptions noshwordsplit 264 | 265 | # initialize async worker 266 | ((!${prompt_pure_async_init:-0})) && { 267 | async_start_worker "prompt_pure" -u -n 268 | async_register_callback "prompt_pure" prompt_pure_async_callback 269 | prompt_pure_async_init=1 270 | } 271 | 272 | # store working_tree without the "x" prefix 273 | local working_tree="${vcs_info_msg_1_#x}" 274 | 275 | # check if the working tree changed (prompt_pure_current_working_tree is prefixed by "x") 276 | if [[ ${prompt_pure_current_working_tree#x} != $working_tree ]]; then 277 | # stop any running async jobs 278 | async_flush_jobs "prompt_pure" 279 | 280 | # reset git preprompt variables, switching working tree 281 | unset prompt_pure_git_dirty 282 | unset prompt_pure_git_last_dirty_check_timestamp 283 | prompt_pure_git_arrows= 284 | 285 | # set the new working tree and prefix with "x" to prevent the creation of a named path by AUTO_NAME_DIRS 286 | prompt_pure_current_working_tree="x${working_tree}" 287 | fi 288 | 289 | # only perform tasks inside git working tree 290 | [[ -n $working_tree ]] || return 291 | 292 | async_job "prompt_pure" prompt_pure_async_git_arrows $working_tree 293 | 294 | # do not preform git fetch if it is disabled or working_tree == HOME 295 | if (( ${PURE_GIT_PULL:-1} )) && [[ $working_tree != $HOME ]]; then 296 | # tell worker to do a git fetch 297 | async_job "prompt_pure" prompt_pure_async_git_fetch $working_tree 298 | fi 299 | 300 | # if dirty checking is sufficiently fast, tell worker to check it again, or wait for timeout 301 | integer time_since_last_dirty_check=$(( EPOCHSECONDS - ${prompt_pure_git_last_dirty_check_timestamp:-0} )) 302 | if (( time_since_last_dirty_check > ${PURE_GIT_DELAY_DIRTY_CHECK:-1800} )); then 303 | unset prompt_pure_git_last_dirty_check_timestamp 304 | # check check if there is anything to pull 305 | async_job "prompt_pure" prompt_pure_async_git_dirty ${PURE_GIT_UNTRACKED_DIRTY:-1} $working_tree 306 | fi 307 | } 308 | 309 | prompt_pure_check_git_arrows() { 310 | setopt localoptions noshwordsplit 311 | local arrows left=${1:-0} right=${2:-0} 312 | 313 | (( right > 0 )) && arrows+=${PURE_GIT_DOWN_ARROW:-⇣} 314 | (( left > 0 )) && arrows+=${PURE_GIT_UP_ARROW:-⇡} 315 | 316 | [[ -n $arrows ]] || return 317 | typeset -g REPLY=" $arrows" 318 | } 319 | 320 | prompt_pure_async_callback() { 321 | setopt localoptions noshwordsplit 322 | local job=$1 code=$2 output=$3 exec_time=$4 323 | 324 | case $job in 325 | prompt_pure_async_git_dirty) 326 | local prev_dirty=$prompt_pure_git_dirty 327 | if (( code == 0 )); then 328 | prompt_pure_git_dirty= 329 | else 330 | prompt_pure_git_dirty="*" 331 | fi 332 | 333 | [[ $prev_dirty != $prompt_pure_git_dirty ]] && prompt_pure_preprompt_render 334 | 335 | # When prompt_pure_git_last_dirty_check_timestamp is set, the git info is displayed in a different color. 336 | # To distinguish between a "fresh" and a "cached" result, the preprompt is rendered before setting this 337 | # variable. Thus, only upon next rendering of the preprompt will the result appear in a different color. 338 | (( $exec_time > 2 )) && prompt_pure_git_last_dirty_check_timestamp=$EPOCHSECONDS 339 | ;; 340 | prompt_pure_async_git_fetch|prompt_pure_async_git_arrows) 341 | # prompt_pure_async_git_fetch executes prompt_pure_async_git_arrows 342 | # after a successful fetch. 343 | if (( code == 0 )); then 344 | local REPLY 345 | prompt_pure_check_git_arrows ${(ps:\t:)output} 346 | if [[ $prompt_pure_git_arrows != $REPLY ]]; then 347 | prompt_pure_git_arrows=$REPLY 348 | prompt_pure_preprompt_render 349 | fi 350 | fi 351 | ;; 352 | esac 353 | } 354 | 355 | prompt_pure_setup() { 356 | # prevent percentage showing up 357 | # if output doesn't end with a newline 358 | export PROMPT_EOL_MARK='' 359 | 360 | # prompt_opts=(subst percent) 361 | 362 | # borrowed from promptinit, sets the prompt options in case pure was not 363 | # initialized via promptinit. 364 | # setopt noprompt{bang,cr,percent,subst} "prompt${^prompt_opts[@]}" 365 | 366 | zmodload zsh/datetime 367 | zmodload zsh/zle 368 | zmodload zsh/parameter 369 | 370 | autoload -Uz add-zsh-hook 371 | autoload -Uz vcs_info 372 | autoload -Uz async && async 373 | 374 | add-zsh-hook precmd prompt_pure_precmd 375 | add-zsh-hook preexec prompt_pure_preexec 376 | 377 | zstyle ':vcs_info:*' enable git 378 | zstyle ':vcs_info:*' use-simple true 379 | # only export two msg variables from vcs_info 380 | zstyle ':vcs_info:*' max-exports 2 381 | # vcs_info_msg_0_ = ' %b' (for branch) 382 | # vcs_info_msg_1_ = 'x%R' git top level (%R), x-prefix prevents creation of a named path (AUTO_NAME_DIRS) 383 | zstyle ':vcs_info:git*' formats ' %b' 'x%R' 384 | zstyle ':vcs_info:git*' actionformats ' %b|%a' 'x%R' 385 | 386 | # if the user has not registered a custom zle widget for clear-screen, 387 | # override the builtin one so that the preprompt is displayed correctly when 388 | # ^L is issued. 389 | if [[ $widgets[clear-screen] == 'builtin' ]]; then 390 | zle -N clear-screen prompt_pure_clear_screen 391 | fi 392 | 393 | # register custom function for vim-mode 394 | zle -N zle-line-init prompt_purer_vim_mode 395 | zle -N zle-keymap-select prompt_purer_vim_mode 396 | 397 | # show username@host if logged in through SSH 398 | [[ "$SSH_CONNECTION" != '' ]] && prompt_pure_username=' %F{242}%n@%m%f' 399 | 400 | # show username@host if root, with username in white 401 | [[ $UID -eq 0 ]] && prompt_pure_username=' %F{white}%n%f%F{242}@%m%f' 402 | 403 | # create prompt 404 | prompt_pure_preprompt_render 'precmd' 405 | } 406 | 407 | prompt_pure_setup "$@" 408 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Purer 2 | 3 | > Pretty one-line ZSH prompt based on [@sindresorhus](https://github.)'s [Pure](https://github.com/sindresorhus/pure) 4 | 5 | ![purer](https://cloud.githubusercontent.com/assets/583202/25418314/c3a29bfa-2a18-11e7-8a6f-4c0960ccadfc.png) 6 | 7 | ## Install 8 | 9 | Can be installed with `npm` or [manually](https://github.com/sindresorhus/pure/blob/master/readme.md#manually). Requires Git 2.0.0+ and ZSH 5.2+. 10 | 11 | ```sh 12 | $ npm install --global purer-prompt 13 | ``` 14 | 15 | Initialize the prompt system (if not so already) and choose `purer`: 16 | 17 | ```sh 18 | # .zshrc 19 | autoload -U promptinit; promptinit 20 | prompt purer 21 | ``` 22 | 23 | See [Pure's readme](https://github.com/sindresorhus/pure/blob/master/readme.md#install) for more detailed instructions. 24 | 25 | ## Customization 26 | 27 | Purer supports customization using [Pure's environment variables](https://github.com/sindresorhus/pure#options), plus: 28 | 29 | ### `PURE_PROMPT_SYMBOL_COLOR` 30 | 31 | Defines the prompt symbol color. The default value is `magenta`; you can use any [colour name](https://wiki.archlinux.org/index.php/Zsh#Colors) or [numeric colour code](https://upload.wikimedia.org/wikipedia/commons/1/15/Xterm_256color_chart.svg) (see `zshzle(1)` section [Character Highlighting](http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting).) 32 | 33 | 34 | ### `PURE_PROMPT_PATH_FORMATTING` 35 | 36 | Defines how to display the path. Default value: `%c`. See [Prompt Expansion](http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html) for more. 37 | 38 | ## License 39 | 40 | Purer MIT © [David Furnes](http://dfurnes.com)
41 | Pure MIT © [Sindre Sorhus](http://sindresorhus.com) 42 | -------------------------------------------------------------------------------- /screenshot-title-cmd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DFurnes/purer/9a2172487e286a2f377d0765dd4321c0a69a9bc1/screenshot-title-cmd.png -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DFurnes/purer/9a2172487e286a2f377d0765dd4321c0a69a9bc1/screenshot.png --------------------------------------------------------------------------------