2014-08-17 22:54:05 +02:00
# /etc/zsh/zshrc ou ~/.zshrc
# Fichier de configuration principal de zsh, lu au lancement des shells interactifs
# (et non des shells d'interprétation de fichier)
# Formation Debian GNU/Linux par Alexis de Lattre
# http://formation-debian.via.ecp.fr/
################
# 1. Les alias #
################
# Gestion du 'ls' : couleur & ne touche pas aux accents
alias ls = 'ls --classify --tabsize=0 --literal --color=auto --show-control-chars --human-readable'
# Copie en récursif et qui garde la date des fichiers copiés
#alias cp='cp -Rp'
2015-02-26 14:20:54 +01:00
alias cp = 'cp -R' # **cp** copy files and directories recursively # TEST
2014-08-17 22:54:05 +02:00
# Copie distante, ajout de la récursivité tout le temps:
alias scp = 'scp -r'
# Demande confirmation avant d'écraser un fichier
alias cP = 'cp --interactive'
alias mv = 'mv --interactive'
alias rm = 'rm --interactive'
# Raccourcis pour 'ls'
2017-08-04 16:37:24 +02:00
if [ ! $( command -v exa) ] ; then
alias ll = 'ls -l'
2022-01-12 11:46:40 +01:00
## Show hidden files
2017-08-04 16:37:24 +02:00
alias la = 'ls -lA'
2021-12-08 20:29:38 +01:00
alias llh = 'ls -l | head'
2017-08-04 16:37:24 +02:00
alias llm = 'ls -l | $PAGER'
2022-01-12 11:46:40 +01:00
## Sort by date
2017-12-11 09:45:22 +01:00
alias lll = 'ls -l -t -h -r'
alias llll = 'ls -l -t -h -r'
2017-08-04 16:37:24 +02:00
alias lld = 'ls -l -d */ -h'
alias l.= 'ls -d .*'
alias lr = 'ls -R | grep ":$" | sed -e ' \' 's/:$//' \' ' -e ' \' 's/[^-][^\/]*\//--/g' \' ' -e ' \' 's/^/ /' \' ' -e ' \' 's/-/|/' \' ''
else
2022-01-12 11:46:40 +01:00
alias ll = 'exa --color=always --long --group --git'
## Show hidden files
alias la = 'll --all'
alias llh = 'll | head'
alias llm = 'll | less'
## Sort by date
alias lll = 'll --sort=modified'
alias llll = 'll --sort=modified'
## Give a tree of current directory
alias llt = 'll --tree'
alias lld = 'll --group-directories-first'
2017-08-04 16:37:24 +02:00
alias l.= 'ls -d .*'
alias lr = 'ls -R | grep ":$" | sed -e ' \' 's/:$//' \' ' -e ' \' 's/[^-][^\/]*\//--/g' \' ' -e ' \' 's/^/ /' \' ' -e ' \' 's/-/|/' \' ''
fi
2014-08-17 22:54:05 +02:00
2021-08-09 10:01:46 +02:00
# cat with number on output lines
alias ca = 'cat -n'
# docker related
2018-09-06 11:27:16 +02:00
alias d = 'docker'
2021-08-09 10:01:46 +02:00
# Correct ip command
alias ipa = 'ip a'
# less with raw character
alias less = 'less -r'
#alias less='less --quiet'
2018-09-06 11:27:16 +02:00
2018-04-19 18:59:24 +02:00
# sudo
## Please consider using "Defaults env_keep+=HOME" configuration in sudoers {{{
### This is Ubuntu default behaviour.
### This will allow to share user's homedir/dotfiles with root throught sudo commands
## }}}
## Ensure sudo can use aliases (end whitespace) {{{
### `man zshall` partie Aliasing: "If the text ends with a space, the next word in the shell input is treated as though it were in command position for
### purposes of alias expansion. "
2017-12-12 09:07:14 +01:00
alias s = 'sudo '
2018-04-19 18:59:24 +02:00
## }}}
## sudo aliases {{{
2014-08-17 22:54:05 +02:00
if [ ${ USER } != "root" ] ; then
2017-08-04 09:17:58 +02:00
alias sc = 'sudo systemctl '
2020-12-21 15:39:10 +01:00
alias scu = 'systemctl --user'
2017-08-04 09:11:30 +02:00
alias sd = 'sudo docker'
alias si = 'sudo iptables -L -vn '
2017-08-04 09:17:58 +02:00
alias sj = 'sudo journalctl '
2017-08-04 09:50:06 +02:00
alias sn = 'sudo nft list ruleset'
2017-08-04 09:11:30 +02:00
alias sp = 'sudo puppet agent -t '
2017-12-20 08:39:22 +01:00
alias sv = 'sudo vi '
alias sz = 'sudo zsh'
2014-08-17 22:54:05 +02:00
else
2017-08-04 09:17:58 +02:00
alias sc = 'systemctl '
2021-08-09 10:01:46 +02:00
alias scu = 'systemctl --user'
2017-08-04 09:11:30 +02:00
alias sd = 'docker'
alias si = 'iptables -L -vn '
2017-08-04 09:17:58 +02:00
alias sj = 'journalctl '
2017-08-11 12:08:29 +02:00
alias sn = 'nft list ruleset'
2017-08-04 09:11:30 +02:00
alias sp = 'puppet agent -t '
2017-12-13 11:16:24 +01:00
alias vi = 'vi -S ~/.vim/vimrc '
alias sv = 'vi -S ~/.vim/vimrc '
2014-08-17 22:54:05 +02:00
fi
2018-04-19 18:59:24 +02:00
## }}}
2014-08-17 22:54:05 +02:00
# Envoyer une notification via libnotify-bin (fin d'une commande, ...)
# Nécessite le paquet libnotify-bin
alias alert = 'notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e ' \' 's/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//' \' ')"'
# Nettoyage de l'écran
alias c = 'clear'
# Liste le contenu du dossier
alias dir = 'dir --color=always'
# Page de manuel en anglais
alias mane = "LANG=C man "
# Afficher les lignes trop longues sur la ligne suivante plutot que de remplacer par un "$":
alias most = 'most -w'
2019-08-26 15:27:31 +02:00
# Commandes de gestion des paquets pour aptitude ou yum {{{
2014-08-17 22:54:05 +02:00
if [ -d /etc/apt ] ; then
2015-09-07 14:21:00 +02:00
alias acle = 'sudo aptitude clean'
alias afil = 'apt-file search'
2015-12-18 10:53:21 +01:00
alias aful = 'sudo aptitude full-upgrade'
alias ains = 'sudo aptitude install'
2021-05-27 07:08:31 +02:00
alias alis = 'apt list --upgradable'
2015-10-20 09:21:07 +02:00
alias apol = 'apt-cache policy'
2015-09-07 13:40:24 +02:00
alias apur = "sudo aptitude purge '~c'"
2015-11-11 21:55:17 +01:00
alias aupd = 'sudo apt update'
2015-12-18 10:53:21 +01:00
alias aupg = 'sudo aptitude upgrade'
2015-11-12 23:38:50 +01:00
alias arem = 'sudo aptitude remove'
2015-12-18 10:53:21 +01:00
alias apts = 'apt search'
alias asea = 'aptitude search'
2015-11-12 02:20:56 +01:00
alias asho = 'aptitude show'
2015-09-07 14:21:00 +02:00
alias aver = 'apt-show-versions'
2015-10-20 09:21:07 +02:00
alias awhy = 'aptitude why'
2015-09-07 13:40:24 +02:00
alias insexperimental = 'sudo aptitude -t experimental install'
2014-08-17 22:54:05 +02:00
else
alias up = 'yum update'
alias show = 'yum info'
alias se = 'yum search'
alias ins = 'yum install'
alias version = 'yum info &1|grep "Version"'
fi
2019-08-26 15:27:31 +02:00
# }}}
2014-08-17 22:54:05 +02:00
2019-08-26 15:27:31 +02:00
# Grep aliases {{{
2017-02-27 10:03:04 +01:00
alias grep = 'grep --color=always -i '
alias gerp = 'grep -i'
alias Grep = '\grep '
2019-08-26 15:58:43 +02:00
alias gdpkg = 'dpkg -l | grep -E -- '
alias gmount = 'mount | grep -E -- '
alias gdf = 'df | grep -E -- '
2019-08-26 15:27:31 +02:00
# }}}
2016-06-06 15:52:00 +02:00
2014-08-17 22:54:05 +02:00
# Espace disque
alias df = 'df -kTh'
2015-03-05 16:00:23 +01:00
alias dus = 'du -ch|sort -h'
alias dua = 'du -ach|sort -h'
2021-08-31 14:41:36 +02:00
alias ncdu = 'gdu'
2014-08-17 22:54:05 +02:00
# Gestion des processus:
# Si htop n'est pas installé sur la machine:
if [ ! -f "`which htop`" ] ; then
alias htop = top
fi
# Qu'est-ce qui consomme de la mémoire vive sur le système
alias wotgobblemem = 'ps -o time,ppid,pid,nice,pcpu,pmem,user,comm -A | sort -n -k 6 | tail -15'
2015-03-05 16:00:23 +01:00
# Afficher uniquement le processus à partir de ps
2021-10-03 11:15:45 +02:00
alias px = 'ps faux|grep -v grep|grep -iE -e VSZ -e '
2015-03-05 16:00:23 +01:00
2014-08-17 22:54:05 +02:00
# Décompression
alias untargz = 'tar -zxvf'
alias untarbz2 = 'tar -jxvf'
2014-09-08 10:15:54 +02:00
# Terminal multiplexer
2014-08-17 22:54:05 +02:00
alias ci = 'screen -x ssh || screen -c ~/.screen/scr.ssh_ci'
2015-08-28 11:09:46 +02:00
alias ta = 'tmux a || tmux'
2018-02-19 09:33:05 +01:00
alias td = 'tmux detach'
2014-08-17 22:54:05 +02:00
2019-08-26 15:27:31 +02:00
# Send the content of a file to a privatebin
# Needs cpaste or any other Third party clients for PrivateBin
# https://github.com/PrivateBin/PrivateBin/wiki/Third-party-clients
alias pbin = '~/repos/cpaste/cpaste --sourcecode --expire 1week --file '
## Git aliases − Try to prefix with 'gg' {{{
2019-06-19 23:31:27 +02:00
### Get status of the repo
alias ggstatus = 'git status'
### Show differences between changes and index
alias ggdiff = 'git diff'
### Show only words/characters differences
alias ggwdiff = 'git diff --color-words=. --patience'
### Add changes to index
alias ggadd = 'git add'
2021-10-03 11:15:25 +02:00
### Restore changes to be committed
alias ggrestore = 'git restore --staged'
2019-06-19 23:31:27 +02:00
### Remove files from the index
alias ggrm = 'git rm'
### Move or rename file
alias ggmv = 'git mv'
### Cancel changes
alias ggcheckout = 'git checkout --'
### Print lines matching a pattern
2019-06-27 11:34:01 +02:00
alias ggrep = 'git grep --color -n -P'
2019-06-19 23:31:27 +02:00
alias gggrep = 'git grep --color -n -P'
### Show commit logs
alias gglog = "git log --graph --full-history --all --color --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'"
### Show last 20 commits with graph
alias gglg = "git --no-pager log --graph --pretty=tformat:'%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%an %ar)%Creset' -20"
### Show all commits with graph
alias ggllg = "git log --graph --pretty=tformat:'%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%an %ar)%Creset'"
### Display all commits/changes of a file
alias ggchanges = "git log --follow -p --"
2021-09-19 23:38:29 +02:00
### Commands that might require a valid gpg-agent
#### Download any new commits
alias ggpull = 'load-gpg-agent && git pull'
#### Commit changes
alias ggco = 'load-gpg-agent && git commit'
alias ggcommit = 'load-gpg-agent && git commit'
#### Amend changes
alias ggamend = 'load-gpg-agent && git commit --amend'
#### Update remote repository
alias ggpush = 'load-gpg-agent && git push'
2019-06-19 23:31:27 +02:00
## }}}
2014-08-17 22:54:05 +02:00
# Lister les fichiers de configuration inutiles
alias purge = 'grep-status -n -sPackage -FStatus config-files'
2019-01-18 19:33:14 +01:00
## Piped alias
2014-08-17 22:54:05 +02:00
alias -g H = '| head'
alias -g T = 'tail -f'
2019-08-14 20:47:10 +02:00
alias -g G = '| grep -v grep | grep -E'
2014-08-17 22:54:05 +02:00
alias -g L = '| less'
alias -g M = "| most"
2015-08-08 22:46:53 +02:00
alias -g S = "| sort"
2015-09-04 14:47:42 +02:00
alias -g V = "| vimmanpager"
2015-08-08 22:46:53 +02:00
alias -g W = "| wc -l"
2017-09-18 10:58:08 +02:00
alias -g X = "| xclip -selection clipboard"
alias -g TM = "| tmux load-buffer -- -"
2014-08-17 22:54:05 +02:00
alias -g B = "&|"
alias -g HL = "--help"
alias -g MM = "2>&1 | most"
alias -g LL = "2>&1 | less"
alias -g CA = "2>&1 | cat -A"
alias -g NE = "2> /dev/null"
alias -g NUL = "> /dev/null 2>&1"
## Affichage de l'historique
if [ " $PAGER " = "most" ] ; then
2015-09-04 14:47:42 +02:00
# En commencant par la fin avec most (bidouillage, on est pas sensé avoir):
2014-08-17 22:54:05 +02:00
alias hist = " fc -El 0 | most + $HISTSIZE "
# Une fois dans un fichier avec most, la touche 'B' permet d'aller à la fin du fichier
else
# En commencant par la fin avec less:
2015-09-04 14:47:42 +02:00
alias hist = " fc -El 0 | $PAGER +G "
2014-08-17 22:54:05 +02:00
#alias hist="less +G ~/.zsh/history"
fi
2017-12-14 17:46:27 +01:00
alias ghist = 'fc -El 0 | grep --'
2014-08-17 22:54:05 +02:00
## Gestion des répertoires
alias u = 'cd ..'
alias cd..= 'cd ..'
alias ..= 'cd ..'
alias ...= 'cd ../..'
alias ....= 'cd ../../..'
# Revenir dans le dossier dans lequel on se trouvait précédemment
alias cd-= 'cd -'
# Afficher la pile des dossiers:
alias dirs = 'dirs -v'
# Créer les répertoires précédents si ils n'existent pas
alias mkdir = 'mkdir -p'
# Affiche l'arborescence du répertoire courant
#alias tree="find . | sed 's/[^/]*\//| /g;s/| *\([^| ]\)/+--- \1/'"
#La commande tree "basique" fait ça très bien ...
# Affiche la variable $PATH ligne par ligne
2015-10-20 09:21:07 +02:00
alias path = 'printf %s $PATH | tr ":" "\n"'
2014-08-17 22:54:05 +02:00
# Edite le dernier fichier d'un dossier
## Fonctionement:
## (. correspond au fichier
## om les classent par date de modification
## [1] choisit le premier
## désactive les options GLOB_DOTS
alias vil = 'vi *(.om[1]^D)'
# Lancer vi pour qu'il ne conserve aucune trace du fichier
## Faire précéder la commande d'un espace empêche l'enregistrement dans l'historique du shell
alias vnb = 'vi -n "+set noundofile" "+set nobackup"'
# Différence entre deux fichiers
alias diff = 'colordiff -u'
2014-09-27 11:19:19 +02:00
alias diffs = '\diff --side-by-side'
2014-08-17 22:54:05 +02:00
# Recherche toutes les occurences de l'arguments passé en paramètre dans l'historique des commandes
2017-12-14 17:46:27 +01:00
alias param = 'fc -l 0 | grep --'
2014-08-17 22:54:05 +02:00
# Multimédia
##Extraire la piste audio d'un .avi
alias avi2wav = 'mplayer -vc dummy -vo null -ao pcm:file=video.wav'
##Modifie la bar de progression du gestionnaire de téléchargement Axel
alias axel = 'axel -a --num-connection=20'
# Calculatrice en ligne de commande
alias caltos = 'bc'
#alias df='df --human-readable'
#alias du='du --human-readable'
alias m = 'mutt -y'
alias md = 'mkdir'
alias rd = 'rmdir'
#Internet
## Créer un mini serveur web à partir du dossier courant (http://localhost:8002)
alias httpserv = 'python -m SimpleHTTPServer'
## Créer un mini serveur web à partir du quel les utilisateurs peuvent uploader des fichiers sur la machine
alias httpup = " python /home/ ${ USER } /bin/droopy -m \"Salut, c'est Bob l'éponge, envoi moi un fichier stp.\" -p /home/ ${ USER } /avatar.png -d /media/data/download "
## Limite l'envoi à 3 requêtes pour ping
alias ping = "ping -c 3"
2015-06-08 14:26:45 +02:00
alias ping6 = "ping6 -c 3"
2014-08-17 22:54:05 +02:00
## JOSM
alias josm = "java -jar -Xmx2048M /opt/josm-tested.jar"
2021-09-19 18:08:35 +02:00
# SSH {{{
#########
# Load ssh-agent with a fix socket path {{{
2021-09-19 17:58:44 +02:00
## This function can be used :
## 1. in zlogin (for a new shell)
2021-09-19 18:08:35 +02:00
## 2. with recossh alias to load a new ssh-agent
2021-09-19 17:58:44 +02:00
function load-ssh-agent( ) {
2021-09-27 16:50:53 +02:00
# If a ssh-key is available
if find " ${ HOME } /.ssh " -maxdepth 1 -type f -iname "id_*" | grep -q -- .; then
## If ssh-agent is not already launched
if ! ps -x | grep -v grep | grep -Fq -- " ssh-agent -a ${ SSH_AGENT_SOCK } " ; then
### Remove any previous socket and environment files
rm --force -- " ${ SSH_AGENT_SOCK } " " ${ SSH_AGENT_ENV } "
### Start ssh-agent with a specified socket path
### AND store informations in a file
ssh-agent -a " ${ SSH_AGENT_SOCK } " > " ${ SSH_AGENT_ENV } "
fi
## Load content of ssh-agent environment file
source " ${ SSH_AGENT_ENV } "
2020-10-26 10:22:36 +01:00
fi
}
2021-09-19 17:58:44 +02:00
# }}}
2021-09-19 18:43:53 +02:00
# Add ed25519 ssh-key to ssh-agent {{{
function load-ssh-ed25519( ) {
# If a ED25519 ssh-key is available
# AND not already loaded in ssh-agent
if [ -f " ${ SSH_ED25519_KEY } " ] &&
! ssh-add -l | grep -qi -- "(ed25519)" ; then
ssh-add " ${ SSH_ED25519_KEY } "
fi
}
# }}}
2021-09-19 18:56:04 +02:00
# Add rsa ssh-key to ssh-agent {{{
function load-ssh-rsa( ) {
# If a RSA ssh-key is available
# AND not already loaded in ssh-agent
if [ -f " ${ SSH_RSA_KEY } " ] &&
! ssh-add -l | grep -qi -- "(rsa)" ; then
ssh-add " ${ SSH_RSA_KEY } "
fi
}
# }}}
2021-09-19 18:08:35 +02:00
# Clear old entries in known_hosts {{{
function clearsshkey( ) {
sed -i " ${ 1 } d " ~/.ssh/known_hosts
}
# }}}
# recossh will:
# (re)load ssh-agent informations
# run the previous ssh command
alias recossh = ' load-ssh-agent &&
$( fc -lr 4900 | \g rep --max-count= 1 --extended-regexp "[0-9]{1,4} ssh " | cut --delimiter= " " --fields= 4-) '
# For development and tests
2021-12-08 20:29:50 +01:00
alias sshdev = 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=accept-new'
alias scpdev = 'scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=accept-new'
2021-09-19 18:08:35 +02:00
# }}}
2021-09-19 23:21:52 +02:00
# GPG {{{
#########
2021-09-19 23:38:29 +02:00
# (re)Load gpg-agent {{{
2021-09-19 23:21:52 +02:00
## This function can be used :
## 1. with aliases (git commit,…)
function load-gpg-agent( ) {
## If a gpg key is available
if [ -f " ${ GPG_PRIV_KEY } " ] ; then
## Remove any previous test file
rm --force -- " ${ GPG_TEST_FILE } "
## Run a gpg command on the test file
gpg --quiet --for-your-eyes-only --decrypt " ${ GPG_TEST_FILE } .gpg " > /dev/null
2020-10-26 10:22:36 +01:00
fi
}
2021-09-19 23:21:52 +02:00
# }}}
2015-09-07 12:23:34 +02:00
2021-09-19 23:21:52 +02:00
# }}}
2017-06-08 15:59:32 +02:00
2018-02-16 10:37:28 +01:00
# Taskwarrior {{{
2018-04-13 22:35:24 +02:00
## Aliases
2018-02-16 10:37:28 +01:00
alias t = "task"
2021-10-18 08:51:50 +02:00
### Most recent tasks first
alias tarecent = "task simple limit:page"
2021-11-26 16:05:32 +01:00
### All pending tasks
alias tapending = "task rc._forcecolor:on +PENDING all | less"
2021-10-08 13:56:28 +02:00
### Filter by tag
2021-11-26 16:05:32 +01:00
alias tawork = "task rc._forcecolor:on +work | head"
alias taperso = "task rc._forcecolor:on +perso | head"
2021-10-11 18:54:53 +02:00
alias tarm = tadel
2019-10-14 13:20:30 +02:00
2021-10-08 13:56:28 +02:00
## Functions
2019-10-14 13:20:30 +02:00
## search a task by it's name (case INsensitive) {{{
2018-03-07 16:21:39 +01:00
function tase( ) {
2021-10-07 17:52:20 +02:00
local search = ""
2018-03-30 14:08:06 +02:00
for i; do ; search = " $search / $i / " ; done ;
2021-10-07 18:05:56 +02:00
task rc.search.case.sensitive:no $search all || return 0
2018-03-30 14:08:06 +02:00
}
2019-10-14 13:20:30 +02:00
## }}}
## search a task by it's name (case SENSITIVE) {{{
2018-03-30 14:08:06 +02:00
function tasec( ) {
2021-10-07 17:52:20 +02:00
local search = ""
2018-03-07 16:21:39 +01:00
for i; do ; search = " $search / $i / " ; done ;
2021-10-07 18:05:56 +02:00
task $search all || return 0
2018-03-30 14:08:06 +02:00
}
2019-10-14 13:20:30 +02:00
## }}}
2021-10-11 09:16:08 +02:00
## Delete a task {{{
function tadel( ) {
# Verify argument
if [ " ${# } " -eq 1 ] ; then
## Get the first arg as task ID
tadel_task_id = " ${ 1 } "
else
## If no argument or more than one
## Ask the user to choose an ID in the 20 more recents tasks {{{
task newest limit:20 || return 0
printf '%b' " Enter the ${ MAGENTAB } ID ${ RESET } of the task to remove : "
read -r tadel_task_id
## }}}
fi
# If no task with this ID exists, exit function {{{
if ! task " ${ tadel_task_id } " | grep --quiet -- " ^ID * ${ tadel_task_id } " ; then
printf '%b' " No available task with ${ REDB } ${ tadel_task_id } ${ RESET } ID. "
return 1
fi
# }}}
# Get task's description
local tadel_task_desc = $( task " ${ tadel_task_id } " | sed -n "s/^Description *\(.*\)/\1/p" )
printf '%b' " Delete the task \" ${ MAGENTAB } ${ tadel_task_id } − ${ tadel_task_desc } ${ RESET } \" [Y/n] ? "
read -r tadel_confirmation
# Check confirmation
if printf -- '%s' " ${ tadel_confirmation : =y } " | grep --quiet --word-regexp -- "y" ; then
2021-10-11 18:30:01 +02:00
task rc.confirmation:no " ${ tadel_task_id } " delete
2021-10-11 18:45:00 +02:00
printf '%b' " \" ${ MAGENTAB } ${ tadel_task_id } − ${ tadel_task_desc } ${ RESET } \" task was removed.\n "
2021-10-11 09:16:08 +02:00
fi
2021-10-11 18:47:03 +02:00
# Also offer to purge this task
tapurge " ${ tadel_task_desc } "
2021-10-11 09:16:08 +02:00
# Unset defined variables
unset tadel_confirmation tadel_task_id
}
## }}}
2021-10-11 15:18:28 +02:00
## Mark a task as done {{{
2021-11-26 15:57:01 +01:00
function tadone( ) {
# Verify argument
if [ " ${# } " -eq 0 ] ; then
## If no argument
## Ask the user to choose a task description from the last week Timewarrior activities {{{
timew summary :week :ids || return 0
printf '%b' " Enter the ${ MAGENTAB } a pattern ${ RESET } matching the expected task to mark as complete : "
read -r tadone_task_regexp
else
## Merge all args into one var
tadone_task_regexp = " ${ * } "
## }}}
fi
#printf '%b' "Pattern to search a task is ${REDB}${tadone_task_regexp}${RESET}.\n"
local tadone_task_id = $( task " ${ tadone_task_regexp } " simpleid | grep --after-context= 2 -- ID | tail --lines= 1 || return 0)
# If no task with this ID exists, exit function {{{
if [ -z " ${ tadone_task_id } " ] ; then
printf '%b' " No available task with ${ REDB } ${ tadone_task_regexp } ${ RESET } pattern. "
return 1
fi
# }}}
# Get task's description
local tadone_task_desc = $( task " ${ tadone_task_id } " | sed -n "s/^Description *\(.*\)/\1/p" )
printf '%b' " Mark the task \" ${ MAGENTAB } ${ tadone_task_id } − ${ tadone_task_desc } ${ RESET } \" as done [Y/n] ? "
read -r tadone_confirmation
# Check confirmation
if printf -- '%s' " ${ tadone_confirmation : =y } " | grep --quiet --word-regexp -- "y" ; then
task " ${ tadone_task_id } " done
printf '%b' " \" ${ MAGENTAB } ${ tadone_task_id } − ${ tadone_task_desc } ${ RESET } \" task is now complete. "
fi
# Unset defined variables
unset tadone_confirmation tadone_task_regexp
}
## }}}
## Purge an old task {{{
2021-10-11 18:45:00 +02:00
function tapurge( ) {
# Verify argument
if [ " ${# } " -eq 0 ] ; then
## If no argument
## Ask the user to choose a task description from the deleted tasks list {{{
task all status:deleted || return 0
printf '%b' " Enter few ${ MAGENTAB } words matching the description ${ RESET } of the expected task to purge : "
read -r tapurge_task_regexp
else
## Merge all args into one var
tapurge_task_regexp = " ${ * } "
## }}}
fi
local tapurge_task_desc = $( task " ${ tapurge_task_regexp } " simpledeleted | grep --after-context= 2 -- "^Description" | tail --lines= 1 || return 0)
# If no task with this Description exists, exit function {{{
if [ -z " ${ tapurge_task_desc } " ] ; then
printf '%b' " No available task with ${ REDB } ${ tapurge_task_regexp } ${ RESET } pattern. "
return 1
fi
# }}}
printf '%b' " Completly purge the task \" ${ MAGENTAB } ${ tapurge_task_desc } ${ RESET } \" [Y/n] ? "
read -r tapurge_confirmation
# Check confirmation
if printf -- '%s' " ${ tapurge_confirmation : =y } " | grep --quiet --word-regexp -- "y" ; then
task rc.confirmation:no " ${ tapurge_task_desc } " purge
printf '%b' " \" ${ MAGENTAB } ${ tapurge_task_desc } ${ RESET } \" was purged. "
fi
# Unset defined variables
unset tapurge_confirmation tapurge_task_regexp
}
## }}}
2021-11-26 15:57:01 +01:00
## Take note for a task {{{
function tanote( ) {
2021-10-11 15:18:28 +02:00
# Verify argument
if [ " ${# } " -eq 0 ] ; then
## If no argument
2021-11-26 15:57:01 +01:00
## Ask the user to choose a task description from the recent tasks {{{
task simple limit:page || return 0
2021-10-11 15:18:28 +02:00
2021-11-26 15:57:01 +01:00
printf '%b' " Enter ${ MAGENTAB } a pattern ${ RESET } matching the expected task that need notes : "
read -r tanote_task_regexp
2021-10-11 15:18:28 +02:00
else
## Merge all args into one var
2021-11-26 15:57:01 +01:00
tanote_task_regexp = " ${ * } "
2021-10-11 15:18:28 +02:00
## }}}
fi
2021-11-26 15:57:01 +01:00
local tanote_task_id = $( task " ${ tanote_task_regexp } " simpleid | grep --after-context= 2 -- ID | tail --lines= 1 || return 0)
2021-10-11 15:18:28 +02:00
# If no task with this ID exists, exit function {{{
2021-11-26 15:57:01 +01:00
if [ -z " ${ tanote_task_id } " ] ; then
printf '%b' " No available task with ${ REDB } ${ tanote_task_regexp } ${ RESET } pattern. "
2021-10-11 15:18:28 +02:00
return 1
fi
# }}}
# Get task's description
2021-11-26 15:57:01 +01:00
local tanote_task_desc = $( task " ${ tanote_task_id } " | sed -n "s/^Description *\(.*\)/\1/p" )
2021-10-11 15:18:28 +02:00
2021-11-26 15:57:01 +01:00
printf '%b' " Add notes to \" ${ MAGENTAB } ${ tanote_task_id } − ${ tanote_task_desc } ${ RESET } \" task [Y/n] ? "
read -r tanote_confirmation
2021-10-11 15:18:28 +02:00
# Check confirmation
2021-11-26 15:57:01 +01:00
if printf -- '%s' " ${ tanote_confirmation : =y } " | grep --quiet --word-regexp -- "y" ; then
task note " ${ tanote_task_id } "
2021-10-11 15:18:28 +02:00
fi
# Unset defined variables
2021-11-26 15:57:01 +01:00
unset tanote_confirmation tanote_task_regexp
2021-10-11 15:18:28 +02:00
}
## }}}
2021-10-07 15:16:17 +02:00
2021-10-08 13:56:28 +02:00
## Completion {{{
2021-10-07 15:16:17 +02:00
zstyle ':completion:*:*:task:*' verbose yes
zstyle ':completion:*:*:task:*:descriptions' format '%U%B%d%b%u'
zstyle ':completion:*:*:task:*' group-name ''
2021-10-08 13:56:28 +02:00
## }}}
2021-10-07 15:16:17 +02:00
# }}}
# Timewarrior {{{
2021-10-08 13:56:28 +02:00
## Aliases
2021-10-11 09:16:08 +02:00
alias tid = "tiday"
2021-10-18 08:44:46 +02:00
alias tiw = "tiweek"
alias tim = "timonth"
2021-10-08 13:56:28 +02:00
alias timv = "timove"
## Functions
2019-10-14 13:20:30 +02:00
## Display tasks of today {{{
2021-10-07 15:16:17 +02:00
function tiday( ) {
2019-10-16 15:18:24 +02:00
if [ " ${# } " -eq 0 ] ; then
2021-10-07 18:05:56 +02:00
timew summary :day :ids || return 0
2019-10-16 15:18:24 +02:00
else
2021-10-07 18:05:56 +02:00
timew summary :day :ids " ${ * } " || return 0
2019-10-16 15:18:24 +02:00
fi
2019-10-14 13:20:30 +02:00
}
## }}}
2020-04-16 06:36:22 +02:00
## Display tasks of last day {{{
2021-10-07 15:16:17 +02:00
function tilastday( ) {
2020-04-16 06:36:22 +02:00
if [ " ${# } " -eq 0 ] ; then
2021-10-07 18:05:56 +02:00
timew summary :yesterday :ids || return 0
2020-04-16 06:36:22 +02:00
else
2021-10-07 18:05:56 +02:00
timew summary :yesterday :ids " ${ * } " || return 0
2020-04-16 06:36:22 +02:00
fi
}
## }}}
2019-10-14 13:20:30 +02:00
## Display tasks of this week {{{
2021-10-07 15:16:17 +02:00
function tiweek( ) {
2019-10-16 15:18:24 +02:00
if [ " ${# } " -eq 0 ] ; then
2021-10-07 18:05:56 +02:00
timew summary :week :ids || return 0
2019-10-16 15:18:24 +02:00
else
2021-10-07 18:05:56 +02:00
timew summary :week :ids " ${ * } " || return 0
2019-10-16 15:18:24 +02:00
fi
2019-10-14 13:20:30 +02:00
}
## }}}
2020-03-23 08:16:19 +01:00
## Display tasks of last week {{{
2021-10-07 15:16:17 +02:00
function tilastweek( ) {
2020-03-23 08:16:19 +01:00
if [ " ${# } " -eq 0 ] ; then
2021-10-07 18:05:56 +02:00
timew summary :lastweek :ids || return 0
2020-03-23 08:16:19 +01:00
else
2021-10-07 18:05:56 +02:00
timew summary :lastweek :ids " ${ * } " || return 0
2020-03-23 08:16:19 +01:00
fi
}
## }}}
2019-10-14 13:20:30 +02:00
## Display tasks of this month {{{
2021-10-07 15:16:17 +02:00
function timonth( ) {
2019-10-16 15:18:24 +02:00
if [ " ${# } " -eq 0 ] ; then
2021-10-07 18:05:56 +02:00
timew summary :month :ids || return 0
2019-10-16 15:18:24 +02:00
else
2021-10-07 18:05:56 +02:00
timew summary :month :ids " ${ * } " || return 0
2019-10-16 15:18:24 +02:00
fi
2019-10-14 13:20:30 +02:00
}
## }}}
2020-03-23 08:16:19 +01:00
## Display tasks of last month {{{
2021-10-07 15:16:17 +02:00
function tilastmonth( ) {
2020-03-23 08:16:19 +01:00
if [ " ${# } " -eq 0 ] ; then
2021-10-07 18:05:56 +02:00
timew summary :lastmonth :ids || return 0
2020-03-23 08:16:19 +01:00
else
2021-10-07 18:05:56 +02:00
timew summary :lastmonth :ids " ${ * } " || return 0
2020-03-23 08:16:19 +01:00
fi
}
## }}}
2019-10-14 13:20:30 +02:00
## Display tasks of this year {{{
2021-10-07 15:16:17 +02:00
function tiyear( ) {
2019-10-16 15:18:24 +02:00
if [ " ${# } " -eq 0 ] ; then
2021-10-07 18:05:56 +02:00
timew summary :year :ids || return 0
2019-10-16 15:18:24 +02:00
else
2021-10-07 18:05:56 +02:00
timew summary :year :ids " ${ * } " || return 0
2019-10-16 15:18:24 +02:00
fi
2019-10-14 13:20:30 +02:00
}
## }}}
2020-03-23 08:16:19 +01:00
## Display tasks of last year {{{
2021-10-07 15:16:17 +02:00
function tilastyear( ) {
2020-03-23 08:16:19 +01:00
if [ " ${# } " -eq 0 ] ; then
2021-10-07 18:05:56 +02:00
timew summary :lastyear :ids || return 0
2020-03-23 08:16:19 +01:00
else
2021-10-07 18:05:56 +02:00
timew summary :lastyear :ids " ${ * } " || return 0
2020-03-23 08:16:19 +01:00
fi
}
## }}}
2021-10-07 16:53:17 +02:00
## Double spent time on a task {{{
## "double" cause by default my tasks runs for 25 minutes
function tidouble( ) {
# Default duration time to add to a task
2021-10-07 17:52:20 +02:00
local tidouble_extra_time = "25mins"
2021-10-07 16:53:17 +02:00
# Verify argument
if [ " ${# } " -eq 1 ] ; then
## Get the first arg as task ID
tidouble_task_id = " ${ 1 } "
else
## If no argument or more than one
## Ask the user to choose an ID in tasks from the yesterday {{{
2021-10-07 18:05:56 +02:00
timew summary from yesterday :ids || return 0
2021-10-07 16:53:17 +02:00
printf '%b' " Enter the ${ MAGENTAB } ID ${ RESET } of the task to double spent time should be doubled : "
read -r tidouble_task_id
## }}}
fi
# If no task with this ID exists, exit function {{{
if ! timew summary :year :ids | grep --quiet -- " @ ${ tidouble_task_id } " ; then
printf '%b' " No available task in the last year with ${ REDB } ${ tidouble_task_id } ${ RESET } ID. "
return 1
fi
# }}}
# Get task's description from all task of this year
2021-10-07 17:52:20 +02:00
local tidouble_task_desc = $( timew summary :year :ids | sed -n " s/.*@\( ${ tidouble_task_id } .*\)/\1/p " | sed 's/ */ − /g' )
2021-10-07 16:53:17 +02:00
printf '%b' " Add ${ tidouble_extra_time } to \" ${ MAGENTAB } ${ tidouble_task_desc } ${ RESET } \" [Y/n] ? "
read -r tidouble_confirmation
# Check confirmation
if printf -- '%s' " ${ tidouble_confirmation : =y } " | grep --quiet --word-regexp -- "y" ; then
timew lengthen @" ${ tidouble_task_id } " " ${ tidouble_extra_time } " || return 0
timew split @" ${ tidouble_task_id } " || return 0
printf '%b' " ${ tidouble_extra_time } were added to \" ${ MAGENTAB } ${ tidouble_task_desc } ${ RESET } \" task. "
fi
2021-10-07 17:52:20 +02:00
# Unset defined variables
unset tidouble_confirmation tidouble_task_id
2021-10-07 16:53:17 +02:00
}
## }}}
2021-10-07 17:47:15 +02:00
## Delete a time tracking {{{
function tirm( ) {
# Verify argument
if [ " ${# } " -eq 1 ] ; then
## Get the first arg as task ID
tirm_task_id = " ${ 1 } "
else
## If no argument or more than one
## Ask the user to choose an ID in tasks from the yesterday {{{
2021-10-07 18:05:56 +02:00
timew summary from yesterday :ids || return 0
2021-10-07 17:47:15 +02:00
printf '%b' " Enter the ${ MAGENTAB } ID ${ RESET } of the task to delete : "
read -r tirm_task_id
## }}}
fi
# If no task with this ID exists, exit function {{{
if ! timew summary :year :ids | grep --quiet -- " @ ${ tirm_task_id } " ; then
printf '%b' " No available task in the last year with ${ REDB } ${ tirm_task_id } ${ RESET } ID. "
return 1
fi
# }}}
# Get task's description from all task of this year
2021-10-07 17:52:20 +02:00
local tirm_task_desc = $( timew summary :year :ids | sed -n " s/.*@\( ${ tirm_task_id } .*\)/\1/p " | sed 's/ */ − /g' )
2021-10-07 17:47:15 +02:00
printf '%b' " Delete to \" ${ MAGENTAB } ${ tirm_task_desc } ${ RESET } \" [Y/n] ? "
read -r tirm_confirmation
# Check confirmation
if printf -- '%s' " ${ tirm_confirmation : =y } " | grep --quiet --word-regexp -- "y" ; then
timew delete @" ${ tirm_task_id } " || return 0
printf '%b' " ${ tirm_task_desc } was deleted "
fi
2021-10-07 17:52:20 +02:00
# Unset defined variables
unset tirm_confirmation tirm_task_id
2021-10-07 17:47:15 +02:00
}
## }}}
2021-10-15 11:55:01 +02:00
## Modify the start of a time tracking {{{
function tistart( ) {
# Define new_start empty by default
tistart_time_new_start = ""
# Verify argument
case " ${# } " in
1 )
## Get the first arg as time ID
tistart_time_id = " ${ 1 } "
; ;
2 )
## Get the first arg as time ID
tistart_time_id = " ${ 1 } "
## Get the second arg as new start time for this track
tistart_time_new_start = " ${ 2 } "
; ;
* )
## Ask the user to choose an ID in time tracking from the yesterday {{{
timew summary from yesterday :ids || return 0
printf '%b' " Enter the ${ MAGENTAB } ID ${ RESET } of the time tracking to modify : "
read -r tistart_time_id
## }}}
; ;
esac
# If no time tracking exists with this ID, exit function {{{
if ! timew summary :year :ids | grep --quiet -- " @ ${ tistart_time_id } " ; then
printf '%b' " No available time tracking in the last year with ${ REDB } ${ tistart_time_id } ${ RESET } ID. "
return 1
fi
# }}}
# Get time tracking's description from all time tracking of this year
local tistart_time_desc = $( timew summary :year :ids | sed -n " s/.*@\( ${ tistart_time_id } .*\)/\1/p " | sed 's/ */ − /g' )
# Get time tracking's start day from all time tracking
local tistart_time_start_day = $( timew export | sed -nE " s/^\{\"id\": ${ tistart_time_id } ,\"start\":\"([0-9]{4})([0-9]{2})([0-9]{2})T.*end.*/\1-\2-\3/p " )
# Check or ask for new start time {{{
if [ -z " ${ tistart_time_new_start } " ] ; then
printf '%b' " Enter the ${ MAGENTAB } new start time ${ RESET } (or new date 'YYYY-MM-DD ${ REDB } T ${ RESET } HH:MM:SS'; default day is ${ tistart_time_start_day } ) for this time tracking : "
read -r tistart_time_new_start
fi
# }}}
printf '%b' " Change start time of \" ${ MAGENTAB } ${ tistart_time_desc } ${ RESET } \" to ${ REDB } => ${ tistart_time_new_start } <= ${ RESET } [Y/n] ? "
read -r tistart_confirmation
# Check confirmation
if printf -- '%s' " ${ tistart_confirmation : =y } " | grep --quiet --word-regexp -- "y" ; then
## If the new start time entered by user contains a "T" (user enter a dateTtime)
if printf -- '%s' " ${ tistart_time_new_start } " | grep --quiet -- "T" ; then
printf '%b' " start time of ${ tistart_time_desc } is now ${ tistart_time_new_start } . "
timew modify start @" ${ tistart_time_id } " " ${ tistart_time_new_start } " || return 0
else
printf '%b' " start time of ${ tistart_time_desc } is now ${ tistart_time_start_day } T ${ tistart_time_new_start } . "
timew modify start @" ${ tistart_time_id } " " ${ tistart_time_start_day } T ${ tistart_time_new_start } " || return 0
fi
fi
# Unset defined variables
unset tistart_confirmation tistart_time_id tistart_time_new_start
}
## }}}
2021-10-12 13:48:06 +02:00
## Modify the end of a time tracking {{{
function tiend( ) {
# Define new_end empty by default
tiend_time_new_end = ""
# Verify argument
case " ${# } " in
1 )
## Get the first arg as time ID
tiend_time_id = " ${ 1 } "
; ;
2 )
## Get the first arg as time ID
tiend_time_id = " ${ 1 } "
## Get the second arg as new end time for this track
tiend_time_new_end = " ${ 2 } "
; ;
* )
## Ask the user to choose an ID in time tracking from the yesterday {{{
timew summary from yesterday :ids || return 0
printf '%b' " Enter the ${ MAGENTAB } ID ${ RESET } of the time tracking to modify : "
read -r tiend_time_id
## }}}
; ;
esac
# If no time tracking exists with this ID, exit function {{{
if ! timew summary :year :ids | grep --quiet -- " @ ${ tiend_time_id } " ; then
printf '%b' " No available time tracking in the last year with ${ REDB } ${ tiend_time_id } ${ RESET } ID. "
return 1
fi
# }}}
# Get time tracking's description from all time tracking of this year
local tiend_time_desc = $( timew summary :year :ids | sed -n " s/.*@\( ${ tiend_time_id } .*\)/\1/p " | sed 's/ */ − /g' )
2021-10-15 11:45:01 +02:00
# Get time tracking's start day from all time tracking
local tiend_time_start_day = $( timew export | sed -nE " s/^\{\"id\": ${ tiend_time_id } ,\"start\":\"([0-9]{4})([0-9]{2})([0-9]{2})T.*end.*/\1-\2-\3/p " )
2021-10-12 13:48:06 +02:00
# Check or ask for new end time {{{
if [ -z " ${ tiend_time_new_end } " ] ; then
2021-10-15 11:45:01 +02:00
printf '%b' " Enter the ${ MAGENTAB } new end time ${ RESET } (or new date 'YYYY-MM-DD ${ REDB } T ${ RESET } HH:MM:SS'; default day is ${ tiend_time_start_day } ) for this time tracking : "
2021-10-12 13:48:06 +02:00
read -r tiend_time_new_end
fi
# }}}
printf '%b' " Change end time of \" ${ MAGENTAB } ${ tiend_time_desc } ${ RESET } \" to ${ REDB } => ${ tiend_time_new_end } <= ${ RESET } [Y/n] ? "
read -r tiend_confirmation
# Check confirmation
if printf -- '%s' " ${ tiend_confirmation : =y } " | grep --quiet --word-regexp -- "y" ; then
2021-10-15 11:45:01 +02:00
## If the new end time entered by user contains a "T" (user enter a dateTtime)
if printf -- '%s' " ${ tiend_time_new_end } " | grep --quiet -- "T" ; then
timew modify end @" ${ tiend_time_id } " " ${ tiend_time_new_end } " || return 0
printf '%b' " End time of ${ tiend_time_desc } is now ${ tiend_time_new_end } . "
else
timew modify end @" ${ tiend_time_id } " " ${ tiend_time_start_day } T ${ tiend_time_new_end } " || return 0
printf '%b' " End time of ${ tiend_time_desc } is now ${ tiend_time_start_day } T ${ tiend_time_new_end } . "
fi
2021-10-12 13:48:06 +02:00
fi
# Unset defined variables
unset tiend_confirmation tiend_time_id tiend_time_new_end
}
## }}}
2021-10-08 13:56:28 +02:00
## Move a time tracking {{{
function timove( ) {
# Define new_start empty by default
2021-10-29 12:12:31 +02:00
timove_time_new_start = ""
2021-10-08 13:56:28 +02:00
# Verify argument
case " ${# } " in
1 )
## Get the first arg as task ID
2021-10-29 12:12:31 +02:00
timove_time_id = " ${ 1 } "
2021-10-08 13:56:28 +02:00
; ;
2 )
## Get the first arg as task ID
2021-10-29 12:12:31 +02:00
timove_time_id = " ${ 1 } "
2021-10-08 13:56:28 +02:00
## Get the second arg as new start time for the task
2021-10-29 12:12:31 +02:00
timove_time_new_start = " ${ 2 } "
2021-10-08 13:56:28 +02:00
; ;
* )
## Ask the user to choose an ID in tasks from the yesterday {{{
timew summary from yesterday :ids || return 0
printf '%b' " Enter the ${ MAGENTAB } ID ${ RESET } of the task to move : "
2021-10-29 12:12:31 +02:00
read -r timove_time_id
2021-10-08 13:56:28 +02:00
## }}}
; ;
esac
# If no task with this ID exists in the last month, exit function {{{
2021-10-29 12:12:31 +02:00
if ! timew summary :month :ids | grep --quiet -- " @ ${ timove_time_id } " ; then
printf '%b' " No available task in the last month with ${ REDB } ${ timove_time_id } ${ RESET } ID. "
2021-10-08 13:56:28 +02:00
return 1
fi
# }}}
# Get task's description from all task of this month
2021-10-29 12:12:31 +02:00
local timove_time_desc = $( timew summary :month :ids | sed -n " s/.*@\( ${ timove_time_id } .*\)/\1/p " | sed 's/ */ − /g' )
# Get time tracking's start day from all time tracking
local timove_time_start_day = $( timew export | sed -nE " s/^\{\"id\": ${ timove_time_id } ,\"start\":\"([0-9]{4})([0-9]{2})([0-9]{2})T.*end.*/\1-\2-\3/p " )
2021-10-08 13:56:28 +02:00
# Check or ask for new start time {{{
2021-10-29 12:12:31 +02:00
if [ -z " ${ timove_time_new_start } " ] ; then
printf '%b' " Enter the ${ MAGENTAB } new start time ${ RESET } (or new date 'YYYY-MM-DD ${ REDB } T ${ RESET } HH:MM:SS'; default day is ${ timove_time_start_day } ) for this task : "
read -r timove_time_new_start
2021-10-08 13:56:28 +02:00
fi
# }}}
2021-10-29 12:12:31 +02:00
printf '%b' " Move \" ${ MAGENTAB } ${ timove_time_desc } ${ RESET } \" to ${ REDB } => ${ timove_time_new_start } <= ${ RESET } [Y/n] ? "
2021-10-08 13:56:28 +02:00
read -r timove_confirmation
# Check confirmation
if printf -- '%s' " ${ timove_confirmation : =y } " | grep --quiet --word-regexp -- "y" ; then
2021-10-29 12:12:31 +02:00
## If the new start time entered by user contains a "T" (user enter a dateTtime)
if printf -- '%s' " ${ timove_time_new_start } " | grep --quiet -- "T" ; then
timew move @" ${ timove_time_id } " " ${ timove_time_new_start } " || return 0
printf '%b' " ${ timove_time_desc } was moved to ${ timove_time_new_start } . "
else
timew move @" ${ timove_time_id } " " ${ timove_time_start_day } T ${ timove_time_new_start } " || return 0
printf '%b' " start time of ${ timove_time_desc } is now ${ timove_time_start_day } T ${ timove_time_new_start } . "
fi
2021-10-08 13:56:28 +02:00
fi
# Unset defined variables
2021-10-29 12:12:31 +02:00
unset timove_confirmation timove_time_id timove_time_new_start
2021-10-08 13:56:28 +02:00
}
## }}}
2018-02-16 10:37:28 +01:00
# }}}
2017-08-04 09:03:34 +02:00
2018-03-07 16:32:10 +01:00
# DebOps {{{
2021-08-09 10:01:46 +02:00
## Direct access to DebOps's roles directory
hash -d dero = " ${ HOME } /.local/share/debops/debops/ansible/roles/ "
2018-04-18 17:32:27 +02:00
## Apply all config to all hosts except the new cluster nodes
alias deal = "debops -l 'debops_all_hosts:!physix'"
2021-08-09 10:01:46 +02:00
## Apply only on new cluster nodes
alias decc = "debops -l 'physix'"
2018-03-07 16:32:10 +01:00
## Limit to a define host/group
2018-03-20 09:55:33 +01:00
function deho( ) {
2018-04-09 09:46:32 +02:00
if [ ${ ANS_HOST } ] ; then
debops -l " ${ ANS_HOST } "
else
printf '%b' " ${ MAGENTA } ANS_HOST ${ RESET } vars is ${ REDB } not ${ RESET } define !\n "
fi
2018-03-20 09:55:33 +01:00
}
2021-08-09 10:01:46 +02:00
2018-03-07 16:32:10 +01:00
## Limit to a define host/group and to a role
function dero( ) {
2018-03-20 09:55:33 +01:00
debops -l " ${ ANS_HOST } " -t role::" ${ 1 } "
2018-03-07 16:32:10 +01:00
}
# }}}
2019-01-18 19:33:14 +01:00
# Web apps {{{
# Get weather
alias meteo = "curl http://fr.wttr.in/"
# }}}
2018-03-07 16:32:10 +01:00
2014-08-17 22:54:05 +02:00
#######################################
#Ouverture d'un programme en fonction
#de l'extension du fichier
#######################################
alias -s txt = '$PAGER '
alias -s odt = 'libreoffice --writer '
alias -s rtf = 'libreoffice --writer '
alias -s doc = 'libreoffice --writer '
2019-01-18 16:14:03 +01:00
alias -s docx = 'libreoffice --writer '
2014-08-17 22:54:05 +02:00
alias -s ods = 'libreoffice --calc '
alias -s xls = 'libreoffice --calc '
alias -s html = $BROWSER
alias -s org = $BROWSER
alias -s php = $BROWSER
alias -s com = $BROWSER
alias -s net = $BROWSER
alias -s png = 'mirage '
alias -s jpg = 'mirage '
alias -s gif = 'mirage '
alias -s mp4 = 'smplayer '
alias -s avi = 'smplayer '
alias -s flv = 'smplayer '
alias -s log = 'tail -f'
alias -s conf = 'vim '
alias -s gz = 'gunzip '
alias -s bz2 = 'tar -xjvf'
#######################################
# Raccourcis pour les dossier
# Pour y accéder, faire ~NOM_DU_RACCOURCIS
#######################################
2015-11-11 23:49:53 +01:00
hash -d apt = "/etc/apt"
2014-08-17 22:54:05 +02:00
hash -d zsh = "/etc/zsh"
hash -d dl = "/media/udata/download/"
hash -d sid = "/media/udata/config_debian"
hash -d smb = "/etc/samba/"
# Inutile mais fun :p
##Affiche le calendrier et le jour courant en couleur
#alias ccal='var=$(cal -m); echo "${var/$(date +%-d)/$(echo -e "\033[1;31m$(date +%-d)\033[0m")}"'
alias ccal = 'var=$(cal); echo "${var/$(date +%-d)/$(echo -e "\033[1;31m$(date +%-d)\033[0m")}"'
##Commande utilisant cowsay (ou PONYSAY!!) pour afficher un message
function bonjour( ) {
MIN_TIME = $( date +%M)
MODULO_MIN = $(( $MIN_TIME % 2 ))
2017-08-04 15:50:57 +02:00
if [ $( command -v bash_quote) ] && [ $( command -v cowsay) ] ; then
2015-09-08 02:09:37 +02:00
if [ $MODULO_MIN -eq 0 ] ; then
#echo Bonjour $USER, nous sommes le `date +"%A %e %B %Y"`, et il est : `date +"%H"` h `date +"%M"` | cowsay -f $(/bin/ls /usr/share/cowsay/cows -1 | head -n $(expr $$$(date +%s) % $(ls /usr/share/cowsay/cows | wc -w) + 1) | tail -n 1)
command bash_quote | cowsay -f $( /bin/ls /usr/share/cowsay/cows -1 | head -n $( expr $$ $( date +%s) % $( ls /usr/share/cowsay/cows | wc -w) + 1) | tail -n 1)
else
#echo Bonjour $USER, nous sommes le `date +"%A %e %B %Y"`, et il est : `date +"%H"` h `date +"%M"` | ponythink
command bash_quote | ponythink
fi
2014-08-17 22:54:05 +02:00
else
2015-09-08 02:09:37 +02:00
printf '%b' " ${ WHITEB } bonjour function ${ RESET } : One of the prerequesites is unavailable.\nFor bash_quote please see: https://git.101010.fr/dotfiles-gardouille/scripts/blob/master/bash_quote\n "
2014-08-17 22:54:05 +02:00
fi
}
##Affiche quelques statistiques à propos de l'ordinateur
alias stat_sys = "echo ' ' && uname -a && echo ' '&& uptime &&echo ' '&& df && echo ' '"
#####################################
#####FONCTIONS
######################################
## Verrouiller le shell avec vlock
#function TRAPALRM() { vlock }
##Cree le repertoire et va dedans
function mkcd( ) {
2015-09-08 10:20:15 +02:00
mkdir $1 && cd $_
2014-08-17 22:54:05 +02:00
}
#liste les alias et functions
function listalias( ) {
cat /etc/zsh/zshrc | egrep "alias|function" | grep -v "^#" | $PAGER
}
#Récupère l'adresse IP publique
function ippub( )
{
#curl ifconfig.me
2014-09-27 11:19:19 +02:00
#lynx --dump http://www.whatismyip.com/|grep Your|awk '{print $4}'
#wget http://checkip.dyndns.org/ -O - -o /dev/null | cut -d" " -f 6 | cut -d\< -f 1
dig +short myip.opendns.com @resolver1.opendns.com
2014-08-17 22:54:05 +02:00
}
#Récupère l'adresse IP (privee)
function ippriv( )
{
2015-09-08 00:41:17 +02:00
for interface in $( find /sys/class/net/ ! -name lo -type l -printf "%f\n" | sort) ;
do
IP_INTER = $( ip a s ${ interface } | grep "inet " | awk '{print $2}' )
printf '%b' " ${ WHITEB } ${ interface } ${ RESET } : ${ IP_INTER } \n "
done
2014-08-17 22:54:05 +02:00
}
2015-09-08 01:15:12 +02:00
# Test if a network connection is available
function is_network( )
{
for path_interface in $( find /sys/class/net/ ! -name lo -type l) ;
do
IS_UP = $( grep 1 ${ path_interface } /carrier)
if [ ${ IS_UP } ] ; then
return 0
fi
done
printf '%b' " ${ REDB } Not Online ${ RESET } \n "
return 1
}
2014-08-17 22:54:05 +02:00
#Renomme les fichiers en minuscule
function lowercase( )
{
2014-09-27 11:19:19 +02:00
for file in *; do
2014-08-17 22:54:05 +02:00
filename = ${ file ##*/ }
case " $filename " in
2014-09-27 11:19:19 +02:00
*/*) dirname = = ${ file %/* } ; ;
*) dirname = .; ;
2014-08-17 22:54:05 +02:00
esac
2014-09-27 11:19:19 +02:00
nf = $( printf $filename | tr A-Z a-z)
2014-08-17 22:54:05 +02:00
newname = " ${ dirname } / ${ nf } "
if [ " $nf " != " $filename " ] ; then
mv " $file " " $newname "
2014-09-27 11:19:19 +02:00
printf 'lowercase: %s --> %s\n' ${ file } ${ newname }
2014-08-17 22:54:05 +02:00
else
2014-09-27 11:19:19 +02:00
printf 'lowercase %s not changed\n' ${ file }
2014-08-17 22:54:05 +02:00
fi
done
}
##Capture d'écran
function printscreen( )
{
scrot -s -e 'gimp $f ; rm -rf $f'
}
## Latex:
##Redéfinition de pdflatex:
# La commande pdflatex est exécutée deux fois pour permettre la construction de l'index
function pdflatex( )
{
# On récupère le nom du fichier sans l'extension
file_name = " ${ 1 : r } "
# Le fichier avec l'extension pdf
pdf = " ${ file_name } .pdf "
# Dossier temporaire
temp_dir = "temp"
# On supprime le fichier pdf si il est présent
if [ -f " ${ pdf } " ] ; then
rm -rf " ${ pdf } "
fi
# Si le répertoire temporaire n'existe pas, on le crée
if [ ! -d " ${ temp_dir } " ] ; then
mkdir " ${ temp_dir } "
fi
# On exécute la commande pour créer le pdf
/usr/bin/pdflatex -output-directory ${ temp_dir } $1
/usr/bin/pdflatex -output-directory ${ temp_dir } $1
# On place le fichier pdf qui est dans le répertoire temporaire dans le répertoire courant
mv -f " ${ temp_dir } " /*.pdf .
}
#Éteint un pc sous windows à distance
#Nécessite le paquet samba-common
# Arguments:
# ${1}: l'ip de la machine
# ${2}: le nom d'utilisateur
# ${3}: le mot de passe de l'utilisateur
function eteint( )
{
net rpc shutdown -f -I $1 -U $2 %$3 -t 10 -C "Arrêt en cours..."
}
# Calculatrice en ligne de commande
function calc( )
{
echo " ${ 1 } " | bc -l
}
# Afficher le code retour de la commande précédente
function cmd_status {
local exit_code = $? # exit code of command
local count = $( jobs | wc -l) # no. of background jobs
# Report no. of background jobs if >0
if [ $count -gt 0 ] ; then
echo -n " %{ $fg [cyan]%}⎇ %j "
fi
# Report exit code
if [ $exit_code -ne 0 ] ; then
echo -n " %{ $fg [yellow]%}%?%{ $fg [red]%} ✖%{ $reset_color %} "
else
echo -n " %{ $fg [green]%}✔%{ $reset_color %} "
fi
}
# Affiche un rappel des raccourcis pour se déplacer dans vim
function rappel_vim( )
{
echo " \
##########################################
# Rappel basique pour VIM
##########################################
# Déplacements basiques :
H pour se déplacer vers la gauche
J pour se déplacer vers le bas
K pour se déplacer vers la droite
L pour se déplacer vers la droite
# Déplacements avancés sur une ligne :
e pour aller à la fin du mot suivant
2014-09-27 11:19:19 +02:00
w pour aller au début du mot suivant
2014-08-17 22:54:05 +02:00
b pour aller à la fin du mot précédent
0 pour aller en début de ligne
$ pour aller en fin de ligne
^ pour aller au premier caractère de la ligne qui n' est pas un espace ni une tabulation
f<c> pour aller jusqu'au caractère <c> vers l' avant
2014-09-27 11:19:19 +02:00
3f<c> pour aller jusqu'à la 3ème occurence du caractère <c> vers l' avant
2014-08-17 22:54:05 +02:00
F<c> pour aller jusqu'au caractère <c> vers l' arrière
2014-09-27 11:19:19 +02:00
nF<c> pour aller jusqu'à la nème occurence du caractère <c> vers l' arrière
2014-08-17 22:54:05 +02:00
t<c> pour aller jusqu'au caractère <c> vers l' avant en s' arrêtant avant
T<c> pour aller jusqu'au caractère <c> vers l' arrière en s' arrêtant avant
# Déplacement dans le document :
gg pour aller au début du document
G pour aller à la fin du document
nG pour aller à la ligne <n>
:<n> pour aller à la ligne <n>
2014-09-27 11:19:19 +02:00
% pour aller à la parenthèse ( acollade, crochet) correspondant
2014-08-17 22:54:05 +02:00
# Copier/coller avancé
\" ayy Copier la ligne courante dans le buffer \" a\"
\" 5byy Copier les 5 lignes sous le curseur dans le buffer \" b\"
<MODE_VISUEL>\" ey Copier les lignes sélectionnées dans le buffer \" e\"
# undo & redo
2014-09-27 11:19:19 +02:00
u pour annuler pour annuler la dernière modification
2014-08-17 22:54:05 +02:00
CTRL+R pour refaire la dernière modification
# Gestion du texte
~ pour inverser la casse du texte sélectionné
# Supprimer le texte du curseur à la fin de la ligne
<mode commande> d$
<mode insertion> CTRL-o D
# Supprimer le texte du curseur au début de la ligne
<mode commande> d^
" | $PAGER
}
# Affiche un rappel des raccourcis pour se déplacer dans vim
function rappel_vim_avance( )
{
echo " \
##########################################
# Utilisation un peu plus avancée de VIM
##########################################
# nom fichier
# Avec par exemple un fichier qui s'appelle fichier.tex dans /home/limax/Documents/
# est le nom du fichier en cours
:!echo % ( renvoie /Documents/fichier.tex )
:!echo %:r ( renvoie /Documents/fichier )
:!echo %:e ( renvoie tex )
:!echo %:t ( renvoie fichier.tex )
:!echo %:p ( renvoie /home/limax/Documents/fichier.tex )
:!echo %:t ( renvoie fichier.tex )
:!echo %:h ( renvoie Documents)
# Par exemple pour ouvrir le pdf avec lesspipe
:!lesspipe %:r.pdf
# Indentation
# Pour réindenter du texte:
mode visuel
- sélectionner toutes les lignes à indenter correctement
touche \" = \"
# Pour décaler plusieurs lignes de plusieurs tabulations:
mode visuel
- sélectionner toutes les lignes à décaler
:>>>
# Commande
# Pour exécuter une seule commande à partir du mode insertion
<mode insertion> CTRL-o suivi de la commande à exécuter
# Code touche
# Pour afficher le code clavier d'une touche spéciale en mode insertion:
<mode insertion> CTRL-V
# Pour afficher le code interne d'une touche spéciale:
<mode insertion> CTRL-K
# Pour obtenir le code ascii d'un caractère:
ga
# Plier/déplier
zm Plier tout le document sur un niveau de plus
zr Déplier tout le document sur un niveau de plus
zc Plier un bloc/fonction/class
zo Déplier un bloc/fonction/class
" | $PAGER
}
# Affiche un rappel pour l'édition de fichier Latex
function rappel_latex( )
{
echo " \
-\\ /- Permet d' afficher -- et non un tiret cadratin
Ligne vide Permet un retour à la ligne entre deux textes
\\ ldots Affiche correctement \" ...\"
# itemize
Mettre un \\ vspace{ 0.5cm} après une liste?
Laisser une ligne vide après une commande root dans une liste?
# À faire
Ajouter un style pour les notes d' informations
Ajouter un style pour les notes importantes
" | $PAGER
}
## Vérifier les logins et logouts de tous les comptes incluant le mien.
watch = all
# Vérifie toutes les 30 secondes
logcheck = 30
# Change le format de watch pour quelques chose avec plus d'informations
# %n = username, %M = hostname, %a = action, %l = tty, %T = time,
# %W = date
WATCHFMT = "%n from %M has %a tty%l at %T %W"
# Crypte le fichier passer en paramètre en utilisant le certificat public
# de l'utilisateur.
# Arguments:
# ${1}: fichier à crypter
# ${2}:
function crypt( )
{
openssl smime -encrypt -aes128 -in ${ 1 } -out .${ 1 } .ls ~/.openssl/mycert.crt
}
# Décrypte le fichier passer en paramètre en fonction de la clef ssl de
# l'utilisateur et trouve la ligne contenant le mot rechercher par l'user
# Arguments:
# ${1}: le fichier à décrypter
# ${2}: le paramètre rechercher dans le fichier
function getpdw( )
{
openssl smime -decrypt -in ${ 1 } -inkey ~/.openssl/mykey.key | grep ${ 2 }
}
# Décrypte le fichier passer en paramètre en fonction de la clef ssl de
# l'utilisateur et le fichier de sorti est le second paramètre
# Arguments:
# ${1}: le fichier à décrypter
# ${2}: le fichier de sorti
function decrypt( )
{
openssl smime -decrypt -in ${ 1 } -out ${ 2 } -inkey ~/.openssl/mykey.key
}
# Traduire en français avec Gogole:
function tradfr( )
{
wget -U "Mozilla/5.0" -qO - " http://translate.google.com/translate_a/t?client=t&text= ${ * } &sl=auto&tl=fr " | sed 's/\[\[\[\"//' | cut -d \" -f 1
}
# Traduire du français à l'anglais avec Gogole:
function traden( )
{
2017-09-18 10:58:08 +02:00
wget -qO- " http://ajax.googleapis.com/ajax/services/language/translate?v=2&q= $1 &langpair= $2 | ${ 3 :- en } " | sed 's/.*"translatedText":"\([^"]*\)".*}/\1\n/'
#wget -U "Mozilla/5.0" -qO - "http://translate.google.com/translate_a/t?client=t&text=${*}&sl=fr&tl=en" | sed 's/\[\[\[\"//' | cut -d \" -f 1
2014-08-17 22:54:05 +02:00
}
# Traduire le texte (1er argument) de la langue source (2nd argument) dans la langue de destination (3ème argument)
function translate( )
{
wget -U "Mozilla/5.0" -qO - " http://translate.google.com/translate_a/t?client=t&text= ${ 1 } &sl= ${ 2 } &tl= ${ 3 } " | sed 's/\[\[\[\"//' | cut -d \" -f 1
}
################################################
# 2. Prompt et définition des touches basiques #
################################################
# Prompt couleur (la couleur n'est pas la même pour le root et
# pour les simples utilisateurs)
# Définition des couleurs:
bleu_clair = "[36;1m"
bleu_fonce = "[34;1m"
rouge = "[31m"
jaune = "[33m"
blanc = "[37m"
vert = "[32m"
couleur_normale = "[0m"
# Définition du texte du prompt
heure = " %{ $bleu_clair %}%T "
user = " %{ $bleu_fonce %}%n "
user_root = " %{ $rouge %}%n "
at = " %{ $jaune %}@ "
host = " %{ $blanc %}%m "
repertoire_courant = " %{ $vert %}%c "
repertoire_absolu = " %{ $vert %}%d "
# Chemin du répertoire courant en relatif à ~
repertoire_relatif = " %{ $vert %}%~ "
root = " %{ $jaune %}%# "
noroot = " %{ $jaune %}%% "
normal = " %{ $couleur_normale %} "
# Définition du prompt
if [ "`id -u`" -eq 0 ] ; then ## Root
export PS1 = " $heure $user_root $at $host $repertoire_courant $root $normal "
# export PS1="%{ $bleu_clair%T %{ $rouge%n%{ $jaune@%{ $blanc%m %{ $vert%c%{ $jaune%#%{ [0m%} "
else ## Simple utilisateur
2015-09-09 16:01:45 +02:00
export PS1 = " $heure $host $repertoire_courant $noroot $normal "
2014-08-17 22:54:05 +02:00
fi
# Prise en charge des touches [début], [fin] et autres
typeset -A key
key[ Home] = ${ terminfo [khome] }
key[ End] = ${ terminfo [kend] }
key[ Insert] = ${ terminfo [kich1] }
key[ Delete] = ${ terminfo [kdch1] }
key[ Up] = ${ terminfo [kcuu1] }
key[ Down] = ${ terminfo [kcud1] }
key[ Left] = ${ terminfo [kcub1] }
key[ Right] = ${ terminfo [kcuf1] }
key[ PageUp] = ${ terminfo [kpp] }
key[ PageDown] = ${ terminfo [knp] }
[ [ -n " ${ key [Home] } " ] ] && bindkey " ${ key [Home] } " beginning-of-line
[ [ -n " ${ key [End] } " ] ] && bindkey " ${ key [End] } " end-of-line
[ [ -n " ${ key [Insert] } " ] ] && bindkey " ${ key [Insert] } " overwrite-mode
[ [ -n " ${ key [Delete] } " ] ] && bindkey " ${ key [Delete] } " delete-char
[ [ -n " ${ key [Up] } " ] ] && bindkey " ${ key [Up] } " up-line-or-history
[ [ -n " ${ key [Down] } " ] ] && bindkey " ${ key [Down] } " down-line-or-history
[ [ -n " ${ key [Left] } " ] ] && bindkey " ${ key [Left] } " backward-char
[ [ -n " ${ key [Right] } " ] ] && bindkey " ${ key [Right] } " forward-char
[ [ -n " ${ key [PageUp] } " ] ] && bindkey " ${ key [PageUp] } " history-beginning-search-backward
[ [ -n " ${ key [PageDown] } " ] ] && bindkey " ${ key [PageDown] } " history-beginning-search-forward
2015-02-26 14:20:54 +01:00
# ctrl+← and ctrl+→ issue
bindkey "^[[1;5C" vi-forward-word-end
bindkey "^[[1;5D" backward-word
2014-08-17 22:54:05 +02:00
# Titre de la fenêtre d'un xterm
case $TERM in
xterm*)
precmd ( ) { print -Pn "\e]0;%n@%m: %~\a" }
; ;
esac
# Gestion de la couleur pour 'ls' (exportation de LS_COLORS)
if [ -x /usr/bin/dircolors ]
then
if [ -r ~/.dir_colors ]
then
eval "`dircolors ~/.dir_colors`"
elif [ -r /etc/dir_colors ]
then
eval "`dircolors /etc/dir_colors`"
else
eval "`dircolors`"
fi
fi
#######################################
# 3. Comportement ligne de commandes #
#######################################
# La ligne de commande dans zsh peut fonctionner suivant différents schémas (options).
# Les principaux que je vais utiliser sont fait pour la ligne de commande dans zhs se
# comporte à la vim. Il y a donc un mode commande/normal et un mode insertion.
# Afficher le mode courant dans le prompt de droite (normal|insertion)
function zle-line-init zle-keymap-select {
RPS1 = " $( cmd_status) ${ ${ KEYMAP /vicmd/-CMD- } /(main|viins)/-INS- } "
RPS2 = $RPS1
zle reset-prompt
}
# easy color names in this config
autoload -U colors && colors
# Chargement des keymaps
zle -N zle-line-init
zle -N zle-keymap-select
### Raccourcis communs à tous les modes
autoload -U edit-command-line
zle -N edit-command-line
bindkey ' ' edit-command-line # Ouvrir la commande actuelle dans l'éditeur
bindkey ' ' history-incremental-search-backward # Recherche incrémentale qui monte dans l'historique
#bindkey ' ' history-incremental-search-forward # Recherche incrémentale qui descend dans l'historique
### Raccourcis spécifiques au mode insertion
bindkey -M viins ' ' beginning-of-line # Début de ligne
bindkey -M viins ' ' vi-forward-blank-word-end # Fin du mot courant
#bindkey -M viins ' ' vi-forward-blank-word # Début du mot suivant
bindkey -M viins ' ' vi-backward-word # Début du mot précédent
bindkey -M viins ' ' vi-find-prev-char # Rechercher la précédente occurence d'une lettre
#bindkey -M viins ' ;' vi-repeat-find # Aller à la prochaine occurence de la lettre recherchée
### Raccourcis spécifiques au mode commande
# Le mode commande dispose déjà de la plupart d'un fonctionnement très semblable
# au mode normal de vim. Seul problème pour le moment, l'absence d'un mode visuel.
###########################################
# 4. Options de zsh (cf 'man zshoptions') #
###########################################
# Je ne veux JAMAIS de beeps
unsetopt beep
unsetopt hist_beep
unsetopt list_beep
# Redirection de la sortie:
# >| doit être utilisés pour pouvoir écraser un fichier déjà existant ;
# le fichier ne sera pas écrasé avec '>'
unsetopt clobber
# Ctrl+D est équivalent à 'logout'
unsetopt ignore_eof
# Affiche le code de sortie si différent de '0'
setopt print_exit_value
# Demande confirmation pour 'rm *'
unsetopt rm_star_silent
# Attend 10 secondes avant d'exécuter une commande rm qui contient un * (asterisk).
setopt rmstarwait
# Correction orthographique des commandes
# Désactivé car, contrairement à ce que dit le "man", il essaye de
# corriger les commandes avant de les hasher
setopt correct
# Si on utilise des jokers dans une liste d'arguments, retire les jokers
# qui ne correspondent à rien au lieu de donner une erreur
setopt nullglob
# Désactivé le raccourcis '='
# Par défaut, `ls -l =vim` indiquera l'emplacement de vim.
# =vim équivaut à `which vim`
#setopt noequals
## Activation des fonctions internes de ZSH:
# Liste des fonctions disponibles:
#zcalc : une calculatrice (plus besoin de bc ou autres expr)
#zargs : un super xargs
#zmv : une commande permettant de faire du renommage/déplaçage en masse de fichiers.
#zftp : un client ftp natif
autoload -U zfinit
zfinit
# Les jobs qui tournent en tâche de fond sont nicé à '0'
unsetopt bg_nice
# N'envoie pas de "HUP" aux jobs qui tourent quand le shell se ferme
unsetopt hup
# Lancer le manuel en se placant sur une commande et en faisant {ESC,ALT}+{H,h}
autoload -U run-help
## Gestion de la pile des dossiers:
# Taille maximale de la pile placé dans zshenv
# L'exécution de "cd" met le répertoire d'où l'on vient sur la pile
setopt auto_pushd
# Ignore les doublons dans la pile
setopt pushd_ignore_dups
# N'affiche pas la pile après un "pushd" ou "popd"
setopt pushd_silent
# Inverse l'action de cd +1 et cd +1
setopt pushdminus
# "pushd" sans argument = "pushd $HOME"
setopt pushd_to_home
## Pour bien utiliser la pile:
# `dirs` va afficher la pile
# `cd -NUMÉRO` ira dans le dossier correspondant au numéro du dossier dans la pile
## Dirstack
DIRSTACKSIZE = 20
setopt autopushd pushdsilent pushdtohome
## Remove duplicate entries
setopt pushdignoredups
## This reverts the +/- operators.
setopt pushdminus
#DIRSTACKFILE="$HOME/.zsh/cache/dirs"
#if [[ -f $DIRSTACKFILE ]] && [[ $#dirstack -eq 0 ]]; then
#dirstack=( ${(f)"$(< $DIRSTACKFILE)"} )
#[[ -d $dirstack[1] ]] && cd $dirstack[1]
#fi
#chpwd() {
#print -l $PWD ${(u)dirstack} >> $DIRSTACKFILE
#}
###################################
###### Options de complétion ######
###################################
# Schémas de complétion
# - Schéma A :
# 1ère tabulation : complète jusqu'au bout de la partie commune
# 2ème tabulation : propose une liste de choix
# 3ème tabulation : complète avec le 1er item de la liste
# 4ème tabulation : complète avec le 2ème item de la liste, etc...
# -> c'est le schéma de complétion par défaut de zsh.
# Schéma B :
# 1ère tabulation : propose une liste de choix et complète avec le 1er item
# de la liste
# 2ème tabulation : complète avec le 2ème item de la liste, etc...
# Si vous voulez ce schéma, décommentez la ligne suivante :
#setopt menu_complete
# Schéma C :
# 1ère tabulation : complète jusqu'au bout de la partie commune et
# propose une liste de choix
# 2ème tabulation : complète avec le 1er item de la liste
# 3ème tabulation : complète avec le 2ème item de la liste, etc...
# Ce schéma est le meilleur à mon goût !
# Si vous voulez ce schéma, décommentez la ligne suivante :
unsetopt list_ambiguous
# Quand le dernier caractère d'une complétion est '/' et que l'on
# tape 'espace' après, le '/' est effacé
setopt auto_remove_slash
# Ne fait pas de complétion sur les fichiers et répertoires cachés
unsetopt glob_dots
# Traite les liens symboliques comme il faut
setopt chase_links
# Quand l'utilisateur commence sa commande par '!' pour faire de la
# complétion historique, il n'exécute pas la commande immédiatement
# mais il écrit la commande dans le prompt
setopt hist_verify
# Si la commande est invalide mais correspond au nom d'un sous-répertoire
# exécuter 'cd sous-répertoire'
setopt auto_cd
###############################################
# 5. Paramètres de l'historique des commandes #
###############################################
# Définition des variables
SAVEHIST = 5000
HISTSIZE = 5000
HISTFILE = $HOME /.zsh/history
#export TIMEFMT="%E"
export SAVEHIST HISTSIZE HISTFILE
# Toutes les sessions zsh partage le même historique
#setopt SHARE_HISTORY
# Ajoute l'historique à la fin de l'ancien fichier
#setopt append_history
# Chaque ligne est ajoutée dans l'historique à mesure qu'elle est tapée
setopt inc_append_history
# Ne stocke pas une ligne dans l'historique si elle est identique à la
# précédente
setopt hist_ignore_dups
# Supprime les répétitions dans le fichier d'historique, ne conservant
# que la dernière occurrence ajoutée
#setopt hist_ignore_all_dups
# Supprime les répétitions dans l'historique lorsqu'il est plein, mais
# pas avant
setopt hist_expire_dups_first
# N'enregistre pas plus d'une fois une même ligne, quelles que soient
# les options fixées pour la session courante
#setopt hist_save_no_dups
# La recherche dans l'historique avec l'éditeur de commandes de zsh ne
# montre pas une même ligne plus d'une fois, même si elle a été
# enregistrée plusieurs fois
setopt hist_find_no_dups
# Affichage de la date du début de la commande et sa durée (depuis epoch)
# Culture time: epoch: 1er janvier 1970
setopt extended_history
# Ne pas enregistrer les commandes précédées d'un espace:
setopt hist_ignore_space
###########################################
# 6. Complétion des options des commandes #
###########################################
zstyle ':completion:*' matcher-list '' 'm:{a-z}={A-Z}'
zstyle ':completion:*' max-errors 3 numeric
zstyle ':completion:*' use-compctl false
## Pour la liste des processus que l'on peut kill, avec un menu et couleur
zstyle ':completion:*:*:*:*:processes' menu yes select
#zstyle ':completion:*:*:*:*:processes' force-list always
2017-03-20 14:37:51 +01:00
zstyle ':completion:*:processes' command 'ps -fau$USER'
2014-08-17 22:54:05 +02:00
zstyle ':completion:*:*:kill:*:processes' list-colors "=(#b) #([0-9]#)*=36=31"
## Pour éviter de reproposer un argument déjà utiliser dans la commande lors de la complétion
zstyle ':completion:*:(rm|mv|cp|ls|scp):*' ignore-line yes
## cd ne sélectionnera pas le dossier courant lorsqu'il devra remonter d'un dossier
# cd ../<TAB> ne proposera pas le dossier courant par exemple.
zstyle ':completion:*:cd:*' ignore-parents parent pwd
## Pour la liste des fichiers qu'on peut ouvrir avec vim
zstyle ':completion:*:*:vim:*' menu yes select
## Mettre en cache les résultats de l'auto-complétion car certaines fonctions sont lentes (apt, dpkg, ...)
# Ne pas hésiter à faire un petit aptitude install <TAB> et de lister tous les résultats possibles une première fois, histoire d'avoir tous les paquets en cache (~600ko), ça vaut le coup!
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path ~/.zsh/cache
## Ajout des couleurs pour la complétion
zmodload -i zsh/complist
zstyle ':completion:*' list-colors ${ (s. : .)LS_COLORS }
## Complétion de la commande cd avec les répertoires locaux puis ceux de la variable CDPATH
zstyle ':completion:*:*:cd:*' tag-order local-directories path-directories
## Complétion des commandes ssh avec le contenu du fichier ~/.ssh/config et le contenu de host
local HOSTS
#[[ -f ~/.ssh/config ]] && HOSTS=(`sed -n \'s/^Host \(.*\)/\1/p\' ~/.ssh/config`)
#if [ -f ~/.ssh/config ]; then
#HOSTS=(`grep ^Host ~/.ssh/config | sed s/Host\ // | egrep -v ‘ ^\*$’ `)
#fi
#zstyle ':completion:*:(ssh|scp|sftp|sshfs):*' hosts ${HOSTS}
# Complétions pour certains programmes en fonction des extensions
zstyle ':completion:*:*:vlc:*' file-patterns '*.(mkv|MKV|avi|AVI|flv|FLV|mp4|MP4|webm|WEBM|mov|MOV|flac|FLAC|mp3|MP3|ogg|OGG|ogv|OGV|wmv|WMV)\ *(-/):directories'
## Ajout de la complétion pour plusieurs fonctions:
autoload -U compinit
autoload -U zutil
autoload -U complist
# Activation
compinit
###########################################
# 7. Création des fichiers et répertoires #
###########################################
# Dossier .zsh dans le répertoire personnel
if [ ! -d ~/.zsh ] ; then
mkdir ~/.zsh
fi
# Fichier contenant l'historique pour chaque utilisateur
if [ ! -f ~/.zsh/history ] ; then
touch ~/.zsh/history
fi
# Dossier contenant le cache pour chaque utilisateur
if [ ! -d ~/.zsh/cache ] ; then
mkdir ~/.zsh/cache
fi
###########################################
############## 8. Globbing ################
###########################################
# Activation du globbing étendu
setopt extendedglob
## '^' inverse la pattern qui suit.
# Exemple:
# `ls ^*.log` listera tous les fichiers exceptés *.log
2017-12-12 09:40:33 +01:00
###########################################
############### 9. Modules ################
###########################################
2017-12-15 13:47:15 +01:00
## fzf
if [ -d ~/.fzf ] ; then
if [ [ ! " $PATH " = = *" ${ HOME } " /.fzf/bin* ] ] ; then
export PATH = " $PATH : ${ HOME } /.fzf/bin "
fi
2017-12-22 11:29:37 +01:00
if [ -f ~/bin/fd ] ; then
export FZF_DEFAULT_COMMAND = 'fd --type f'
fi
2017-12-15 13:47:15 +01:00
# Auto-completion
# ---------------
[ [ $- = = *i* ] ] && source " ${ HOME } /.fzf/shell/completion.zsh " 2> /dev/null
# Key bindings
# ------------
source " ${ HOME } /.fzf/shell/key-bindings.zsh "
# ff - cd to selected directory (exclude hidden directories
ff( ) {
local dir
dir = $( find ${ 1 :- . } -path '*/\.*' -prune \
-o -type d -print 2> /dev/null | fzf +m) &&
cd " $dir "
}
# ffh - hidden directories only
ffh( ) {
local dir
dir = $( find ${ 1 :- . } -type d 2> /dev/null | fzf +m) && cd " $dir "
}
# ffa - all directories
# ffr - cd to selected parent directory
ffr( ) {
local declare dirs = ( )
get_parent_dirs( ) {
if [ [ -d " ${ 1 } " ] ] ; then dirs += ( " $1 " ) ; else return ; fi
if [ [ " ${ 1 } " = = '/' ] ] ; then
for _dir in " ${ dirs [@] } " ; do echo $_dir ; done
else
get_parent_dirs $( dirname " $1 " )
fi
}
local DIR = $( get_parent_dirs $( realpath " ${ 1 :- $PWD } " ) | fzf-tmux --tac)
cd " $DIR "
}
# fff - cd into the directory of the selected file
fff( ) {
local file
local dir
file = $( fzf +m -q " $1 " ) && dir = $( dirname " $file " ) && cd " $dir "
}
# cf - fuzzy cd from anywhere
# ex: cf word1 word2 ... (even part of a file name)
# zsh autoload function
cf( ) {
local file
file = " $( locate -Ai -0 $@ | grep -z -vE '~$' | fzf --read0 -0 -1) "
if [ [ -n $file ] ]
then
if [ [ -d $file ] ]
then
cd -- $file
else
cd -- ${ file : h }
fi
fi
}
fi
2018-09-06 11:27:16 +02:00
# v - fuzzy open with vi from current directory
# cd into the directory of the selected file
# open the selected file with vi
v( ) {
local files
files = $( find ${ 1 :- . } -path '*/\.*' -prune \
-o -print 2> /dev/null | fzf +m) &&
if [ [ -n $files ] ]
then
dir = $( dirname " ${ files } " )
cd " ${ dir } "
file = $( basename " ${ files } " )
vi -- " ${ file } "
fi
}
2021-08-09 10:01:58 +02:00
# Try to give the real creation time of a file
xstat( ) {
for target in " ${ @ } " ; do
inode = $( ls -di " ${ target } " | cut -d ' ' -f 1)
fs = $( df " ${ target } " | tail -1 | awk '{print $1}' )
crtime = $( sudo debugfs -R 'stat <' " ${ inode } " '>' " ${ fs } " 2>/dev/null |
grep -oP 'crtime.*--\s*\K.*' )
printf "%s\t%s\n" " ${ crtime } " " ${ target } "
done
}
2019-01-18 16:14:03 +01:00
# PDF with fzf {{{
2019-01-08 14:13:54 +01:00
# pdf - fuzzy open with "${PDF_VIEWER}" from current directory
# cd into the directory of the selected file
# open the selected file with "${PDF_VIEWER}"
pdf( ) {
local files
files = $( find ${ 1 :- . } -iname "*.pdf" 2> /dev/null | fzf +m) &&
if [ [ -n $files ] ]
then
dir = $( dirname " ${ files } " )
cd " ${ dir } "
file = $( basename " ${ files } " )
" ${ PDF_VIEWER } " -- " ${ file } "
fi
}
# pdfe - fuzzy open with evince from current directory
# cd into the directory of the selected file
# open the selected file with evince
pdfe( ) {
local files
files = $( find ${ 1 :- . } -iname "*.pdf" 2> /dev/null | fzf +m) &&
if [ [ -n $files ] ]
then
dir = $( dirname " ${ files } " )
cd " ${ dir } "
file = $( basename " ${ files } " )
evince -- " ${ file } "
fi
}
# pdfz - fuzzy open with zathura from current directory
# cd into the directory of the selected file
# open the selected file with zathura
pdfz( ) {
local files
files = $( find ${ 1 :- . } -iname "*.pdf" 2> /dev/null | fzf +m) &&
if [ [ -n $files ] ]
then
dir = $( dirname " ${ files } " )
cd " ${ dir } "
file = $( basename " ${ files } " )
zathura -- " ${ file } "
fi
}
2019-01-18 16:14:03 +01:00
# }}}
# LibreOffice with fzf {{{
# odt - fuzzy open wordprocessor related files
# Look for some known extensions (odt, rtf, doc,…).
# cd into the directory of the selected file.
# Open in background the selected file with libreoffice-writer.
odt( ) {
local files
files = $( find ${ 1 :- . } -regextype posix-extended -regex ".*\.(odt|rtf|doc|docx)" 2> /dev/null | fzf +m) &&
if [ [ -n $files ] ]
then
dir = $( dirname " ${ files } " )
cd -- " ${ dir } "
file = $( basename " ${ files } " )
command libreoffice --writer " ${ file } " &
fi
}
# ods - fuzzy open spreadsheet related files
# Look for some known extensions (ods, xls,…).
# cd into the directory of the selected file.
# Open in background the selected file with libreoffice-calc.
ods( ) {
local files
files = $( find ${ 1 :- . } -regextype posix-extended -regex ".*\.(ods|xls|xlsx)" 2> /dev/null | fzf +m) &&
if [ [ -n $files ] ]
then
dir = $( dirname " ${ files } " )
cd -- " ${ dir } "
file = $( basename " ${ files } " )
command libreoffice --calc " ${ file } " &
fi
}
# odp - fuzzy open presentation related files
# Look for some known extensions (odp, ppt,…).
# cd into the directory of the selected file.
# Open in background the selected file with libreoffice-impress.
odp( ) {
local files
files = $( find ${ 1 :- . } -regextype posix-extended -regex ".*\.(odp|ppt|pptx)" 2> /dev/null | fzf +m) &&
2019-01-08 14:13:54 +01:00
2019-01-18 16:14:03 +01:00
if [ [ -n $files ] ]
then
dir = $( dirname " ${ files } " )
cd -- " ${ dir } "
file = $( basename " ${ files } " )
command libreoffice --impress " ${ file } " &
fi
}
# }}}
2018-03-29 19:07:07 +02:00
# zsh-syntax-highlighting {{{
## Activate if plugin is available
2017-12-12 09:40:33 +01:00
[ -f ~/repos/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh ] && source ~/repos/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
2018-03-29 19:07:07 +02:00
## Additionnal highlighters
### The order is important. Put **regexp** before **main** to prioritize
### the double quotation marks
ZSH_HIGHLIGHT_HIGHLIGHTERS = ( regexp main brackets pattern)
### Dangerous commands
ZSH_HIGHLIGHT_PATTERNS += ( 'rm -rf *' 'fg=white,bold,bg=red' )
ZSH_HIGHLIGHT_REGEXP += ( '\bsudo\b' 'fg=white,bold,bg=red' )
2018-03-30 11:14:04 +02:00
### CLI
2018-04-03 15:25:43 +02:00
ZSH_HIGHLIGHT_REGEXP += ( '\ \-[^- ]+' 'fg=227' ) # short args in yellow (-l)
ZSH_HIGHLIGHT_REGEXP += ( '\ \--[^ ]+' 'fg=214' ) # long args in orange (--all)
2018-03-29 19:07:07 +02:00
### Taskwarrior
ZSH_HIGHLIGHT_REGEXP += ( '\ \+[^ ]+' 'fg=226' ) # tags in yellow (+txt)
2018-03-30 11:14:04 +02:00
ZSH_HIGHLIGHT_REGEXP += ( '[^ ]+\:' 'fg=135' ) # metadata in purple (project:)
ZSH_HIGHLIGHT_REGEXP += ( '\ \_[^ ]+' 'fg=32' ) # subcommands in blue (_command)
2018-03-29 19:07:07 +02:00
# }}}