zshrc.d/30-functions.zrc
author Mikael Berthe <mikael@lilotux.net>
Sat, 14 Jul 2012 19:31:01 +0200
changeset 1 7da32984f5b5
parent 0 7215ca490221
child 5 5dbc9ebf690c
permissions -rw-r--r--
Add a README in the zsh_local directory, remove placeholder Isn't a README much more useful than the previous placeholder?


#############
# Functions #
#############

# Commande tres pratique pour formatter un fichier .man
# exemple : mf prog.1
function mf() { tbl $* | nroff -mandoc | less -s }

# ,,(), ,,,() for quickly changing $CWD {{{1
# http://www.shell-fu.org/lister.php?id=769

# Go up n levels:
# ,, 3
function ,, (){
    local arg=${1:-1};
    local dir=""
    while [ $arg -gt 0 ]; do
        dir="../$dir"
        arg=$(($arg - 1));
    done
    cd $dir >&/dev/null
}

# Go up to a named dir
# ,,, usr
function ,,, (){
    if [ -z "$1" ]; then
        return
    fi
    local maxlvl=16
    local dir=$1
    while [ $maxlvl -gt 0 ]; do
        dir="../$dir"
        maxlvl=$(($maxlvl - 1));
        if [ -d "$dir" ]; then
            cd $dir >&/dev/null
        fi
    done
}


# Customized version from Frank Terbeck' scripts
# http://bewatermyfriend.org/p/2011/013/
# "."   will display the current working directory
# ".."  will get you 1 directory up,
# "..." will get you 2 directories up, etc.
function ft_accept_line_cd_up() {
    setopt local_options extended_glob
    local -a cmdline
    cmdline=( ${(z)BUFFER} )
    if (( ${#cmdline} == 1 )) && [[ ${cmdline[1]} == "." ]] ; then
        BUFFER="pwd"
        zle ".$WIDGET"
        return
    fi
    if (( ${#cmdline} == 1 )) && [[ ${cmdline[1]} == ..## ]] ; then
        BUFFER='cd '
        for (( i = 2; i <= ${#${cmdline[1]}}; i++ )); do
            BUFFER="${BUFFER}../"
        done
        BUFFER=${BUFFER%/}
    fi
    zle ".$WIDGET"
}
zle -N accept-line ft_accept_line_cd_up

# 2nd part, completion support...
function ft_complete_with_dots() {
    setopt local_options extended_glob
    local -a cmdline
    cmdline=( ${(z)BUFFER} )
    if (( ${#cmdline} == 1 )) && [[ ${cmdline[1]} == ..## ]] ; then
        BUFFER='cd '
        for (( i = 2; i <= ${#${cmdline[1]}}; i++ )); do
            BUFFER="${BUFFER}../"
        done
        CURSOR=${#BUFFER}
    fi
    zle ".$WIDGET"
}
# Disabling for now as I don't know how to fallback to automatic correction...
#zle -N expand-or-complete ft_complete_with_dots


# genpass()
# Generates a tough password of a given length
# Borrowed (and slightly modifed) from Seth House github repository.

function genpass() {
    if [ ! "$1" ]; then
        echo "Usage: $0 20"
        echo "For a random, 20-character password."
        return 1
    fi
    dd if=/dev/urandom count=1 2>/dev/null | tr -cd 'A-Za-z0-9' | cut -c-$1
}