Skip to content

Latest commit

 

History

History
551 lines (495 loc) · 15.6 KB

zsh-utilities-modules.org

File metadata and controls

551 lines (495 loc) · 15.6 KB

Zsh Utilities Modules

This is part of the Zsh Utilities.

Zsh Utilities - Modules

This file adds some configuration to external resources. Each program configuration is done item per item. The preamble is just here to ensure the binary is present. Thus each item is embedded between a preamble and postamble block code which is a basic if command.

fasd

fasd is a command-line productivity booster, offers quick access to files and directories, inspired by autojump, z and v. Most of the following code is stolen from prezto.

Preamble

if (( $+commands[fasd] )); then

Initialization

mkdir -p ${HOME}/.config/zsh/tmp
cache_file="${HOME}/.config/zsh/tmp/fasd_cache.zsh"
if [[ "${commands[fasd]}" -nt "$cache_file" || ! -s "$cache_file" ]]; then
    # Set the base init arguments.
    init_args=(zsh-hook)

    # Set fasd completion init arguments, if applicable.
    #    if zstyle -t ':prezto:module:completion' loaded; then
    init_args+=(zsh-ccomp zsh-ccomp-install zsh-wcomp zsh-wcomp-install)
    #    fi

    # Cache init code.
    fasd --init "$init_args[@]" >! "$cache_file" 2> /dev/null
fi
source "$cache_file"
unset cache_file init_args

Additional function for fast cd

function fasd_cd {
  local fasd_ret="$(fasd -d "$@")"
  if [[ -d "$fasd_ret" ]]; then
    cd "$fasd_ret"
  else
    print "$fasd_ret"
  fi
}

Aliases

Change the current working directory interactively

alias j='fasd_cd -i'

Postamble

fi

rsync

rsync is an open source utility that provides fast incremental file transfer

Preamble

if (( $+commands[rsync] )); then

Aliases

function rsync ()
{
    # if (( $+commands[colout] )); then
    #     $(pkgtools::get_binary_path rsync) $@ 2>&1 | colout -t rsync -T ${zsh_utilities_dir}
    # else
        $(pkgtools::get_binary_path rsync) $@
    # fi
}
local _rsync_cmd='noglob rsync --verbose --progress --human-readable --compress --archive --hard-links --one-file-system'

alias rsync-copy="${_rsync_cmd}"
alias rsync-move="${_rsync_cmd} --remove-source-files"
alias rsync-update="${_rsync_cmd} --update"
alias rsync-synchronize="${_rsync_cmd} --update --delete"

Postamble

fi

colout

colout read lines of text stream on the standard input and output characters matching a given regular expression pattern in given and style: style may be colored bold strings, for instance.

Preamble

if (( $+commands[colout] )); then

Homemade themes

g++ theme

#encoding: utf-8

def theme(context):
  import locale
  section="blue"
  # if the locale is unicode
  enc = locale.getpreferredencoding()
  if "UTF" in enc:
    # gcc will use unicode quotes
      qo = "[‘`]"
      qc = "[’']"
  else:
    # rather than ascii ones
      qo = "['`]"
      qc = "'"

  return context, [
      [ ("error: |erreur: "), "red", "bold" ],
      [ ("warning: |attention: "), "magenta", "bold" ],
      [ ("undefined reference to "), "red", "bold" ],
      # [-Wflag]
      [ "\[-W.*\]", "magenta"],

      # Highlight message start:
      #   path   file   ext     : line   :  col     …
      [ "(/.*?)/([^/:]+): (In .*)",
        section,
        "normal,normal,bold" ],

      [ "(/.*?)/([^/:]+): (At .*)",
        section,
        "normal,normal,bold" ],

      [ ("In file included from"), section ],

      # Highlight locations:
      #   path   file   ext     : line   :  col     …
      [ "(/.*?)/([^/:]+):([0-9]+):*([0-9]*)(.*)",
        "none,magenta,yellow,yellow,none",
        "normal,normal,normal,normal" ],

      # source code in single quotes
      [ qo+"(.*?)"+qc, "green", "bold" ],

      # # source code after a "note: candidate are/is:"
      [ ("note: ")+"((?!.*(candidate|"+qo+"|"+qc+")).*)$", "none", "bold" ],
      # after the code part, to avoid matching ANSI escape chars
      [ ("note: "), "green", "normal" ]
    ]

