Fixed vim and zsh

This commit is contained in:
2018-04-05 13:06:54 +02:00
parent f9db886bd3
commit 0331f6518a
2009 changed files with 256303 additions and 0 deletions

View File

@ -0,0 +1,15 @@
Prompt
======
Initializes and provides customizable prompt themes.
Images of various prompt themes can be found on the [wiki](https://github.com/Eriner/zim/wiki/Themes).
A list of available prompts can be found by running `prompt -l`.
To test a prompt, simply run `prompt prompt_name_here`.
.zimrc Configuration
--------------------
* `zprompt_theme='eriner'` change 'eriner' to the name of your desired prompt. This will set it as you default prompt.

View File

@ -0,0 +1,57 @@
About
=====
After having used [prompt pure](https://github.com/sindresorhus/pure) for about
a year, I felt that a two-line prompt was not for me. Also not utilizing the
right side of the terminal seemed a missed opportunity. Still there is much to
like: the elapsed time of a process, the coloring of the prompt if the exit
code of the process isn't 0, git integration. So I took "pure", mixed in my
ideas of what a prompt should look like and came up with "lean" - a 1 line
prompt that stays out of your face.
So lean is an evolution of pure, with the following changes:
* Defaults to a very sparse setup, only showing information you need at the
moment.
* Comes with the perfect prompt character. Author went through the entire ASCII
range to find it (and found it pretty quickly!)
* Never displays your username (assuming you know who you are).
* When tmux is active it shows a yellow 't' (I disabled the tmux bar, so this
is some visual indication that tmux is active). If you don't want this
indicator, you can always set `PROMPT_LEAN_TMUX=""` prior to loading this
plugin (or prior to sourcing `zgen`, etc.).
* Show remote host if logged in through SSH.
* All in one line, most stuff in the right prompt, leaving the left prompt nice
and clean
* Shows background jobs (in the left prompt)
* Show (dirty) git repos
* Shortens path if needed (longer then 70% of your screen)
* Uses `PROMPT_LEAN_LEFT` and `PROMPT_LEAN_RIGHT` to allow customization of the left
and/or right side of the prompt.
* For a configurable insertmode indicator, set the `PROMPT_LEAN_VIMODE` and `PROMPT_LEAN_VIMODE_FORMAT`
variables.
`PROMPT_LEAN_VIMODE_FORMAT` defaults to `"%F{red}[NORMAL]%f"`
When lean starts, only 2 characters show on the screen '%' on the left and '~'
on the right. All other info is omitted (like the user and system you are on),
and shown only when needed.
Here is a [screencast](https://asciinema.org/a/d1b5wccq23kglwwhaymoi8z5i)
showing the prompt.
*Note*: for some reason the screencast does not show the space between the '%'
character and the start of the command line. **NOTE** This
[issue](https://github.com/miekg/lean/issues/2) has been fixed.
[![asciicast](https://asciinema.org/a/d1b5wccq23kglwwhaymoi8z5i.png)](https://asciinema.org/a/d1b5wccq23kglwwhaymoi8z5i)
Installation
===========
If you use [zgen](https://github.com/tarjoilija/zgen) you can add the following
to your `~/.zshrc`:
```
zgen load miekg/lean
```
and force reload with `zgen reset && source~/.zshrc`.

View File

@ -0,0 +1 @@
prompt_lean_setup

View File

@ -0,0 +1,139 @@
# lean prompt theme
# by Miek Gieben: https://github.com/miekg/lean
#
# Base on Pure by Sindre Sorhus: https://github.com/sindresorhus/pure
#
# MIT License
PROMPT_LEAN_TMUX=${PROMPT_LEAN_TMUX-"t "}
PROMPT_LEAN_PATH_PERCENT=${PROMPT_LEAN_PATH_PERCENT-60}
prompt_lean_help() {
cat <<'EOF'
This is a one line prompt that tries to stay out of your face. It utilizes
the right side prompt for most information, like the CWD. The left side of
the prompt is only a '%'. The only other information shown on the left are
the jobs numbers of background jobs. When the exit code of a process isn't
zero the prompt turns red. If a process takes more then 5 (default) seconds
to run the total running time is shown in the next prompt.
Configuration:
PROMPT_LEAN_TMUX: used to indicate being in tmux, set to "t ", by default
PROMPT_LEAN_LEFT: executed to allow custom information in the left side
PROMPT_LEAN_RIGHT: executed to allow custom information in the right side
PROMPT_LEAN_VIMODE: used to determine wither or not to display indicator
PROMPT_LEAN_VIMODE_FORMAT: Defaults to "%F{red}[NORMAL]%f"
You can invoke it thus:
prompt lean
EOF
}
# turns seconds into human readable time, 165392 => 1d 21h 56m 32s
prompt_lean_human_time() {
local tmp=$1
local days=$(( tmp / 60 / 60 / 24 ))
local hours=$(( tmp / 60 / 60 % 24 ))
local minutes=$(( tmp / 60 % 60 ))
local seconds=$(( tmp % 60 ))
(( $days > 0 )) && echo -n "${days}d "
(( $hours > 0 )) && echo -n "${hours}h "
(( $minutes > 0 )) && echo -n "${minutes}m "
echo "${seconds}s "
}
# fastest possible way to check if repo is dirty
prompt_lean_git_dirty() {
# check if we're in a git repo
command git rev-parse --is-inside-work-tree &>/dev/null || return
# check if it's dirty
local umode="-uno" #|| local umode="-unormal"
command test -n "$(git status --porcelain --ignore-submodules ${umode} 2>/dev/null | head -100)"
(($? == 0)) && echo ' +'
}
# displays the exec time of the last command if set threshold was exceeded
prompt_lean_cmd_exec_time() {
local stop=$EPOCHSECONDS
local start=${cmd_timestamp:-$stop}
integer elapsed=$stop-$start
(($elapsed > ${PROMPT_LEAN_CMD_MAX_EXEC_TIME:=5})) && prompt_lean_human_time $elapsed
}
prompt_lean_preexec() {
cmd_timestamp=$EPOCHSECONDS
# shows the current dir and executed command in the title when a process is active
print -Pn "\e]0;"
echo -nE "$PWD:t: $2"
print -Pn "\a"
}
prompt_lean_pwd() {
local lean_path="`print -Pn '%~'`"
if (($#lean_path / $COLUMNS.0 * 100 > ${PROMPT_LEAN_PATH_PERCENT:=60})); then
print -Pn '...%2/'
return
fi
print "$lean_path"
}
prompt_lean_precmd() {
vcs_info
rehash
local jobs
local prompt_lean_jobs
unset jobs
for a (${(k)jobstates}) {
j=$jobstates[$a];i="${${(@s,:,)j}[2]}"
jobs+=($a${i//[^+-]/})
}
# print with [ ] and comma separated
prompt_lean_jobs=""
[[ -n $jobs ]] && prompt_lean_jobs="%F{242}["${(j:,:)jobs}"] "
local lean_vimode_default="%F{red}[NORMAL]%f"
#If LEAN_VIMODE is set, set lean_vimode_indicator to either PROMPT_LEAN_VIMOD_FORMAT or a default value
local lean_vimode_indicator="${PROMPT_LEAN_VIMODE:+${PROMPT_LEAN_VIMODE_FORMAT:-${lean_vimode_default}}}"
prompt_lean_vimode="${${KEYMAP/vicmd/$lean_vimode_indicator}/(main|viins)/}"
PROMPT="$prompt_lean_jobs%F{yellow}${prompt_lean_tmux}%f`$PROMPT_LEAN_LEFT`%f%(?.%F{blue}.%B%F{red})%#%f%b "
RPROMPT="%F{yellow}`prompt_lean_cmd_exec_time`%f$prompt_lean_vimode%F{blue}`prompt_lean_pwd`%F{242}$vcs_info_msg_0_`prompt_lean_git_dirty`$prompt_lean_host%f`$PROMPT_LEAN_RIGHT`%f"
unset cmd_timestamp # reset value since `preexec` isn't always triggered
}
function zle-keymap-select {
prompt_lean_precmd
zle reset-prompt
}
prompt_lean_setup() {
prompt_opts=(cr subst percent)
zmodload zsh/datetime
autoload -Uz add-zsh-hook
autoload -Uz vcs_info
[[ "$PROMPT_LEAN_VIMODE" != '' ]] && zle -N zle-keymap-select
add-zsh-hook precmd prompt_lean_precmd
add-zsh-hook preexec prompt_lean_preexec
zstyle ':vcs_info:*' enable git
zstyle ':vcs_info:git*' formats ' %b'
zstyle ':vcs_info:git*' actionformats ' %b|%a'
[[ "$SSH_CONNECTION" != '' ]] && prompt_lean_host=" %F{yellow}%m%f"
[[ "$TMUX" != '' ]] && prompt_lean_tmux=$PROMPT_LEAN_TMUX
return 0
}
prompt_lean_setup "$@"

View File

@ -0,0 +1,4 @@
Shell: bash/zsh
Operating system:
Liquid Prompt version (tag, commit):

View File

@ -0,0 +1,33 @@
nojhan <nojhan@nojhan.net> <johann.dreo@thalesgroup.com>
nojhan <nojhan@nojhan.net> <nojhan@gmail.com>
Alexander Belaev (alexbel) <alexbel@lavabit.com>
Alex Prengere <alexprengere@gmail.com> <alex.prengere@amadeus.com>
Alex Prengere <alexprengere@gmail.com> Alex <alexprengere@gmail.com>
Aurélien Requiem <aurelien@requiem.fr> <aurelien.requiem@loadedtech.com.au>
Aurélien Requiem <aurelien@requiem.fr>
Clément Mathieu <clement@unportant.info>
Christophe Drevet (dr4Ke) <dr4ke@dr4ke.net> <christophe.drevet@cea.fr>
François Schmidts (jaesivsm) <francois.schmidts@gmail.com>
François Schmidts (jaesivsm) <francois.schmidts@gmail.com> <fschmidts@olfeo.com>
François Schmidts (jaesivsm) <francois.schmidts@gmail.com> <jaesivsm>
Frédéric Lepied <flepied@gmail.com>
Étienne Deparis <etienne@depar.is>
Étienne Deparis <etienne@depar.is> <etienne.deparis@umaneti.net>
Felix Chern (dryman) <idryman@gmail.com>
Jean-Sébastien Leroy <jean.sebastien.leroy@gmail.com>
Joris Dedieu <joris@nfrance.com>
Joris Dedieu <joris@nfrance.com> <joris@pontiac3.nfrance.com>
Julien Pecqueur <jpec@julienpecqueur.net>
Julien Pecqueur <jpec@julienpecqueur.net> <jpec80@gmail.com>
Ludovic Rousseau <ludovic.rousseau@gmail.com> <lroussea@370bh2j.(none)>
Matthew Micene (nzwulfin) <nzwulfin@gmail.com>
Nicolas Lacourte <nicolas@dotinfra.fr>
Olivier Dupuis <oj.dupuis@gmail.com>
Ying Li (cyli) <cyli@twistedmatrix.com>
Poil <poil@quake.fr> M.Poil <?@?>
Poil <poil@quake.fr> Poil <?@?>
Thomas Debesse <thomas.debesse@gmail.com>
Rolf Morel (polyphemus) <rolfmorel@gmail.com>
Wilson Maravilha (algaerhythm) <algaerhythm@gmail.com>
Yannack <yannack@gmail.com>
Brad Beyenhof <bbeyenhof@gmail.com> <bbeyenhof@icloud.com>

View File

@ -0,0 +1,208 @@
NEXT
New features:
- Workaround broken .bashrc that export PROMPT_COMMAND (GH #450, #463):
we now unexport it on startup
- Allow to customize the symbol before the path that shows if the
directory is writable: LP_MARK_PERM (GitHub #430, #484)
Bug fixes:
- Fix regression in LP_ENABLE_FQDN implementation (GitHub #472)
- Fix LP_COLOR_HOST_HASH on SunOS (GitHub #461, #462)
- Fix LP_MARK_DEFAULT being ignored if root (GitHub #501)
- Git:
* Faster "git stash" check (GitHub #503)
Thanks to Roman (@hatifnatt), Jon Garrison (@jpwgarrison),
Mark Vander Stel (@Rycieos), Bryce Jasmer (b-jazz), Felix
Schlitter (@felixSchl), Philip Garrison (@pgarrison), Lubomir
Host (@lhost), Iain Hallam (@iainhallam), Matt
Smith (@ncs-msmith)...
... for their patches or bug reports.
1.11 2016-06-25
Bug fixes:
- OS X: sudo feature fixed
- OS X: battery level restored
1.10 2016-05-30
Breaking changes:
- In themes, LP_COLORMAP_x variables are replaced by a single
LP_COLORMAP array variable. A warning will be displayed at startup
if your config still uses the old variables, but a compatibility
shim is active (will be removed in next release).
- Many LP_ENABLE_* settings are now static (their effect applies when
liquidprompt is loaded, and changing them at the prompt does nothing)
to more and more improve speed.
- zsh: option 'nopromptsubst' is enabled for security reasons.
This will unfortunately also affect evaluations of other prompt
contexts such as RPS1.
- Variables LP_SCREEN_TITLE_OPEN and LP_SCREEN_TITLE_CLOSE are now
removed to simplify the code (GitHub #371)
New features:
- Sudo:
* The color of the prompt mark is now dynamic and changes to
LP_COLOR_MARK_SUDO (default: bold red) as long as your sudo
credentials are cached (GitHub #335).
Requires sudo 1.7.0+.
This feature must be enabled with LP_ENABLE_SUDO=1
Use 'sudo -K' to revoke your credentials early.
* This feature is disabled by default as there is no way to
detect if the user has sudo rights without triggering a security
alert that will annoy the sysadmin.
- Git:
* Show the number of commits behind the remote (GitHub #269)
* Show the rebasing/merging/cherry-picking state (GitHub #409)
- Add variable LP_TTYN: the basename of the terminal (GitHub #357)
- Add setting LP_ENABLE_FQDN to show the fully qualified domain name
of the host (GitHub #254, #277)
- LP_HOSTNAME_ALWAYS=-1 to always hide the hostname (GitHub #406)
- Run duration of the last command (LP_ENABLE_RUNTIME) is now also
supported on zsh (GitHub #404, #355)
- Python: add support for Conda (CONDA_DEFAULT_ENV) (GitHub #425)
Bug fixes:
- Use $XDG_CONFIG_HOME to locate the config (GitHub #415, #420, #425)
- Improved zsh integration (but most issues had no impact of the
user experience)
- Fix escaping of special chars from $PWD (well, almost, see GitHub
#389) and explicitely set the shell options we need (instead of
relying on the shell default settings)
- Git:
* Fix typo in git work directory detection
- Fossil:
* Fix on darwin (GitHub #390)
- LP_DISABLED_VCS_PATH is fixed on zsh (GitHub #423)
- Battery indicator:
* MacOS: many fixes to handle (all?) edge cases (GitHub #326)
We now have a pmset simulator to better detect regressions.
- Temperature indicator:
* The code using the 'sensors' command now uses the '-u' option
("raw output") that is easier to parse. This format is at least
7 years old. (GitHub #379, #380)
* We now try each backend (acpi/sensors) once to check it works
at startup and disable the feature if none works.
(GitHub #410, #319, #381, #387)
- CPU load indicator:
* Fix the scale that was incorrectly 0-200 (GitHub #391)
- Title:
* Fix terminal sequences that were sent in the title text (the
escaping algorithm is rewritten and now just correct).
- Terminal channel:
* Fix detection of tmux (GitHub #304, #377)
* Fix detection of local session on OS X (GitHub #407)
- Misc:
* Fix bash 3 compatibility (GitHub #313)
* Clear GREP_OPTIONS and skip 'grep' aliases (GitHub #372)
- Shortened path:
* Fix bugs when $PWD contains spaces or special chars (GitHub #369)
* Optimize implementation in case of LP_PATH_KEEP=-1 : LP_PWD
becomes static (related to GitHub #256, #336)
* Optimize implementation in case LP_ENABLE_SHORTEN_PATH=0
* Optimize implementation in case LP_ENABLE_SHORTEN_PATH=0 on bash
with PROMPT_DIRTRIM
- Sample configuration files:
* example.bashrc: major fixes
- The last statement of liquidprompt did not return 0 (GitHub #360,#361)
- Analog clock:
* complete rewrite for speed and correctness (GitHub #365 and other
issues)
- Documentation:
* Many small fixes
- Move dist/ to contrib/dist/ as files there are unmaintained
- Fix title escapes in zsh inside tmux/screen (GitHub #370, #371)
Thanks to Matt Fletcher (@MaffooBristol), Kevin Yap (@iKevinY), Sean
Hussey (@seanhussey), François Schmidts (@jaesivsm), Morgan Knicely
(@morganizeit), Daniel Serodio (@dserodio), Jonathan Giddy
(@jongiddy), Jeremy Clement (@jeremyclement), Panayiotis Kkolos
(@pkkolos), Arturo Borrero Gonzalez (@aborrero), Samuel Krieg
(@SamK), Brian May (@brianmay), Colin Lieberman (@colinlieberman),
@hegedus, Anthony Gelibert (@anthonygelibert), Anthony Ramine (@nox),
Erik M Jacobs (@thoraxe), Pedro Parracho (@berserck), Brad Beyenhof
(@augmentedfourth), Austen Adler (@stonewareslord), Hagen Graf
(@hcgraf), William P. Riley-Land (@wprl), Dave Rigby (@daverigby),
Ned Batchelder (@nedbat), Fabien Marty (@thefab), Alessio Garzi
(@Ozzyboshi), Roger Huang (@rhuang2014), Sebastian Bremicker
(@sebrem), Alex Prengere (@alexprengere), Philipp Grogg (@gro-gg),
Tener Hades (@tenerhades), Thomas Kühnel (@kuehnelth), Étienne Deparis
(@milouse), @Hotschke, Software Mechanic (@softwaremechanic), Simon
McVittie (@smcv)...
... for their patches or bug reports.
1.9 2014-11-12 dolmen (Olivier Mengué)
Bug fixes:
- Battery indicator:
* General fixes (GitHub #264)
* MacOS: fix for computers without battery (like iMacs) (GitHub
#319)
* Optimize colormap
- Temperature indicator:
* Linux: Add a guard against any future l10n of the 'acpi' command
* Linux: Fix for negative temperature values (GitHub #308)
- CPU load:
* Darwin/BSD: quoting fixes
- Hostname:
* Fix colorization for SSH
* Simplify chroot detection
- VCS:
- Git:
* Use --porcelain for "git status" (GitHub #270)
* Minir optimization (GitHub #266)
- Fossil:
* Cleanup and fixes (GitHub #274 and others)
- Subversion:
* Fix branch/tag name extraction (GitHub #117, #237, #293)
- Bazar:
* Fix branch name extraction
* zsh fixes (GitHub #303)
- Mercurial:
* General cleanup for speed and fixes
* Disabled "hg outgoing" because it is slow (GitHub #217)
- Shortened path:
* Bash: Fix quoting for PROMPT_DIRTRIM
- Prompt mark:
* Simplify implementation of LP_MARK_DEFAULT
- Jobs:
* Refactoring
* Fix when screen/tmux are not installed (GitHub #304)
- Analog clock:
* Fix hour for 12AM and 12PM (GitHub #273)
- Misc:
* bash: save and set 'promptvars'
* bash: workaround broken pattern substitution in bash 4.2 (GitHub
#289, #294, #302)
* zsh: fix restoration of the original (pre-liquidprompt) prompt
* Fix tmux detection (GitHub #279)
* Save IFS (GitHub #267)
* Fix $TERM check (GitHub #291)
* Various quoting fixes
* Apply some shellcheck.com suggestions
* Many, many optimizations (GitHub #267)
New features:
- Add vcsh support (GitHub #148, #287)
- Add support for Software Collections (GitHub #299, #300)
Thanks to Anthony Gelibert, Frédéric Mahé, Panayiotis Kkolos, Étienne
Deparis, François Schmidts, Linus Wallgren, Alexander Belaev, Bartosz
Janda, Brett McBride, Chase Colman, Cosmin L. Neagu, Matthew Micene,
Vincent Lara, Wilson Maravilha and Yannack for their patches. Thanks
to all the other contributors who reported issues or proposed patches
that have not been applied.
1.8 2014-01-15 dolmen (Olivier Mengué)
1.7 2013-11-30 nojhan
1.6 2013-05-14 nojhan
1.5 2013-04-20 nojhan
1.4 2013-04-11 nojhan
1.3 2013-03-11 nojhan
1.2 2013-01-16 nojhan
1.1 2012-08-16 nojhan
1.0 2012-08-10 nojhan
0.0 2011-02-05 nojhan

View File

@ -0,0 +1,101 @@
Contributing to Liquid Prompt
=============================
Contributing a patch
--------------------
The public stable branch for end users is `master`.
How to do the right thing?
--------------------------
$ git clone -o upstream git://github.com/nojhan/liquidprompt.git
$ cd liquidprompt
# Run liquidprompt and check that your issue is still on that branch
$ source liquidprompt
# Prepare a fix (include the issue number in the branch name if an issue
# already exists)
$ git checkout -b fix/my-fix
# Prepare a new feature
$ git checkout -b feature/my-feature
# Hack, commit, hack, commit...
# Fork the project on GitHub (if you haven't yet)
# Add the remote target for pushes
$ git remote add github git@github.com:$GITHUB_USER/liquidprompt.git
# Check that your local repo is up to date
$ git fetch
# Rebase your work on the latest state of `master`
$ git rebase upstream/master
# Push your commits
$ git push github fix/my-fix
$ git push github feature/my-feature
# Create the pull request on GitHub. Check that Github chose the `master`
# branch as the starting point for your branch.
How to make a good pull request?
--------------------------------
1. Check that your Git authorship settings are correct:
$ git config -l | grep ^user\.
2. All the commits in the pull request must be on the same topic. If instead
you propose fixes on different topics, use separate branches in your repo
and make a pull request for each.
3. Good commit messages:
- first line must be 72 chars max and is a summary of the commit
- second line must be empty
- following lines (72 chars max) are optional and take this space freely
to express what that changes does.
Use references to GitHub issues number (ex: `#432`) if applicable
4. Use a good title for your pull request.
5. Put details, web links, in the pull request body. Use Markdown fully to
format the content (see
[Markdown syntax](http://daringfireball.net/projects/markdown/syntax)).
For example use triple backquotes for code blocks.
Never, ever, merge the branches `master` of the main repo into one
of your own branches. Instead, always rebase your own work on top the `master`
branch.
How my patch will be applied?
-----------------------------
Before being applied, your pull request will be reviewed, by the maintainer
and also by other users. You can also help the project by reviewing others
pull requests.
If your patch is accepted it will be applied either:
- by "merging" your branch
- by cherry-picking your commit on top of the `master` branch. This makes the
history linear, and so easier to track.
In any case, your authorship will be preserved in the commit.
What if my patch is not applied?
--------------------------------
If you don't even get a review, add a "ping" comment with increasing delay
between pings: 1 week, 2 weeks, then every month.
If a stable version is released while your pull request has still not been
merged on any working branch of the main repo, it would be helpful to ease
the maitainer's work by rebasing your branch on top of the latest `master`
and push it again to your GitHub repo. Be careful (for example create a
branch or a tag before your rebase) because your may lose all your work in
that process.
Olivier Mengué, maintainer.
http://github.com/dolmen

View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

View File

@ -0,0 +1,368 @@
Liquid Prompt — a useful adaptive prompt for Bash & zsh
=======================================================
Liquid Prompt gives you a nicely displayed prompt with useful information
when you need it. It shows you what you need when you need it.
You will notice what changes *when* it changes, saving time and frustration.
You can even use it with your favorite shell Bash or zsh.
![Screenshot](https://raw.github.com/nojhan/liquidprompt/master/demo.png)
## Features
If there is nothing special about the current context, the appearance of Liquid
Prompt is similar to that of a default prompt:
`[user:~] $ `
If you are running a background command and are also in the "myb" branch
of a Git repository on a server:
`1r [user@server:~/liquidprompt] myb ± `
When Liquid Prompt is displaying everything (a rare event!), it may look like this:
`code 🕤 ⌁24% ⌂42% 3d/2&/1z [user@server:~/ … /code/liquidprompt][pyenv]↥ master(+10/-5,3)*+ 125 ± `
Here is an overview of what Liquid Prompt is capable of displaying:
* a tag associated to the current shell session (you can easily add any
prefix tag to your prompt by invoking `prompt_tag MYTAG`)
* the current time, displayed as either numeric values or as an analog clock
* the current battery status:
* a green `⏚` if charging, above the given threshold, but not charged
* a yellow `⏚` if charging and under the given threshold
* a yellow `⌁` if discharging but above the given threshold
* a red `⌁` if discharging and under the given threshold
* the remaining battery power if it is under the given threshold, displayed with
an increasingly red color map as remaining power decreases
* the average of the processors load if it is over a given limit, displayed with
an intensity color map as load increases
* the average temperature of the available system sensors (generally CPU and MB)
* the number of detached sessions (`screen` or `tmux`)
* the number of attached sleeping jobs (when you interrupt a command with Ctrl-Z
and bring it back with `fg`)
* the number of attached running jobs (commands started with a `&`)
* a pair of square brackets, in blue if your current shell is running in a
terminal multiplexer (`screen` or `tmux`)
* the current user, in bold yellow if it is root and in light white if it is not
the same as the login user
* a green `@` if the connection has X11 support; a yellow one if not
* the current host in bold red if you are connected via a `telnet` connection
and blue (or other unique colors) if connected via SSH
* a green colon if the user has write permissions in the current directory and
a red one if not
* the current directory in bold, shortened if it takes too much space while always
preserving the first two directory names
* the current Python virtual environment
* an up arrow if an HTTP proxy is in use
* the name of the current branch if you are in a version control repository
(Git, Mercurial, Subversion, Bazaar, or Fossil):
* in green if everything is up-to-date
* in red if there are changes
* in yellow if there are pending commits to push
* the number of added/deleted lines if changes have been made and the
number of pending commits
* a yellow `+` if there are stashed modifications
* a red `*` if there are untracked files in the repository
* the runtime of the last command, if it has exceeded a certain threshold
* the error code of the last command, if it has failed in some way
* a smart mark at the end of the prompt:
* `±` for Git,
* `☿` for Mercurial,
* `‡` for Subversion,
* `‡±` for Git-Subversion,
* `⌘` for Fossil,
* `$` or `%` for a simple user, in red if you have `sudo` rights,
* a red `#` for the root user.
* if desired, the prompt will be replicated in your terminal window's
title (without the colors)
You can temporarily deactivate Liquid Prompt and revert to your previous prompt
by typing `prompt_off`. Use `prompt_on` to bring it back. You can disable
*all* prompts and simply use a single mark sign (`$ ` for user and `# ` for root)
by using the `prompt_OFF` command.
## Test Drive and Installation
Installation is simple. The basic dependencies are standard Unix utilities/commands.
If you experience some problems during the installation, please check that they
are met; see the [dependencies](#dependencies) section for what you need specifically.
Follow these steps:
cd
git clone https://github.com/nojhan/liquidprompt.git
source liquidprompt/liquidprompt
To use it every time you start a shell, add the following lines to your
`.bashrc` (if you use Bash) or `.zshrc` (if you use zsh):
# Only load Liquid Prompt in interactive shells, not from a script or from scp
[[ $- = *i* ]] && source ~/liquidprompt/liquidprompt
Next up is the configuration; you can skip this step if you like the defaults:
cp ~/liquidprompt/liquidpromptrc-dist ~/.config/liquidpromptrc
You can also copy the file to `~/.liquidpromptrc`.
Use your favorite text editor to change the defaults.
The `liquidpromptrc` file is richly commented and easy to set your own defaults.
You can even theme Liquid Prompt and use a custom PS1 prompt. This is explained
in the sections below.
Check in your `.bashrc` that the `PROMPT_COMMAND` variable is not set, or else
the prompt will not be available.
### Installation via Antigen
To install via antigen, simply add the following line in your `.zshrc` after activating antigen:
antigen bundle nojhan/liquidprompt
## Dependencies
Apart from obvious ones, some features depend on specific commands. If you do
not install them, the corresponding feature will not be available, but no error
will be displayed.
* Battery status requires `acpi` on GNU/Linux.
* Temperature status requires `acpi` or `lm-sensors` on GNU/Linux.
* Detached session status looks for `screen` and/or `tmux`.
* VCS support features require `git`, `hg`, `svn`, `bzr` or `fossil`, but you
probably already knew that.
For other features, the script uses commands that should be available on a large
variety of Unix systems: `tput`, `grep`, `awk`, `sed`, `ps`, `who`, and `expr`.
## Feature Configuration
You can configure some variables in the `~/.config/liquidpromptrc` file:
* `LP_BATTERY_THRESHOLD`, the maximal value under which the battery level is displayed
* `LP_LOAD_THRESHOLD`, the minimal value after which the load average is displayed
* `LP_TEMP_THRESHOLD`, the minimal value after which the average temperature is displayed
* `LP_RUNTIME_THRESHOLD`, the minimal value after which the runtime is displayed
* `LP_PATH_LENGTH`, the maximum percentage of the screen width used to display the path
* `LP_PATH_KEEP`, how many directories to keep at the beginning of a shortened path
* `LP_HOSTNAME_ALWAYS`, a choice between always displaying the hostname or
showing it only when connected via a remote shell
* `LP_USER_ALWAYS`, a choice between always displaying the user or showing
it only when he is different from the one that logged in
You can also force some features to be disabled, to save some time in the
prompt-building process:
* `LP_ENABLE_PERM`, if you want to detect if the directory is writeable
* `LP_ENABLE_SHORTEN_PATH`, if you want to shorten the path display
* `LP_ENABLE_PROXY`, if you want to detect if a proxy is used
* `LP_ENABLE_JOBS`, if you want to have jobs information
* `LP_ENABLE_LOAD`, if you want to have load information
* `LP_ENABLE_BATT`, if you want to have battery information
* `LP_ENABLE_GIT`, if you want to have Git information
* `LP_ENABLE_SVN`, if you want to have Subversion information
* `LP_ENABLE_HG`, if you want to have Mercurial information
* `LP_ENABLE_BZR`, if you want to have Bazaar information
* `LP_ENABLE_FOSSIL`, if you want to have Fossil information
* `LP_ENABLE_VCS_ROOT`, if you want to show VCS informations with root account
* `LP_ENABLE_TITLE`, if you want to use the prompt as your terminal window's title
* `LP_ENABLE_SCREEN_TITLE`, if you want to use the prompt as your screen window's title
* `LP_ENABLE_SSH_COLORS`, if you want different colors for hosts you SSH into
* `LP_ENABLE_RUNTIME`, if you want to display the runtime of the last command
* `LP_ENABLE_SUDO`, if you want the prompt mark to change color while you have password-less root access
* `LP_ENABLE_FQDN`, if you want the display of the fully qualified domain name
* `LP_ENABLE_TIME`, if you want to display the time at which the prompt was shown
* `LP_TIME_ANALOG`, if you want to show the time using an analog clock instead of numeric values
Note that if required commands are not installed, enabling the corresponding
feature will have no effect. Also, all the `LP_ENABLE_…` variables override the
templates; i.e. if you use `$LP_BATT` in your template and you set `LP_ENABLE_BATT=0`
in your configuration file, your prompt will not have any battery information.
If you are using Bash and want to use the `PROMPT_DIRTRIM` built-in
functionality to shorten but still want to have Liquid Prompt calculating the
number of directories to keep in the path, precise a value for `PROMPT_DIRTRIM`
before sourcing Liquid Prompt and it will override this value with one fitting
the width of your terminal.
You may face performances decrease when using VCS located in remote directories.
To avoid this, you can set the `LP_DISABLED_VCS_PATH` variable to a list of
absolute colon-separated paths where VCS-related features should be disabled.
## Customizing the Prompt
### Adding a Prefix/Postfix
You can prefix the `LP_PS1` variable with anything you want using
`LP_PS1_PREFIX`. The following example activate a custom window's title:
LP_PS1_PREFIX="\[\e]0;\u@\h: \w\a\]"
To postfix the prompt, use the `LP_PS1_POSTFIX` variable. For example, to add a
newline and a single character:
LP_PS1_POSTFIX="\n>"
Note: the `prompt_tag` function is a convenient way to add a prefix. You can use
it to add a keyword to each of your different terminals:
[:~/code/liquidprompt] develop ± prompt_tag mycode
mycode [:~/code/liquidprompt] develop ±
### Rearranging the Prompt
You can sort what you want to see by sourcing your favorite template file
(`*.ps1`) in the configuration file.
You can start from the `liquid.ps1` file, which show the default settings.
To use your own configuration, just set `LP_PS1_FILE` to your own file path in
your `~/.liquidpromptrc` and you're done.
Those scripts basically export the `LP_PS1` variable, by appending features and
theme colors.
Available features:
* `LP_BATT` battery
* `LP_LOAD` load
* `LP_TEMP` temperature
* `LP_JOBS` detached `screen` or `tmux` sessions/running jobs/suspended jobs
* `LP_USER` user
* `LP_HOST` hostname
* `LP_PERM` a colon (`:`)
* `LP_PWD` current working directory
* `LP_PROXY` HTTP proxy
* `LP_VCS` informations concerning the current working repository
* `LP_ERR` last error code
* `LP_MARK` prompt mark
* `LP_TITLE` the prompt as a window's title escaped sequences
* LP_TTYN the terminal basename
* `LP_BRACKET_OPEN` and `LP_BRACKET_CLOSE`, brackets enclosing the user+path part
For example, if you just want to have a prompt displaying the user and the
host, with a normal full path in blue and Git support only:
export LP_PS1=`echo -ne "[\${LP_USER}\${LP_HOST}:\${BLUE}\$(pwd)\${NO_COL}] \${LP_GIT} \\\$ "`
Note that you need to properly escape dollar signs in a string that will be
interpreted by Bash at each prompt.
To erase your new formatting, just bind `LP_PS1` to a null string:
export LP_PS1=""
## Themes
You can change the colors and special characters of some parts of Liquid Prompt
by sourcing your favorite theme file (`*.theme`) in the configuration file. See
[`liquid.theme`](liquid.theme) for an example of the default Liquid Prompt theme.
### Colors
The available colours available for use are:
`BOLD`, `BLACK`, `BOLD_GRAY`, `WHITE`, `BOLD_WHITE`, `GREEN`, `BOLD_GREEN`,
`YELLOW`, `BOLD_YELLOW`, `BLUE`, `BOLD_BLUE`, `PINK`, `CYAN`, `BOLD_CYAN,`,
`RED`, `BOLD_RED`, `WARN_RED`, `CRIT_RED`, `DANGER_RED`, and `NO_COL`.
Set the variable to a null string (`""`) if you do not want color.
* Current working directory
* `LP_COLOR_PATH` as normal user
* `LP_COLOR_PATH_ROOT` as root
* Color of the proxy mark
* `LP_COLOR_PROXY`
* Jobs count
* `LP_COLOR_JOB_D` Detached (`screen` / `tmux` sessions without attached clients)
* `LP_COLOR_JOB_R` Running (`xterm &`)
* `LP_COLOR_JOB_Z` Sleeping (Ctrl-Z)
* `LP_COLOR_IN_MULTIPLEXER` currently running in a terminal multiplexer
* Last error code
* `LP_COLOR_ERR`
* Prompt mark
* `LP_COLOR_MARK` as user
* `LP_COLOR_MARK_ROOT` as root
* `LP_COLOR_MARK_SUDO` when you did `sudo` and your credentials are still cached (use `sudo -K` to revoke them)
* `LP_MARK_PREFIX="\n"` put the prompt on the second line
* Current user
* `LP_COLOR_USER_LOGGED` user who logged in
* `LP_COLOR_USER_ALT` user but not the one who logged in
* `LP_COLOR_USER_ROOT` root
* Hostname
* `LP_COLOR_HOST` local host
* `LP_COLOR_SSH` connected via SSH
* `LP_COLOR_TELNET` connected via `telnet`
* `LP_COLOR_X11_ON` connected with X11 support
* `LP_COLOR_X11_OFF` connected without X11 support
* Separation mark (by default, the colon before the path)
* `LP_COLOR_WRITE` have write permission
* `LP_COLOR_NOWRITE` do not have write permission
* VCS
* `LP_COLOR_UP` repository is up-to-date / a push has been made
* `LP_COLOR_COMMITS` some commits have not been pushed
* `LP_COLOR_CHANGES` there are some changes to commit
* `LP_COLOR_DIFF` number of lines or files impacted by current changes
* Battery
* `LP_COLOR_CHARGING_ABOVE` charging and above threshold
* `LP_COLOR_CHARGING_UNDER` charging but under threshold
* `LP_COLOR_DISCHARGING_ABOVE` discharging but above threshold
* `LP_COLOR_DISCHARGING_UNDER` discharging and under threshold
### Special Characters
* `LP_MARK_DEFAULT` (default: "") the mark you want at the end of your prompt
(leave empty to use your shell's default mark)
* `LP_MARK_BATTERY` (default: "⌁") in front of the battery charge
* `LP_MARK_ADAPTER` (default: "⏚") displayed when plugged-in
* `LP_MARK_LOAD` (default: "⌂") in front of the load
* `LP_MARK_PROXY` (default: "↥") indicate a proxy in use
* `LP_MARK_HG` (default: "☿") prompt mark in Mercurial repositories
* `LP_MARK_SVN` (default: "‡") prompt mark in Subversion repositories
* `LP_MARK_GIT` (default: "±") prompt mark in Git repositories
* `LP_MARK_FOSSIL` (default: "⌘") prompt mark in Fossil repositories
* `LP_MARK_BZR` (default: "⚯") prompt mark in Bazaar repositories
* `LP_MARK_DISABLED` (default: "⌀") prompt mark in disabled repositories
(see `LP_DISABLED_VCS_PATH`)
* `LP_MARK_UNTRACKED` (default: "\*") if Git has untracked files
* `LP_MARK_STASH` (default: "+") if Git has stashed modifications
* `LP_MARK_BRACKET_OPEN` (default: "[") marks around the main part of the prompt
* `LP_MARK_BRACKET_CLOSE` (default: "]") marks around the main part of the prompt
* `LP_MARK_PERM` (default: ":") colored green red or green to indicate write
permissions of the current directory
* `LP_TITLE_OPEN` (default: "\e]0;") escape character opening a window's title
* `LP_TITLE_CLOSE` (default: "\a") escape character closing a window's title
## Known Limitations and Bugs
Liquid Prompt is distributed under the [GNU Affero General Public License
version 3](LICENSE).
* Does not display the number of commits to be pushed in Mercurial repositories.
* Browsing very large Subversion repositories may dramatically slow down
the display of Liquid Prompt (use `LP_DISABLED_VCS_PATH` to avoid that).
* Subversion repositories cannot display commits to be pushed because
that's not how Subversion works
* The proxy detection only uses the `$http_proxy` environment variable.
* The window's title escape sequence may not work properly on some terminals
(like `xterm-256`).
* The analog clock requires a Unicode-aware terminal and at least a
sufficiently complete font on your system. The [Symbola](http://users.teilar.gr/~g1951d/)
font, designed by Georges Douros, is known to work well. On Debian or Ubuntu
install try the `fonts-symbola` or `ttf-ancient-fonts` package.
## Authors
Current Maintainer: [![endorse](https://api.coderwall.com/dolmen/endorsecount.png)](https://coderwall.com/dolmen)
Original Author: [![endorse](https://api.coderwall.com/nojhan/endorsecount.png)](https://coderwall.com/nojhan)
And many contributors!

View File

@ -0,0 +1,12 @@
liquidprompt/contrib Policy
---------------------------
This directory contains files that have been contributed by contributors
but that the core liquidprompt maintainers don't take care.
So they are probably outdated, maybe of poor quality (because the maintainers
do not have the knowledge to properly review them).
So use them at your own risks, and don't fill issues about them, just send
patches.

View File

@ -0,0 +1,40 @@
# Maintainer: Julien Pecqueur (JPEC) <jpec[at]julienpecqueur[dot]net>
pkgname=liquidprompt-git
pkgver=20130314
pkgrel=3
pkgdesc="An intelligent and non intrusive prompt for bash and zsh"
url="https://github.com/nojhan/liquidprompt"
arch=('any')
license=('AGPLv3')
optdepends=('screen' 'acpi')
makedepends=('git')
md5sums=('SKIP')
install=liquidprompt.install
_gitroot="git://github.com/nojhan/liquidprompt.git"
_gitname="liquidprompt"
build() {
cd ${srcdir}/
msg "Connecting to the GIT server...."
if [[ -d ${srcdir}/${_gitname} ]] ; then
cd ${_gitname}
git reset --hard
git pull origin
msg "The local files are updated..."
else
msg "Cloning git repo..."
git clone ${_gitroot}
cd ${_gitname}
fi
git reset --hard
msg "GIT checkout done."
}
package() {
cd "${srcdir}/${_gitname}"
# install files
install -Dm755 liquidprompt "$pkgdir/usr/bin/liquidprompt"
install -Dm644 liquidpromptrc-dist "$pkgdir/etc/liquidpromptrc"
}
# vim:set ts=2 sw=2 et:

View File

@ -0,0 +1,4 @@
post_install() {
echo "Use 'source liquidprompt' to enable the prompt."
}

View File

@ -0,0 +1,18 @@
#!/bin/sh
echo "Creating Debian's package..."
nano ./liquidprompt/DEBIAN/control
echo "Copying files..."
cp ../../liquidprompt ./liquidprompt/usr/bin/liquidprompt
cp ../../liquidpromptrc-dist ./liquidprompt/etc/liquidpromptrc
chmod a+x ./liquidprompt/usr/bin/liquidprompt
echo "Building liquidprompt.deb..."
dpkg-deb -b liquidprompt
echo "Deleting files..."
rm -f ./liquidprompt/etc/*
rm -f ./liquidprompt/usr/bin/*
echo "Done !"

View File

@ -0,0 +1,11 @@
Package: liquidprompt
Version: 1.3-0
Section: base
Priority: optional
Architecture: all
Depends: bash
Recommends: acpi
Suggests: git, screen, tmux
Maintainer: Julien Pecqueur <jpec@julienpecqueur.net>
Description: A slick adaptative prompt for Bash and Zsh.
Homepage: http://github.com/nojhan/liquidprompt

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

View File

@ -0,0 +1,25 @@
# If you want to use Liquid Prompt without bothering about its configuration,
# just run the following command:
# cp example.bashrc ~/.bashrc
# The following is a minimalistic Bash config file
# Use the system config if it exists
if [ -f /etc/bashrc ]; then
. /etc/bashrc # --> Read /etc/bashrc, if present.
elif [ -f /etc/bash.bashrc ]; then
. /etc/bash.bashrc # --> Read /etc/bash.bashrc, if present.
fi
# The following lines are only for interactive shells
[[ $- = *i* ]] || return
# Use Bash completion, if installed
if [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
# Use Liquid Prompt
source ~/liquidprompt/liquidprompt

View File

@ -0,0 +1,53 @@
#######################################
# LIQUID PROMPT DEFAULT TEMPLATE FILE #
#######################################
# Available features:
# LP_BATT battery
# LP_LOAD load
# LP_JOBS screen sessions/running jobs/suspended jobs
# LP_USER user
# LP_HOST hostname
# LP_PERM a colon ":"
# LP_PWD current working directory
# LP_VENV Python virtual environment
# LP_PROXY HTTP proxy
# LP_VCS the content of the current repository
# LP_ERR last error code
# LP_MARK prompt mark
# LP_TIME current time
# LP_TTYN number of current terminal (useful in title for quick switching)
# LP_RUNTIME runtime of last command
# LP_MARK_PREFIX user-defined prompt mark prefix (helpful if you want 2-line prompts)
# LP_PS1_PREFIX user-defined general-purpose prefix (default set a generic prompt as the window title)
# LP_PS1_POSTFIX user-defined general-purpose postfix
# LP_BRACKET_OPEN open bracket
# LP_BRACKET_CLOSE close bracket
# Remember that most features come with their corresponding colors,
# see the README.
# add time, jobs, load and battery
LP_PS1="${LP_PS1_PREFIX}${LP_TIME}${LP_BATT}${LP_LOAD}${LP_JOBS}"
# add user, host and permissions colon
LP_PS1="${LP_PS1}${LP_BRACKET_OPEN}${LP_USER}${LP_HOST}${LP_PERM}"
LP_PS1="${LP_PS1}${LP_PWD}${LP_BRACKET_CLOSE}${LP_VENV}${LP_PROXY}"
# Add VCS infos
# If root, the info has not been collected unless LP_ENABLE_VCS_ROOT
# is set.
LP_PS1="${LP_PS1}${LP_VCS}"
# add return code and prompt mark
LP_PS1="${LP_PS1}${LP_RUNTIME}${LP_ERR}${LP_MARK_PREFIX}${LP_MARK}${LP_PS1_POSTFIX}"
# "invisible" parts
# Get the current prompt on the fly and make it a title
LP_TITLE="$(_lp_title "$LP_PS1")"
# Insert it in the prompt
LP_PS1="${LP_TITLE}${LP_PS1}"
# vim: set et sts=4 sw=4 tw=120 ft=sh:

View File

@ -0,0 +1,137 @@
####################################
# LIQUID PROMPT DEFAULT THEME FILE #
####################################
# Special characters
# Be sure to use characters that exists in the font you use. You can use several
# characters at once.
# Below is an example of how to fallback to ASCII if the term is not Unicode-capable.
# Defaults to UTF-8 characters.
if [[ "$(locale -k LC_CTYPE | sed -n 's/^charmap="\(.*\)"/\1/p')" == *"UTF-8"* ]]; then
# If charset is UTF-8.
LP_MARK_BATTERY="⌁" # in front of the battery charge
LP_MARK_ADAPTER="⏚" # displayed when plugged
LP_MARK_LOAD="⌂" # in front of the load
LP_MARK_TEMP="θ" # in front of the temp
LP_MARK_PROXY="↥" # indicate a proxy in use
LP_MARK_HG="☿" # prompt mark in hg repositories
LP_MARK_SVN="‡" # prompt mark in svn repositories
LP_MARK_GIT="±" # prompt mark in git repositories
LP_MARK_FOSSIL="⌘" # prompt mark in fossil repositories
LP_MARK_DISABLED="⌀" # prompt mark in directory with disabled VCS info
LP_MARK_UNTRACKED="*" # if git has untracked files
LP_MARK_STASH="+" # if git has stashs
LP_MARK_SHORTEN_PATH=" … " # prompt mark in shortened paths
LP_MARK_PERM=":" # separator between host and path
else
# If charset is anything else, fallback to ASCII chars
LP_MARK_BATTERY="b"
LP_MARK_ADAPTER="p"
LP_MARK_LOAD="c"
LP_MARK_TEMP="T"
LP_MARK_PROXY="^"
LP_MARK_HG="m"
LP_MARK_SVN="="
LP_MARK_GIT="+"
LP_MARK_FOSSIL="f"
LP_MARK_DISABLED="!"
LP_MARK_UNTRACKED="*"
LP_MARK_STASH="+"
LP_MARK_SHORTEN_PATH=" ... "
LP_MARK_PERM=":"
fi
LP_MARK_BRACKET_OPEN="[" # open bracket
LP_MARK_BRACKET_CLOSE="]" # close bracket
#LP_MARK_DEFAULT="" # default prompt mark
LP_MARK_PREFIX=" " # prompt mark prefix
LP_PS1_PREFIX=""
LP_PS1_POSTFIX=""
# Colors
# Available colors are:
# BOLD, BLACK, BOLD_GRAY, WHITE, BOLD_WHITE,
# RED, BOLD_RED, WARN_RED, CRIT_RED, DANGER_RED,
# GREEN, BOLD_GREEN, YELLOW, BOLD_YELLOW, BLUE,
# BOLD_BLUE, PURPLE, PINK, CYAN, BOLD_CYAN
# Set to a null string "" if you do not want color.
# Current working directory
LP_COLOR_PATH="$BOLD" # as normal user
LP_COLOR_PATH_ROOT="$BOLD_YELLOW" # as root
# Color of the proxy mark
LP_COLOR_PROXY="$BOLD_BLUE"
# Jobs count
LP_COLOR_JOB_D="$YELLOW" # Detached (aka screen sessions)
LP_COLOR_JOB_R="$BOLD_YELLOW" # Running (xterm &)
LP_COLOR_JOB_Z="$BOLD_YELLOW" # Sleeping (Ctrl-Z)
# Last error code
LP_COLOR_ERR="$PURPLE"
# Prompt mark
LP_COLOR_MARK="$BOLD" # as user
LP_COLOR_MARK_ROOT="$BOLD_RED" # as root
LP_COLOR_MARK_SUDO="$BOLD_RED" # when sudo credentials are cached
# Current user
LP_COLOR_USER_LOGGED="" # user who logged in
LP_COLOR_USER_ALT="$BOLD" # user but not the one who logged in
LP_COLOR_USER_ROOT="$BOLD_YELLOW" # root
# Hostname
LP_COLOR_HOST="" # local host
LP_COLOR_SSH="$BLUE" # connected via SSH
LP_COLOR_SU="$BOLD_YELLOW" # connected remotely but in new environment through su/sudo
LP_COLOR_TELNET="$WARN_RED" # connected via telnet
LP_COLOR_X11_ON="$GREEN" # connected with X11 support
LP_COLOR_X11_OFF="$YELLOW" # connected without X11 support
# Separation mark (aka permission in the working dir)
LP_COLOR_WRITE="$GREEN" # have write permission
LP_COLOR_NOWRITE="$RED" # do not have write permission
# VCS
LP_COLOR_UP="$GREEN" # repository is up to date / a push have been made
LP_COLOR_COMMITS="$YELLOW" # some commits have not been pushed
LP_COLOR_COMMITS_BEHIND="$BOLD_RED" # some commits have not been pushed
LP_COLOR_CHANGES="$RED" # there is some changes to commit
LP_COLOR_DIFF="$PURPLE" # number of lines impacted by current changes
# Battery
LP_COLOR_CHARGING_ABOVE="$GREEN" # charging and above threshold
LP_COLOR_CHARGING_UNDER="$YELLOW" # charging but under threshold
LP_COLOR_DISCHARGING_ABOVE="$YELLOW" # discharging but above threshold
LP_COLOR_DISCHARGING_UNDER="$RED" # discharging and under threshold
# Time
LP_COLOR_TIME="$BLUE"
# Brackets inside screen/tmux
LP_COLOR_IN_MULTIPLEXER="$BOLD_BLUE"
# Virtual environment
LP_COLOR_VIRTUALENV="$CYAN"
# Runtime
LP_COLOR_RUNTIME="$YELLOW"
# Color map (for battery and load levels, and temperature)
# Range from 0 (nothing special) to 9 (alert)
LP_COLORMAP=(
""
"$GREEN"
"$BOLD_GREEN"
"$YELLOW"
"$BOLD_YELLOW"
"$RED"
"$BOLD_RED"
"$WARN_RED"
"$CRIT_RED"
"$DANGER_RED"
)
# vim: set et sts=4 sw=4 tw=120 ft=sh:

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
source ${0%/*}/liquidprompt

View File

@ -0,0 +1,165 @@
####################################
# LIQUID PROMPT CONFIGURATION FILE #
####################################
# If you want to use different themes and features,
# you can load the corresponding files here:
#source ~/.config/liquidprompt/nojhan.theme
#LP_PS1_FILE=~/.config/liquidprompt/nojhan.ps1
#############
# BEHAVIOUR #
#############
# Display the battery level when the level is below this threshold.
# Recommended value is 75
LP_BATTERY_THRESHOLD=75
# Display the load average when the load is above this threshold.
# Recommended value is 60
LP_LOAD_THRESHOLD=60
# Display the temperature when the temperate is above this threshold (in
# degrees Celsius).
# Recommended value is 60
LP_TEMP_THRESHOLD=60
# Use the shorten path feature if the path is too long to fit in the prompt
# line.
# Recommended value is 1
LP_ENABLE_SHORTEN_PATH=1
# The maximum percentage of the screen width used to display the path before
# removing the center portion of the path and replacing with '...'.
# Recommended value is 35
LP_PATH_LENGTH=35
# The number of directories (including '/') to keep at the beginning of a
# shortened path.
# Recommended value is 2
LP_PATH_KEEP=2
# Determine if the hostname should always be displayed, even if not connecting
# through network.
# Defaults to 0 (do not display hostname when locally connected)
# set to 1 if you want to always see the hostname
# set to -1 if you want to never see the hostname
LP_HOSTNAME_ALWAYS=0
# Use the fully qualified domain name (FQDN) instead of the short hostname when
# the hostname is displayed
LP_ENABLE_FQDN=0
# Always display the user name, even if the user is the same as the one logged
# in.
# Defaults to 1 (always display the user name)
# set to 0 if you want to hide the logged user (it will always display different
# users)
LP_USER_ALWAYS=1
# Display the percentages of load/batteries along with their
# corresponding marks. Set to 0 to only print the colored marks.
# Defaults to 1 (display percentages)
LP_PERCENTS_ALWAYS=1
# Use the permissions feature and display a red ':' before the prompt to show
# when you don't have write permission to the current directory.
# Recommended value is 1
LP_ENABLE_PERM=1
# Enable the proxy detection feature.
# Recommended value is 1
LP_ENABLE_PROXY=1
# Enable the jobs feature.
# Recommended value is 1
LP_ENABLE_JOBS=1
# Enable the load feature.
# Recommended value is 1
LP_ENABLE_LOAD=1
# Enable the battery feature.
# Recommended value is 1
LP_ENABLE_BATT=1
# Enable the 'sudo credentials' feature.
# Be warned that this may pollute the syslog if you don't have sudo
# credentials, and the sysadmin will hate you.
LP_ENABLE_SUDO=0
# Enable the VCS features with the root account.
# Recommended value is 0
LP_ENABLE_VCS_ROOT=0
# Enable the Git special features.
# Recommended value is 1
LP_ENABLE_GIT=1
# Enable the Subversion special features.
# Recommended value is 1
LP_ENABLE_SVN=1
# Enable the Mercurial special features.
# Recommended value is 1
LP_ENABLE_HG=1
# Enable the Fossil special features.
# Recommended value is 1
LP_ENABLE_FOSSIL=1
# Enable the Bazaar special features.
# Recommanded value is 1
LP_ENABLE_BZR=1
# Show time of when the current prompt was displayed. (Must be enabled and
# disabled in the config file and not after liquidprompt has already been
# sourced.)
LP_ENABLE_TIME=0
# Show runtime of the previous command if over LP_RUNTIME_THRESHOLD
# Recommended value is 0
LP_ENABLE_RUNTIME=0
# Minimal runtime (in seconds) before the runtime will be displayed
# Recommended value is 2
LP_RUNTIME_THRESHOLD=2
# Display the virtualenv that is currently activated, if any
# Recommended value is 1
LP_ENABLE_VIRTUALENV=1
# Display the enabled software collections, if any
# Recommended value is 1
LP_ENABLE_SCLS=1
# Show average system temperature
LP_ENABLE_TEMP=1
# When showing the time, use an analog clock instead of numeric values.
# The analog clock is "accurate" to the nearest half hour.
# You must have a unicode-capable terminal and a font with the "CLOCK"
# characters.
# Recommended value is 0
LP_TIME_ANALOG=0
# Use the prompt as the title of the terminal window
# The content is not customizable, the implementation is very basic,
# and this may not work properly on exotic terminals, thus the
# recommended value is 0
# See LP_TITLE_OPEN and LP_TITLE_CLOSE to change escape characters to adapt this
# feature to your specific terminal.
LP_ENABLE_TITLE=0
# Enable Title for screen and byobu
LP_ENABLE_SCREEN_TITLE=0
# Use different colors for the different hosts you SSH to
LP_ENABLE_SSH_COLORS=0
# Specify a list of complete and colon (":") separated paths in which, all vcs
# will be disabled
LP_DISABLED_VCS_PATH=""
# vim: set et sts=4 sw=4 tw=120 ft=sh:

View File

@ -0,0 +1,48 @@
# Simulator for "pmset -g batt" for testing the implementation of
# battery display on MacOS X
pmset()
{
case "$pmset_sim" in
iMac|no-battery)
# https://github.com/nojhan/liquidprompt/issues/315
cat <<EOF
Now drawing from 'AC Power'
EOF
;;
attached)
# https://github.com/nojhan/liquidprompt/issues/326#issuecomment-66120495
cat <<'EOF'
Now drawing from 'AC Power'
-InternalBattery-0 37%; AC attached; not charging
EOF
;;
charging)
# https://github.com/nojhan/liquidprompt/issues/326
cat <<'EOF'
Now drawing from 'AC Power'
-InternalBattery-0 8%; charging; 2:46 remaining
EOF
;;
discharging)
# https://github.com/nojhan/liquidprompt/issues/326
cat <<'EOF'
Now drawing from 'Battery Power'
-InternalBattery-0 9%; discharging; (no estimate)
EOF
;;
warning-Early)
# https://github.com/nojhan/liquidprompt/issues/326
cat <<'EOF'
Now drawing from 'Battery Power'
-InternalBattery-0 7%; discharging; 0:13 remaining
Battery Warning: Early
EOF
;;
*)
echo "unsupported '$pmset_sim' pmset simulation"
;;
esac
}

View File

@ -0,0 +1,351 @@
#!/bin/sh
# Run the testsuite with both bash and zsh
if [ -z "$BASH_VERSION$ZSH_VERSION" ]; then
for sh in bash zsh
do
if [ -x /bin/$sh ]; then
/bin/$sh "$0"
elif [ -x /usr/bin/$sh ]; then
/usr/bin/$sh "$0"
fi
done
exit 0
fi
print_ok()
{
local OK="\\033[1;32m"
local RAZ="\\033[0;39m"
local cols=$1
local name=$2
# printf "\e${OK}%-${cols}s %-${cols}s\n${RAZ}" "$name" "OK"
printf "${OK}%-${cols}s %-${cols}s\n${RAZ}" "$name" "OK"
}
print_no()
{
local NOK="\\033[1;31m"
local RAZ="\\033[0;39m"
local cols=$1
local name=$2
local sub=$3
local line=$4
# printf "\e${NOK}%-${cols}s %-${cols}s #%-5s\n${RAZ}" "$name" "$sub" "$line"
printf "${NOK}%-${cols}s %-${cols}s #%-5s\n${RAZ}" "$name" "$sub" "$line"
}
assert()
{
local has=$1
local name=$2
local sub=$3
local line=$4
if [[ -z "$sub" ]]
then
return 1
fi
cols=20
if [[ $has == 1 ]] ; then
if [[ "$PS1" == *$sub* ]]
then
print_ok $cols "has $name"
else
print_no $cols "has $name" $sub $line
fi
elif [[ $has == 0 ]] ; then
if [[ "$PS1" != *$sub* ]]
then
print_ok $cols " no $name"
else
print_no $cols " no $name" $sub $line
fi
else
if [[ "$PS1" == $sub ]]
then
print_ok $cols " is $name"
else
print_no $cols " is $name" $sub $line
fi
fi
}
assert_has()
{
assert 1 "$@"
}
assert_not()
{
assert 0 "$@"
}
assert_is()
{
assert 2 "$@"
}
log_prompt()
{
echo -e "$PS1" 1>&2
}
#####################
# REDEFINE COMMANDS #
#####################
command()
{
echo "fake command $@" 1>&2
echo "/bin/fake"
}
uname()
{
echo "fake uname $@" 1>&2
echo Linux
}
nproc()
{
echo "fake nproc $@" 1>&2
echo 2
}
# battery
acpi()
{
echo "fake acpi $@" 1>&2
if [[ "x$1" == --battery ]]; then
echo 'Battery 0: Discharging, 55%, 01:39:34 remaining'
elif [[ "x$1" == -t ]]; then
echo 'Thermal 0: ok, 36.0 degrees C'
else
return 1
fi
}
git()
{
echo "fake git $@" 1>&2
case $1 in
"rev-parse" )
echo ".git";;
"branch" )
echo "* fake_test";;
"diff" )
echo "2 1 fake_file"
return 1;;
"status" )
echo "# Untracked";;
"rev-list" )
echo 111;;
esac
}
# global variables
export http_proxy="fake"
##########################
# Call the liquid prompt #
##########################
# As if we were in an interactive shell
export PS1="fake prompt \$"
# load functions
source ./liquidprompt
# Force liquid prompt function redefinition
_lp_cpu_load()
{
echo "fake _lp_cpu_load $@" 1>&2
echo "0.64"
}
################
# ADHOC CONFIG #
################
export LP_BATTERY_THRESHOLD=60
export LP_LOAD_THRESHOLD=1
export LP_MARK_PROXY="proxy"
export LP_MARK_BATTERY="BATT"
export LP_MARK_LOAD="LOAD"
export LP_MARK_UNTRACKED="untracked"
export LP_MARK_GIT="gitmark"
export LP_USER_ALWAYS=1
# Force erroneous command
fake_error
# Force set prompt
_lp_set_prompt
#########
# TESTS #
#########
echo "FULL PROMPT"
log_prompt
assert_has Battery_Mark BATT $LINENO
assert_has Battery_Level 55% $LINENO
assert_has Load_Mark LOAD $LINENO
assert_has Load_Level 32% $LINENO
assert_has User "[\\\u" $LINENO
if [[ $LP_HOSTNAME_ALWAYS == 0 ]] ; then
assert_not Hostname "\\\h" $LINENO
else
assert_has Hostname "\\\h" $LINENO
fi
assert_has Perms : $LINENO
assert_has Path $(pwd | sed -e "s|$HOME|~|") $LINENO
assert_has Proxy proxy $LINENO
assert_has Error 127 $LINENO
assert_has GIT_Branch fake_test $LINENO
assert_has GIT_Changes "+2/-1" $LINENO
assert_has GIT_Commits 111 $LINENO
assert_has GIT_Untrack untracked $LINENO
assert_has GIT_Mark gitmark $LINENO
# start hiding features
echo "DISABLE BATTERY"
export LP_ENABLE_BATT=0
_lp_set_prompt
log_prompt
assert_not Battery_Mark BATT $LINENO
assert_not Battery_level 55% $LINENO
assert_not Error 127 $LINENO
echo "HIDE BATTERY LEVEL"
export LP_ENABLE_BATT=1
export LP_BATTERY_THRESHOLD=50
_lp_set_prompt
log_prompt
assert_has Battery_Mark BATT $LINENO
assert_not Battery_level 55% $LINENO
assert_not Error 127 $LINENO
alias acpi="echo 'Battery 0: Full, 100%'"
_lp_set_prompt
log_prompt
assert_not Battery_Mark BATT $LINENO
echo "DISABLE LOAD"
export LP_ENABLE_LOAD=0
_lp_set_prompt
log_prompt
assert_not Load_Mark LOAD $LINENO
assert_not Load_Level 32% $LINENO
echo "HIDE LOAD"
export LP_ENABLE_LOAD=1
export LP_LOAD_THRESHOLD=40
_lp_set_prompt
log_prompt
assert_not Load_Mark LOAD $LINENO
assert_not Load_Level 32% $LINENO
echo "DISABLE PROXY"
export LP_ENABLE_PROXY=0
_lp_set_prompt
log_prompt
assert_not Proxy_Mark proxy $LINENO
echo "NO PROXY"
export LP_ENABLE_PROXY=1
export http_proxy=""
_lp_set_prompt
log_prompt
assert_not Proxy_Mark proxy $LINENO
echo "DISABLE GIT"
export LP_ENABLE_GIT=0
_lp_set_prompt
log_prompt
assert_not GIT_Branch fake_test $LINENO
assert_not GIT_Changes "+2/-1" $LINENO
assert_not GIT_Commits 111 $LINENO
assert_not GIT_Untrack untracked $LINENO
assert_not GIT_Mark gitmark $LINENO
assert_has User_Mark $ $LINENO
echo "NO GIT"
export LP_ENABLE_GIT=1
alias git="echo"
_lp_set_prompt
log_prompt
assert_not GIT_Branch fake_test $LINENO
assert_not GIT_Changes "+2/-1" $LINENO
assert_not GIT_Commits 111 $LINENO
assert_not GIT_Untrack untracked $LINENO
assert_not GIT_Mark gitmark $LINENO
assert_has User_Mark $ $LINENO
# create a deep dir tree
current=$PWD
for d in $(seq 20) ; do
dirname=""
for i in $(seq 5); do
dirname="$dirname$d"
done
mkdir -p $dirname
cd $dirname
done
echo "DISABLE SHORTEN PATH"
export LP_ENABLE_SHORTEN_PATH=0
_lp_set_prompt
log_prompt
assert_has Path "$(pwd | sed -e "s|$HOME|~|")" $LINENO
echo "ENABLE SHORTEN PATH"
export LP_ENABLE_SHORTEN_PATH=1
export LP_PATH_LENGTH=35
export LP_PATH_KEEP=1
_lp_set_prompt
log_prompt
assert_has Short_Path " … " $LINENO
# get back out of the deep tree
cd $current
echo "LOCAL HOST NAME"
_lp_set_prompt
log_prompt
# As the hostname is set once at the script start,
# and not re-interpret at each prompt,
# we cannot export the option in the test script.
# We thus rely on the existing config.
if [[ $LP_HOSTNAME_ALWAYS == 0 ]] ; then
assert_not Hostname "\\\h" $LINENO
else
assert_has Hostname "\\\h" $LINENO
fi
echo "prompt_OFF"
prompt_OFF
log_prompt
assert_is Prompt "$ " $LINENO
echo "prompt_on"
prompt_on
export LP_USER_ALWAYS=1
log_prompt
assert_has User "\\\u" $LINENO
assert_has Perms : $LINENO
assert_has Path $(pwd | sed -e "s|$HOME|~|") $LINENO
# assert_has Path "\\\w" $LINENO
assert_has Prompt "$ " $LINENO

View File

@ -0,0 +1,15 @@
root = true
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[package.json]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false

View File

@ -0,0 +1 @@
* text=auto

View File

@ -0,0 +1,34 @@
<!-- TIP: Hit 'Preview' for a more readable version of this template -->
### General information
- Pure version: 1.x.x
- ZSH version: 5.x.x
- Terminal program & version: <!-- e.g. Hyper 1.0.0, iTerm 3.0.0, Terminal 2.7.1, xterm 327, other? -->
- Operating system: <!-- e.g. macOS Sierra 10.12.1 -->
- ZSH framework: <!-- e.g. oh-my-zsh, prezto, antigen, antibody, zplug, other? -->
I have:
- [ ] Tested with another terminal program and can reproduce the issue: <!-- e.g. iTerm, etc. -->
- [ ] Followed the [Integration](https://github.com/sindresorhus/pure#integration) instructions for my framework
### Problem description
### Reproduction steps
1.
2.
3.
### My `.zshrc`:
<!--
Please provide a minimal `.zshrc` that reproduces the issue.
Try to remove everything that that does not affect the issue, the fewer lines, the better.
-->
```shell
autoload -U promptinit; promptinit
prompt pure
```

View File

@ -0,0 +1,26 @@
# Author: Sindre Sorhus
# Maintainer: Pat Brisbin <pbrisbin@gmail.com>
# Contributor: Emil Falk <emph@emph.se>
pkgname=zsh-pure-prompt-git
pkgver=r61.7d3b317
pkgrel=1
pkgdesc='A minimal and pure prompt for zsh.'
arch=('any')
url='https://github.com/sindresorhus/pure'
license=('MIT')
depends=('zsh' 'git')
source=("$pkgname::git://github.com/sindresorhus/pure.git")
sha256sums=('SKIP')
pkgver() {
cd $srcdir/$pkgname
printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
}
package() {
cd $srcdir/$pkgname
install -Dm644 pure.zsh \
"$pkgdir/usr/share/zsh/functions/Prompts/prompt_pure_setup"
install -Dm644 async.zsh \
"$pkgdir/usr/share/zsh/functions/async"
}

View File

@ -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 (<job_name> <return_code> <stdout> <duration> <stderr>).
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 <worker_name> <callback_function>
#
# 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 <worker_name> <my_function> [<function_params>]
#
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 <worker_name> <callback_function>
#
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 <worker_name>
#
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 <worker_name>
#
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 <worker_name> [-u] [-n] [-p <pid>]
#
# 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 <worker_name_1> [<worker_name_2>]
#
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 "$@"

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,45 @@
{
"name": "pure-prompt",
"version": "1.5.1",
"description": "Pretty, minimal and fast ZSH prompt",
"license": "MIT",
"repository": "sindresorhus/pure",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
{
"name": "Mathias Fredriksson",
"url": "github.com/mafredri"
}
],
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"postinstall": "PURE_DEST=/usr/local/share/zsh/site-functions npm run --silent postinstall-link && exit 0; PURE_DEST=\"$PWD/functions\" npm run postinstall-link && npm run postinstall-fail-instructions",
"postinstall-link": "mkdir -p \"$PURE_DEST\" && ln -sf \"$PWD/pure.zsh\" \"$PURE_DEST/prompt_pure_setup\" && ln -sf \"$PWD/async.zsh\" \"$PURE_DEST/async\"",
"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')\""
},
"files": [
"pure.zsh",
"async.zsh"
],
"keywords": [
"zsh",
"zshell",
"sh",
"shell",
"bash",
"pure",
"prompt",
"theme",
"git",
"async",
"fast",
"minimal",
"pretty"
]
}

View File

@ -0,0 +1 @@
pure.zsh

View File

@ -0,0 +1,436 @@
# Pure
# by Sindre Sorhus
# https://github.com/sindresorhus/pure
# MIT License
# For my own and others sanity
# 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
# 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:=5} )) && {
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'
# print preprompt
prompt_pure_preprompt_render precmd
}
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() {
if [[ -n $prompt_pure_git_fetch_pattern ]]; then
# detect when git is performing pull/fetch (including git aliases).
if [[ $2 =~ (git|hub)\ (.*\ )?($prompt_pure_git_fetch_pattern)(\ .*)?$ ]]; then
# we must flush the async jobs to cancel our git fetch in order
# to avoid conflicts with the user issued pull / fetch.
async_flush_jobs 'prompt_pure'
fi
fi
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=242
[[ -n ${prompt_pure_git_last_dirty_check_timestamp+x} ]] && git_color=red
# construct preprompt, beginning with path
local preprompt="%F{blue}%~%f"
# 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{yellow}${prompt_pure_cmd_exec_time}%f"
# make sure prompt_pure_last_preprompt is a global array
typeset -g -a prompt_pure_last_preprompt
# if executing through precmd, do not perform fancy terminal editing
if [[ "$1" == "precmd" ]]; then
print -P "\n${preprompt}"
else
# only redraw if the expanded preprompt has changed
[[ "${prompt_pure_last_preprompt[2]}" != "${(S%%)preprompt}" ]] || return
# calculate length of preprompt and store it locally in preprompt_length
integer preprompt_length lines
prompt_pure_string_length_to_var "${preprompt}" "preprompt_length"
# calculate number of preprompt lines for redraw purposes
(( lines = ( preprompt_length - 1 ) / COLUMNS + 1 ))
# calculate previous preprompt lines to figure out how the new preprompt should behave
integer last_preprompt_length last_lines
prompt_pure_string_length_to_var "${prompt_pure_last_preprompt[1]}" "last_preprompt_length"
(( last_lines = ( last_preprompt_length - 1 ) / COLUMNS + 1 ))
# clr_prev_preprompt erases visual artifacts from previous preprompt
local clr_prev_preprompt
if (( last_lines > lines )); then
# move cursor up by last_lines, clear the line and move it down by one line
clr_prev_preprompt="\e[${last_lines}A\e[2K\e[1B"
while (( last_lines - lines > 1 )); do
# clear the line and move cursor down by one
clr_prev_preprompt+='\e[2K\e[1B'
(( last_lines-- ))
done
# move cursor into correct position for preprompt update
clr_prev_preprompt+="\e[${lines}B"
# create more space for preprompt if new preprompt has more lines than last
elif (( last_lines < lines )); then
# move cursor using newlines because ansi cursor movement can't push the cursor beyond the last line
printf $'\n'%.0s {1..$(( lines - last_lines ))}
fi
# disable clearing of line if last char of preprompt is last column of terminal
local clr='\e[K'
(( COLUMNS * lines == preprompt_length )) && clr=
# modify previous preprompt
print -Pn "${clr_prev_preprompt}\e[${lines}A\e[${COLUMNS}D${preprompt}${clr}\n"
if [[ $prompt_subst_status = 'on' ]]; then
# re-eanble prompt_subst for expansion on PS1
setopt prompt_subst
fi
# redraw prompt (also resets cursor position)
zle && zle .reset-prompt
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
# print the preprompt
prompt_pure_preprompt_render "precmd"
# remove the prompt_pure_cmd_timestamp, indicating that precmd has completed
unset prompt_pure_cmd_timestamp
}
prompt_pure_async_git_aliases() {
setopt localoptions noshwordsplit
local dir=$1
local -a gitalias pullalias
# we enter repo to get local aliases as well.
builtin cd -q $dir
# list all aliases and split on newline.
gitalias=(${(@f)"$(command git config --get-regexp "^alias\.")"})
for line in $gitalias; do
parts=(${(@)=line}) # split line on spaces
aliasname=${parts[1]#alias.} # grab the name (alias.[name])
shift parts # remove aliasname
# check alias for pull or fetch (must be exact match).
if [[ $parts =~ ^(.*\ )?(pull|fetch)(\ .*)?$ ]]; then
pullalias+=($aliasname)
fi
done
print -- ${(j:|:)pullalias} # join on pipe (for use in regex).
}
# 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
unset prompt_pure_git_fetch_pattern
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
if [[ -z $prompt_pure_git_fetch_pattern ]]; then
# we set the pattern here to avoid redoing the pattern check until the
# working three has changed. pull and fetch are always valid patterns.
prompt_pure_git_fetch_pattern="pull|fetch"
async_job "prompt_pure" prompt_pure_async_git_aliases $working_tree
fi
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_aliases)
if [[ -n $output ]]; then
# append custom git aliases to the predefined ones.
prompt_pure_git_fetch_pattern+="|$output"
fi
;;
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
# 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'
# prompt turns red if the previous command didn't exit with 0
PROMPT='%(?.%F{magenta}.%F{red})${PURE_PROMPT_SYMBOL:-}%f '
}
prompt_pure_setup "$@"

View File

@ -0,0 +1,236 @@
# Pure
> Pretty, minimal and fast ZSH prompt
<img src="screenshot.png" width="864">
## Overview
Most prompts are cluttered, ugly and slow. I wanted something visually pleasing that stayed out of my way.
### Why?
- Comes with the perfect prompt character.
Author went through the whole Unicode range to find it.
- Shows `git` branch and whether it's dirty (with a `*`).
- Indicates when you have unpushed/unpulled `git` commits with up/down arrows. *(Check is done asynchronously!)*
- Prompt character turns red if the last command didn't exit with `0`.
- Command execution time will be displayed if it exceeds the set threshold.
- Username and host only displayed when in an SSH session.
- Shows the current path in the title and the [current folder & command](screenshot-title-cmd.png) when a process is running.
- Makes an excellent starting point for your own custom prompt.
## Install
Can be installed with `npm` or manually. Requires Git 2.0.0+ and ZSH 5.2+. Older versions of ZSH are known to work, but they are **not** recommended.
### npm
```console
$ npm install --global pure-prompt
```
That's it. Skip to [Getting started](#getting-started).
### Manually
1. Either…
- Clone this repo
- add it as a submodule, or
- just download `pure.zsh` and `async.zsh`
2. Symlink `pure.zsh` to somewhere in [`$fpath`](http://www.refining-linux.org/archives/46/ZSH-Gem-12-Autoloading-functions/) with the name `prompt_pure_setup`.
3. Symlink `async.zsh` in `$fpath` with the name `async`.
#### Example
```console
$ ln -s "$PWD/pure.zsh" /usr/local/share/zsh/site-functions/prompt_pure_setup
$ ln -s "$PWD/async.zsh" /usr/local/share/zsh/site-functions/async
```
*Run `echo $fpath` to see possible locations.*
For a user-specific installation (which would not require escalated privileges), simply add a directory to `$fpath` for that user:
```sh
# .zshenv or .zshrc
fpath=( "$HOME/.zfunctions" $fpath )
```
Then install the theme there:
```console
$ ln -s "$PWD/pure.zsh" "$HOME/.zfunctions/prompt_pure_setup"
$ ln -s "$PWD/async.zsh" "$HOME/.zfunctions/async"
```
## Getting started
Initialize the prompt system (if not so already) and choose `pure`:
```sh
# .zshrc
autoload -U promptinit; promptinit
prompt pure
```
## Options
### `PURE_CMD_MAX_EXEC_TIME`
The max execution time of a process before its run time is shown when it exits. Defaults to `5` seconds.
### `PURE_GIT_PULL`
Set `PURE_GIT_PULL=0` to prevent Pure from checking whether the current Git remote has been updated.
### `PURE_GIT_UNTRACKED_DIRTY`
Set `PURE_GIT_UNTRACKED_DIRTY=0` to not include untracked files in dirtiness check. Only really useful on extremely huge repos like the WebKit repo.
### `PURE_GIT_DELAY_DIRTY_CHECK`
Time in seconds to delay git dirty checking for large repositories (git status takes > 2 seconds). The check is performed asynchronously, this is to save CPU. Defaults to `1800` seconds.
### `PURE_PROMPT_SYMBOL`
Defines the prompt symbol. The default value is ``.
### `PURE_GIT_DOWN_ARROW`
Defines the git down arrow symbol. The default value is `⇣`.
### `PURE_GIT_UP_ARROW`
Defines the git up arrow symbol. The default value is `⇡`.
## Example
```sh
# .zshrc
autoload -U promptinit; promptinit
# optionally define some options
PURE_CMD_MAX_EXEC_TIME=10
prompt pure
```
## Tips
In the screenshot you see Pure running in [Hyper](https://hyper.is) with the [hyper-snazzy](https://github.com/sindresorhus/hyper-snazzy) theme and Menlo font.
The [Tomorrow Night Eighties](https://github.com/chriskempson/tomorrow-theme) theme with the [Droid Sans Mono](https://fonts.google.com/specimen/Droid+Sans+Mono) font (15pt) is also a [nice combination](https://github.com/sindresorhus/pure/blob/95ee3e7618c6e2162a1e3cdac2a88a20ac3beb27/screenshot.png).<br>
*Just make sure you have anti-aliasing enabled in your terminal.*
To have commands colorized as seen in the screenshot, install [zsh-syntax-highlighting](https://github.com/zsh-users/zsh-syntax-highlighting).
## Integration
### [oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh)
1. Symlink (or copy) `pure.zsh` to `~/.oh-my-zsh/custom/pure.zsh-theme`.
2. Symlink (or copy) `async.zsh` to `~/.oh-my-zsh/custom/async.zsh`.
3. Set `ZSH_THEME="pure"` in your `.zshrc` file.
Or skip the `oh-my-zsh` integration above and simply:
1. Set `ZSH_THEME=""` in your `.zshrc` to disable oh-my-zsh themes.
2. Follow the Pure [Install](#install) instructions.
### [prezto](https://github.com/zsh-users/prezto)
Pure is bundled with Prezto. No need to install it.
Set `zstyle ':prezto:module:prompt' theme 'pure'` in `~/.zpreztorc`.
### [zim](https://github.com/Eriner/zim)
Pure is bundled with Zim. No need to install it.
Set `zprompt_theme='pure'` in `~/.zimrc`.
### [antigen](https://github.com/zsh-users/antigen)
Update your `.zshrc` file with the following two lines (order matters). Do not use the `antigen theme` function.
```sh
antigen bundle mafredri/zsh-async
antigen bundle sindresorhus/pure
```
### [antibody](https://github.com/getantibody/antibody)
Update your `.zshrc` file with the following two lines (order matters):
```sh
antibody bundle mafredri/zsh-async
antibody bundle sindresorhus/pure
```
### [zplug](https://github.com/zplug/zplug)
Update your `.zshrc` file with the following two lines:
```sh
zplug mafredri/zsh-async, from:github
zplug sindresorhus/pure, use:pure.zsh, from:github, as:theme
```
## FAQ
### My preprompt is missing when I clear the screen with Ctrl+L
Pure doesn't register its custom *clear-screen* widget if it has been previously modified. If you haven't registered your own zle widget with `zle -N clear-screen custom-clear-screen` it might have been done by third-party modules. For example `zsh-syntax-highlighting` and `zsh-history-substring-search` are known to do this and they should for that reason be **the very last thing** in your `.zshrc` (as pointed out in their documentation).
To find out the culprit that is overriding your *clear-screen* widget, you can run the following command: `zle -l | grep clear-screen`.
### I am stuck in a shell loop in my terminal that ask me to authenticate. What should I do ?
[This is a known issue](https://github.com/sindresorhus/pure/issues/76).
Using `git pull` when you get the username prompt should help you to break the loop by giving you a real prompt for this. **[This has been fixed in git 2.3](https://github.com/sindresorhus/pure/commit/f43ab97e1cf4a276b7a6e33eac055ee16610be15)**
### I am seeing the error `zpty: can't open pseudo terminal: bad file descriptor`.
[This is a known issue](https://github.com/sindresorhus/pure/issues/117). `zsh/zpty` requires either legacy bsd ptys or access to `/dev/ptmx`. Here are some known solutions.
#### Gentoo
```console
$ sudo sh -c "echo 'SANDBOX_WRITE=\"/dev/ptmx\"' > /etc/sandbox.d/10zsh"
$ sudo emerge -1 zsh
```
#### FreeBSD 10.1
On a default setup, running the command `kldload pty` should do the trick. If you have a custom kernel, you might need to add `device pty` to the configuration file ([example](https://github.com/nbari/freebsd/blob/58646a9c3c4aaabf6f6467ff505f27f09e29dc75/kernels/xen.kernel#L188)).
## Ports
* **Bash**
* [sapegin/dotfiles](https://github.com/sapegin/dotfiles)s [prompt](https://github.com/sapegin/dotfiles/blob/dd063f9c30de7d2234e8accdb5272a5cc0a3388b/includes/bash_prompt.bash) and [color theme](https://github.com/sapegin/dotfiles/tree/master/color) for `Terminal.app`.
* **Fish**
* [brandonweiss/pure.fish](https://github.com/brandonweiss/pure.fish): a Pure-inspired prompt for Fish, not intended to have feature parity.
* [rafaelrinaldi/pure](https://github.com/rafaelrinaldi/pure), support for bare Fish and various framework ([Oh-My-Fish](https://github.com//oh-my-fish/oh-my-fish), [Fisherman](https://github.com//fisherman/fisherman) and [Wahoo](https://github.com//bucaran/wahoo)).
* **Zsh**
* [therealklanni/purity](https://github.com/therealklanni/purity): a more compact current working directory, important details on the main prompt line, and extra Git indicators.
* [intelfx/pure](https://github.com/intelfx/pure): Solarized-friendly colors, highly verbose and fully async Git integration
## Team
[![Sindre Sorhus](https://avatars.githubusercontent.com/u/170270?v=3&s=100)](http://sindresorhus.com) | [![Mathias Fredriksson](https://avatars.githubusercontent.com/u/147409?v=3&s=100)](https://github.com/mafredri)
---|---
[Sindre Sorhus](http://sindresorhus.com) | [Mathias Fredriksson](https://github.com/mafredri)
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

View File

@ -0,0 +1 @@
../external-themes/pure/async.zsh

View File

@ -0,0 +1 @@
../external-themes/liquidprompt/liquidprompt

View File

@ -0,0 +1 @@
../themes/eriner.zsh-theme

View File

@ -0,0 +1 @@
../themes/gitster.zsh-theme

View File

@ -0,0 +1 @@
../external-themes/lean/prompt_lean_setup

View File

@ -0,0 +1,13 @@
prompt_liquidprompt_setup() {
autoload -Uz ex-liquidprompt
ext-liquidprompt
prompt_opts=(cr subst percent)
}
prompt_liquidprompt_preview() {
_lp_set_prompt
prompt_preview_theme liquidprompt
}
prompt_liquidprompt_setup "$@"

View File

@ -0,0 +1 @@
../themes/magicmace.zsh-theme

View File

@ -0,0 +1 @@
../themes/minimal.zsh-theme

View File

@ -0,0 +1 @@
../external-themes/pure/pure.zsh

View File

@ -0,0 +1 @@
../themes/steeef.zsh-theme

View File

@ -0,0 +1,13 @@
# shortens the pwd for use in prompt
local current_dir="${1:-${PWD}}"
local return_dir='~'
current_dir="${current_dir/#${HOME}/~}"
# if we aren't in ~
if [[ ${current_dir} != '~' ]]; then
return_dir="${${${${(@j:/:M)${(@s:/:)current_dir}##.#?}:h}%/}//\%/%%}/${${current_dir:t}//\%/%%}"
fi
print ${return_dir}

Binary file not shown.

View File

@ -0,0 +1,8 @@
#
# load user-defined prompt
#
if [[ ! ${TERM} == (linux|*bsd*|dumb) ]] && (( ${+zprompt_theme} )); then
autoload -Uz promptinit && promptinit
prompt ${zprompt_theme}
fi

View File

@ -0,0 +1,117 @@
# vim:ts=2 sw=2 sts=2 ft=zsh
#
# Eriner's Theme - fork of agnoster
# A Powerline-inspired theme for ZSH
#
# In order for this theme to render correctly, you will need a font with
# powerline symbols. A simple way to add the powerline symbols is to follow the
# instructions here:
# https://simplyian.com/2014/03/28/using-powerline-symbols-with-your-current-font/
#
# The aim of this theme is to only show you *relevant* information. Like most
# prompts, it will only show git information when in a git working directory.
# However, it goes a step further: everything from the current user and
# hostname to whether the last call exited with an error to whether background
# jobs are running in this shell will all be displayed automatically when
# appropriate.
#
# Requires the `git-info` zmodule to be included in the .zimrc file.
### Segment drawing
# Utility functions to make it easy and re-usable to draw segmented prompts.
local prompt_eriner_bg
# Begin a segment. Takes two arguments, background color and contents of the
# new segment.
prompt_eriner_segment() {
print -n "%K{$1}"
if [[ -n ${prompt_eriner_bg} ]]; then
print -n "%F{${prompt_eriner_bg}}"
fi
print -n "$2"
prompt_eriner_bg=$1
}
# End the prompt, closing last segment.
prompt_eriner_end() {
print -n "%k%F{${prompt_eriner_bg}}%f "
}
### Prompt components
# Each component will draw itself, or hide itself if no information needs to be
# shown.
# Status: Was there an error? Am I root? Are there background jobs? Who and
# where am I (user@hostname)?
prompt_eriner_status() {
local segment=''
(( ${RETVAL} )) && segment+=' %F{red}✘'
(( ${UID} == 0 )) && segment+=' %F{yellow}⚡'
(( $(jobs -l | wc -l) > 0 )) && segment+=' %F{cyan}⚙'
if [[ ${USER} != ${DEFAULT_USER} || -n ${SSH_CLIENT} ]]; then
segment+=' %F{%(!.yellow.default)}${USER}@%m'
fi
if [[ -n ${segment} ]]; then
prompt_eriner_segment black "${segment} "
fi
}
# Ranger: <https://github.com/ranger/ranger>, which can spawn a shell under its
# own process.
prompt_eriner_ranger() {
if (( ${RANGER_LEVEL} )); then
prompt_eriner_segment blue ' %F{black}r '
fi
}
# Pwd: current working directory.
prompt_eriner_pwd() {
prompt_eriner_segment cyan " %F{black}$(short_pwd) "
}
# Git: branch/detached head, dirty status.
prompt_eriner_git() {
if [[ -n ${git_info} ]]; then
local indicator
[[ ${git_info[color]} == yellow ]] && indicator='± '
prompt_eriner_segment ${git_info[color]} " %F{black}${(e)git_info[prompt]} ${indicator}"
fi
}
### Main prompt
prompt_eriner_main() {
RETVAL=$?
prompt_eriner_status
prompt_eriner_ranger
prompt_eriner_pwd
prompt_eriner_git
prompt_eriner_end
}
prompt_eriner_precmd() {
(( ${+functions[git-info]} )) && git-info
}
prompt_eriner_setup() {
autoload -Uz colors && colors
autoload -Uz add-zsh-hook
prompt_opts=(cr percent subst)
add-zsh-hook precmd prompt_eriner_precmd
zstyle ':zim:git-info:branch' format ' %b'
zstyle ':zim:git-info:commit' format '➦ %c'
zstyle ':zim:git-info:action' format ' (%s)'
zstyle ':zim:git-info:clean' format 'green'
zstyle ':zim:git-info:dirty' format 'yellow'
zstyle ':zim:git-info:keys' format \
'prompt' '%b%c%s' \
'color' '%C%D'
PROMPT='${(e)$(prompt_eriner_main)}'
RPROMPT=''
}
prompt_eriner_setup "$@"

View File

@ -0,0 +1,44 @@
#
# Gitster theme
# https://github.com/shashankmehta/dotfiles/blob/master/thesetup/zsh/.oh-my-zsh/custom/themes/gitster.zsh-theme
#
# Requires the `git-info` zmodule to be included in the .zimrc file.
prompt_gitster_status() {
print -n '%(?:%F{green}➜:%F{red}➜) '
}
prompt_gitster_pwd() {
prompt_short_dir=$(short_pwd)
git_root=$(command git rev-parse --show-toplevel 2> /dev/null) && prompt_short_dir=${prompt_short_dir#${$(short_pwd $git_root):h}/}
print -n "%F{white}${prompt_short_dir}"
}
prompt_gitster_git() {
[[ -n ${git_info} ]] && print -n "${(e)git_info[prompt]}"
}
prompt_gitster_precmd() {
(( ${+functions[git-info]} )) && git-info
}
prompt_gitster_setup() {
autoload -Uz colors && colors
autoload -Uz add-zsh-hook
prompt_opts=(cr percent subst)
add-zsh-hook precmd prompt_gitster_precmd
zstyle ':zim:git-info:branch' format '%b'
zstyle ':zim:git-info:commit' format '%c'
zstyle ':zim:git-info:clean' format '%F{green}✓'
zstyle ':zim:git-info:dirty' format '%F{yellow}✗'
zstyle ':zim:git-info:keys' format \
'prompt' ' %F{cyan}%b%c %C%D'
PROMPT='$(prompt_gitster_status)$(prompt_gitster_pwd)$(prompt_gitster_git)%f '
RPROMPT=''
}
prompt_gitster_setup "$@"

View File

@ -0,0 +1,73 @@
#
# magicmace theme
# Ideas and code taken from:
# xero's zsh prompt <http://code.xero.nu/dotfiles>
# eriner's eriner prompt <https://github.com/Eriner/zim/blob/master/modules/prompt/themes/eriner.zsh-theme>
#
# Requires the `git-info` zmodule to be included in the .zimrc file.
# Global variables
function {
COLOR_ROOT="%F{red}"
COLOR_USER="%F{cyan}"
COLOR_NORMAL="%F{white}"
COLOR_ERROR="%F{red}"
if (( ${EUID} )); then
COLOR_USER_LEVEL=${COLOR_USER}
else
COLOR_USER_LEVEL=${COLOR_ROOT}
fi
}
# Status:
# - was there an error?
# - are there background jobs?
# - are we in a ranger session?
prompt_magicmace_status() {
local symbols=""
(( ${RETVAL} )) && symbols+="${COLOR_ERROR}${RETVAL}${COLOR_NORMAL}" # $? for error.
(( $(jobs -l | wc -l) > 0 )) && symbols+='b' # 'b' for background.
(( ${RANGER_LEVEL} )) && symbols+='r' # 'r' for... you guessed it!
[[ -n ${symbols} ]] && print -n "─${COLOR_NORMAL}${symbols}${COLOR_USER_LEVEL}─"
}
prompt_magicmace_git() {
[[ -n ${git_info} ]] && print -n "${(e)git_info[prompt]}"
}
prompt_magicmace_precmd() {
# While it would be apt to have this as a local variable in prompt_status(),
# $? (returned value) and ${(%):-%?} ("The return status of the last command
# executed just before the prompt") both change before executing the function.
# Is this perhaps because prompt_status _is_ here?
# We could also just set $? as an argument, and thus get our nifty local variable,
# but that's stretching it, and makes the code harder to read.
RETVAL=$?
(( ${+functions[git-info]} )) && git-info
}
prompt_magicmace_setup() {
autoload -Uz colors && colors
autoload -Uz add-zsh-hook
prompt_opts=(cr percent subst)
add-zsh-hook precmd prompt_magicmace_precmd
zstyle ':zim:git-info:branch' format '%b'
zstyle ':zim:git-info:commit' format '%c...'
zstyle ':zim:git-info:dirty' format '*'
zstyle ':zim:git-info:ahead' format '↑'
zstyle ':zim:git-info:behind' format '↓'
zstyle ':zim:git-info:keys' format \
'prompt' '─[${COLOR_NORMAL}%b%c%D%A%B${COLOR_USER_LEVEL}]'
# Call git directly, ignoring aliases under the same name.
PROMPT='${COLOR_USER_LEVEL}$(prompt_magicmace_status)[${COLOR_NORMAL}$(short_pwd)${COLOR_USER_LEVEL}]$(prompt_magicmace_git)── ─%f '
RPROMPT=''
}
prompt_magicmace_setup "$@"

View File

@ -0,0 +1,98 @@
#
# Minimal theme
# https://github.com/S1cK94/minimal
#
minimal_user() {
print "%(!.$on_color.$off_color)$prompt_char%f"
}
minimal_jobs() {
print "%(1j.$on_color.$off_color)$prompt_char%f"
}
minimal_vimode(){
local ret=""
case $KEYMAP in
main|viins)
ret+="$on_color"
;;
vicmd)
ret+="$off_color"
;;
esac
ret+="$prompt_char%f"
print "$ret"
}
minimal_status() {
print "%(0?.$on_color.$err_color)$prompt_char%f"
}
minimal_path() {
local path_color="%F{244}"
local rsc="%f"
local sep="$rsc/$path_color"
print "$path_color$(sed s_/_${sep}_g <<< $(short_pwd))$rsc"
}
git_branch_name() {
local branch_name="$(command git rev-parse --abbrev-ref HEAD 2> /dev/null)"
[[ -n $branch_name ]] && print "$branch_name"
}
git_repo_status(){
local rs="$(command git status --porcelain -b)"
if $(print "$rs" | grep -v '^##' &> /dev/null); then # is dirty
print "%F{red}"
elif $(print "$rs" | grep '^## .*diverged' &> /dev/null); then # has diverged
print "%F{red}"
elif $(print "$rs" | grep '^## .*behind' &> /dev/null); then # is behind
print "%F{11}"
elif $(print "$rs" | grep '^## .*ahead' &> /dev/null); then # is ahead
print "%f"
else # is clean
print "%F{green}"
fi
}
minimal_git() {
local bname=$(git_branch_name)
if [[ -n ${bname} ]]; then
local infos="$(git_repo_status)${bname}%f"
print " $infos"
fi
}
function zle-line-init zle-line-finish zle-keymap-select {
zle reset-prompt
zle -R
}
prompt_minimal_precmd() {
zle -N zle-line-init
zle -N zle-keymap-select
zle -N zle-line-finish
PROMPT='$(minimal_user)$(minimal_jobs)$(minimal_vimode)$(minimal_status) '
RPROMPT='$(minimal_path)$(minimal_git)'
}
prompt_minimal_setup() {
prompt_char=""
on_color="%F{green}"
off_color="%f"
err_color="%F{red}"
autoload -Uz add-zsh-hook
add-zsh-hook precmd prompt_minimal_precmd
prompt_opts=(cr subst percent)
}
prompt_minimal_setup "$@"

View File

@ -0,0 +1,102 @@
# prompt style and colors based on Steve Losh's Prose theme:
# http://github.com/sjl/oh-my-zsh/blob/master/themes/prose.zsh-theme
#
# vcs_info modifications from Bart Trojanowski's zsh prompt:
# http://www.jukie.net/bart/blog/pimping-out-zsh-prompt
#
# git untracked files modification from Brian Carper:
# http://briancarper.net/blog/570/git-info-in-your-zsh-prompt
export VIRTUAL_ENV_DISABLE_PROMPT=1
virtualenv_info() {
[ ${VIRTUAL_ENV} ] && print '('${fg[blue]}${VIRTUAL_ENV:t}%{${reset_color}%}') '
}
steeef_preexec() {
case "$(history $HISTCMD)" in
*git*)PR_GIT_UPDATE=1
;;
*svn*)PR_GIT_UPDATE=1
;;
esac
}
steeef_chpwd() {
PR_GIT_UPDATE=1
}
prompt_steeef_precmd() {
if [[ -n "$PR_GIT_UPDATE" ]] ; then
# check for untracked files or updated submodules, since vcs_info doesn't
if git ls-files --other --exclude-standard 2> /dev/null | grep -q "."; then
PR_GIT_UPDATE=1
FMT_BRANCH="(%{$turquoise%}%b%u%c%{$hotpink%}●${PR_RST})"
else
FMT_BRANCH="(%{$turquoise%}%b%u%c${PR_RST})"
fi
zstyle ':vcs_info:*:prompt:*' formats "${FMT_BRANCH} "
vcs_info 'prompt'
fi
PROMPT='
%{$purple%}%n${${reset_color}%} at %{$orange%}%m${${reset_color}%} in %{$limegreen%}%~${${reset_color}%} $vcs_info_msg_0_$(virtualenv_info)%{${reset_color}%}
%(!.#.$) '
}
prompt_steeef_setup() {
#use extended color pallete if available
if [[ ${TERM} == *256* || ${TERM} == *rxvt* ]]; then
turquoise="%F{81}"
orange="%F{166}"
purple="%F{135}"
hotpink="%F{161}"
limegreen="%F{118}"
else
turquoise="%F{cyan}"
orange="%F{yellow}"
purple="%F{magenta}"
hotpink="%F{red}"
limegreen="%F{green}"
fi
# enable VCS systems you use
zstyle ':vcs_info:*' enable git svn
# check-for-changes can be really slow.
# you should disable it, if you work with large repositories
zstyle ':vcs_info:*:prompt:*' check-for-changes true
# set formats
# %b - branchname
# %u - unstagedstr (see below)
# %c - stagedstr (see below)
# %a - action (e.g. rebase-i)
# %R - repository path
# %S - path in the repository
PR_RST="%f"
FMT_BRANCH="(%{$turquoise%}%b%u%c${PR_RST})"
FMT_ACTION="(%{$limegreen%}%a${PR_RST})"
FMT_UNSTAGED="%{$orange%}●"
FMT_STAGED="%{$limegreen%}●"
zstyle ':vcs_info:*:prompt:*' unstagedstr "${FMT_UNSTAGED}"
zstyle ':vcs_info:*:prompt:*' stagedstr "${FMT_STAGED}"
zstyle ':vcs_info:*:prompt:*' actionformats "${FMT_BRANCH}${FMT_ACTION}"
zstyle ':vcs_info:*:prompt:*' formats "${FMT_BRANCH}"
zstyle ':vcs_info:*:prompt:*' nvcsformats ""
PR_GIT_UPDATE=1
autoload -Uz add-zsh-hook
autoload -Uz vcs_info
autoload -Uz colors && colors
add-zsh-hook preexec steeef_preexec
add-zsh-hook chpwd steeef_chpwd
add-zsh-hook precmd prompt_steeef_precmd
prompt_opts=(cr subst percent)
}
prompt_steeef_setup "$@"