ninja theme

def theme(context):
    # Ninja theme:
    #  actions building
    building="blue"
    #  actions linking
    linking="green"
    #  actions generating
    generating="blue"

    return context, [
        # Linking
        [ "\[.*\]\s(Linking .* )(library|executable) (.*/)*(.+(\.[aso]+)*)$",
          linking, "normal,normal,normal,bold" ],
        # Building
        [ "^\[.*\]\s(Building \w* object)(\s+.*/)([-\w]+.c.*)(.o)$",
          building, "normal,normal,bold,normal"],
        # [percent] Generating
        [ "^\[.*\]\s(Generating)(\s+.*)$",
          generating, "normal,bold"],
        [ "^\[.*\]\s(Creating)(\s+.*/)(.*)$",
          "magenta", "normal,normal,bold"],
        # Ninja stop
        [ ".*build stopped.*", "red", "bold" ],
        # progress percentage
        [ "^(\[.*\])", "yellow" ]
    ]

cmake theme

def theme(context):
    # CMake theme:
    #  actions performing in cyan
    performing="yellow"
    #  actions performed in green
    performed="green"
    #  actions taking an unknown time
    untimed="blue"

    return context,[
        # Configure...
        [ "^--.*works", performed ],
        [ "^--.*done", performed ],
        [ "^-- Found.*NO", "red" ],
        [ "^-- Found.*", performed ],
        [ "^--.*broken", "red" ],
        [ "^-- Coult NOT find.*", "red" ],
        [ "^-- Configuring incomplete, errors occurred!", "red" ],
        [ "^--.*", performing ],
        # Errors
        [ "CMake .*Error:", "red" ],
        [ "CMake .*Warning", "magenta" ],
        # Scan
        [ "^(Scanning dependencies of target)(.*)$",
          performing, "normal,bold" ],
    ]

Logging theme

Theme used to color output from SN@ilWare software. Syntax used is defined in this file https://nemo.lpc-caen.in2p3.fr/browser/datatools/trunk/include/datatools/logger.h

#encoding: utf-8

def theme(context):
    error="red"
    warning="magenta"
    notice="blue"
    information="cyan"
    debug="green"
    trace="yellow"
    return context, [
        [ "(^\[fatal]:|^\[fatal.*\])(.*$)", error, "bold,normal" ],
        [ "(^\[error]:|^\[error.*\])(.*$)", error, "bold,normal" ],
        [ "(^\[warning]:|^\[warning.*\])(.*$)", warning, "bold,normal" ],
        [ "(^\[notice]:|^\[notice.*\])(.*$)", notice, "bold,normal" ],
        [ "(^\[information]:|^\[information.*\])(.*$)", information, "bold,normal" ],
        [ "(^\[debug]:|^\[debug.*\])(.*$)", debug, "bold,normal" ],
        [ "(^\[trace]:|^\[trace.*\])(.*$)", trace, "bold,normal" ],
  ]

org-mode theme

#encoding: utf-8

def theme(context):
    return context, [
        [ "(=[^\"].*?=[^\"])", "cyan" ],
        [ "^\*{1}\s.*$", "red", "bold" ],
        [ "^\*{2}\s.*$", "green", "bold" ],
        [ "^\*{3}\s.*$", "blue", "bold" ],
        [ "^\*{4}\s.*$", "yellow", "bold" ],
        [ "^\*{5}\s.*$", "cyan", "bold" ],
        [ ("((?i)^#\+)(title|date|author|email):(.*)"), "blue", "bold,bold,normal" ],
        [ "#\+.*$", "250" ],
        [ "^:.*:.*$", "250" ],
        [ "\[\w\]", "magenta" ],
        [ "\[\[.*\]\]", "yellow" ],
        [ "^[\||+-].*", "blue" ],
  ]

rsync theme

#encoding: utf-8

def theme(context):
      return context, [
            ["^sending.*", "red", "bold"],
            ["(^sent.*bytes.*)(received.*bytes) (.*/sec)",
             "blue,magenta,yellow", "bold,bold,normal"],
            ["(^total.*) (speedup.*)",
             "green,cyan", "bold,normal"],
            [ "^[\.a-zA-Z].*", "yellow", "normal"],
            [ "(^.*) (.*%)(.*/s)(.*:.*:.*).*(\(xfr#.*\))",
              "blue,green,magenta,green",
              "bold,conceal,normal,normal,conceal"]
      ]

Wrapping some functions arround colout

cmake

if (( $+commands[cmake] )); then
    function cmake ()
    {
        $(pkgtools::get_binary_path cmake) $@ | colout -t cmake
    }
fi

ninja

if (( $+commands[ninja] )); then
    function ninja ()
    {
        $(pkgtools::get_binary_path ninja) $@ | colout -t mycmake -T ${zsh_utilities_dir} | colout -t myg++ -T ${zsh_utilities_dir} | colout -t myninja -T ${zsh_utilities_dir}
    }
fi

Postamble

fi

mr

Preamble

if (( $+commands[mr] )); then

Function

function mr ()
{
    last=~/${@[-1]}
    if [ -d $last ]; then
        (
            cd $last
            $(pkgtools::get_binary_path $0) ${@:1:-1}
        )
    else
        $(pkgtools::get_binary_path $0) $@
    fi
}

Postamble

fi

plan

plan is a python package for writing and deploying cron jobs. plan will convert python code to cron syntax.

If the following error occurs

~/.local/lib/python3.8/site-packages/plan/core.py in read_crontab(self)
    206 
    207             if returncode != 0:
--> 208                 raise PlanError("couldn't read crontab")
    209         except OSError:
    210             raise PlanError("couldn't read crontab; please make sure you "

PlanError: couldn't read crontab

you first need to create an entry in crontab. So you have to do sudo EDITOR=nano crontab -u $USER -e and close the empty file. You should get

no crontab for garrido - using an empty one
crontab: no changes made to crontab

Make sure to use nano and not vi or emacs. To make sure everything goes well you can check that crontab -l works well (otherwise it would say no crontab for USER) and a USER directory within /var/spool/cron must have been created

Cron syntax

from plan import Plan

cron = Plan()

# cron.command('DISPLAY=:0 /home/garrido/.config/openbox/scripts/change-wallpaper', every='1.hour')
cron.command('DISPLAY=:0 /home/garrido/Development/org-caldav/sync_calendar.sh', every='1.day', at='12:00')
cron.command('cp /home/garrido/.emacs.d/tmp/session/emacs.desktop /home/garrido/.emacs.d/tmp/session/emacs-`date +\%Y-\%m-\%d`.desktop', every='monthly')
cron.command('DISPLAY=:0 /home/garrido/.bin/mybackup --profile lal', every='1.day', at='13:00')
cron.command('DISPLAY=:0 /home/garrido/.bin/mybackup --profile usb', every='1.day', at='13:00')
cron.command('DISPLAY=:0 /home/garrido/.bin/mybackup --profile orico', every='1.day', at='6:00')
if __name__ == '__main__':
    cron.run('update')

fzf

fzf is a general-purpose command-line fuzzy finder. See https://github.com/junegunn/fzf

Preamble

if (( $+commands[fzf] )); then
    [ -f /usr/share/fzf/completion.zsh ] && source /usr/share/fzf/completion.zsh
    [ -f /usr/share/fzf/key-bindings.zsh ] && source /usr/share/fzf/key-bindings.zsh

Use ag

if (( $+commands[ag] )); then
    export FZF_DEFAULT_COMMAND='ag -g ""'
fi

Color scheme

export FZF_DEFAULT_OPTS="--color=16,info:4,pointer:3,bg+:-1"

z - changing directory with fasd

z() {
    [ $# -gt 0 ] && fasd_cd -d "$*" && return
    local dir
    dir="$(fasd -Rdl "$1" | fzf -1 -0 --no-sort +m)" && cd "${dir}" || return 1
}

fo - open file

fo() {
    (
        cd ~
        local out file key
        IFS=$'\n' out=$(fzf --query="$1" --exit-0 --expect=ctrl-o,ctrl-e --preview '[[ $(file --mime {}) =~ binary ]] &&
               echo {} is a binary file ||
               (bat --style=numbers --color=always {} ||
                highlight -O ansi -l {} ||
                coderay {} ||
                rougify {} ||
                cat {}) 2> /dev/null | head -500')
        key=$(head -1 <<< "$out")
        file=$(head -2 <<< "$out" | tail -1)
        if [ -n "$file" ]; then
            [ "$key" = ctrl-e ] && ec "$file" || xdg-open "$file" &
        fi
    )
}

fd - go to the directory where the file is

fd() {
    pkgtools::enter_directory $HOME
    local file
    local dir
    file=$(fzf +m -q "$1") && dir=$(dirname "$file")
    if [ -d "$dir" ]; then
      cd "$dir"
    else
      pkgtools::exit_directory
      return 1
    fi
    return 0
}

Postamble

fi

docker

Preamble

if (( $+commands[docker] )); then

Clean docker

From https://lebkowski.name/docker-volumes/

function clean_docker ()
{
    # remove exited containers:
    docker ps --filter status=dead --filter status=exited -aq | xargs -r docker rm -v

    # remove unused images:
    docker images --no-trunc | grep '<none>' | awk '{ print $3 }' | xargs -r docker rmi --force

    # # remove unused volumes:
    # sudo find '/home/garrido/Development/docker.d/volumes/' -mindepth 1 -maxdepth 1 -type d | grep -vFf <(
    #         docker ps -aq | xargs sudo docker inspect | jq -r '.[] | .Mounts | .[] | .Name | select(.)'
    #     ) | xargs -r sudo rm -fr
}

Aliases

function acroread ()
{
    if [ -z $1 ]; then
        pkgtools::msg_error "Missing pdf file!"
        return 1
    fi
    xhost +local:docker
    local _path=$(dirname $1)
    [[ $_path = . ]] && _path=$PWD
    local _file=$(basename $1)
    docker run --rm  -v $_path:/home/acroread/Documents:rw \
           -v /tmp/.X11-unix:/tmp/.X11-unix \
           -e DISPLAY=$DISPLAY \
           -e FILE='/home/acroread/Documents/'$_file \
           --name acroread \
           chrisdaish/acroread
}

Postamble

fi

mybackup

Preamble

if (( $+commands[mybackup] )); then

Completion

compdef _mybackup mybackup
function _mybackup()
{
    local ret=1 state

    _arguments                                         \
        {-h,--help}'[produce help message]'            \
        {-d,--debug}'[enable debug mode]'              \
        {-D,--devel}'[enable devel mode]'              \
        '--profile[set the profile]:profile:->prof'    \
        && ret=0

    case $state in
        prof)
            local -a _profiles
            _profiles=(
                lal:'LAL machine'
                usb:'USB hard disk'
                orico:'Orico hard disk'
            )
            _describe -t _profiles 'Backup profiles' _profiles
            ;;
    esac

    return ret
}

Postamble

fi

exa/eza

Preamble

if (( $+commands[eza] )); then

Alias

alias ls="eza"
alias ll="ls --long --git --sort time"
alias lla="ll -a"

Postamble

fi