aboutsummaryrefslogtreecommitdiffstats
path: root/lib/functions.sh
blob: f9aab582565c7ffecfe892d56d0879e084bc94ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/bin/bash

### ariketa helper functions

# establish key bindings in current session
## accepts split string arrays or strings, one array or string per binding
_bindings.load_from_arrays () {
    local _binding
    for _binding; do
        declare -n _binding_array="${_binding}"
        bind "${_binding_array[*]}"
    done
}

_example.highlight () { 
    hl < <(echo "${_examples[$_I]}")
}

### prompt / tagging helpers

#custom tag:value tuple handlers for _examples array
## tag delineator is ":\n"
_example.unpack() {
    printf "%s" "${1#*:$'\n'}"
}

_tag.unpack() {
    local _tag="${1%%:$'\n'*}"
    (( ${#_tag} < ${#1} )) || return 1
    printf "%s" "$_tag"
}

#presentation page header prompt display functions
## specify custom indicator as argument, '+' is default
_ps2.swap () {
    local _cur_ps2="${PS2}"
    PS2="$_old_ps2"
    _old_ps2="$_cur_ps2"
}

_tag.same_as_next? () {
    [[ "$(_tag.unpack "${_examples[$_I]}")" \
    == "$(_tag.unpack "${_examples[$((_I+1))]}")" ]] \
        || return 1
    printf "%s" "${1:-+}"
}

_tag.same_as_prev? () {
    [[ "$(_tag.unpack "${_examples[$_I]}")" \
    == "$(_tag.unpack "${_examples[$((_I-1))]}")" ]] \
        || return 1
    printf "%s" "${1:-+}"
}

_tag.display () {
    local _tag=$(_tag.unpack "${_examples[$_I]}") \
        && printf "[$(_tag.same_as_prev?) %s $(_tag.same_as_next?)]" "${_tag}"
}

### public functions

#simple bash code highlighting if the 'highlight' program is installed
## http://www.andre-simon.de/doku/highlight/en/highlight.php
hl () { 
    local hl=$(which highlight 2>/dev/null) || {
        printf "%s\n" "${@}"
	return
    }
    "$hl" --syntax bash -O xterm256 "${@}"
}

#diff between adjacent examples
ydiff () {
    diff -wyW${COLUMNS:-80} \
        <(echo "${_examples[(( _I - ${1:-1} ))]}") \
        <(echo "${_examples[(( _I ))]}")
    local diff_err=$?
    (( diff_err <= 1 )) || return $diff_err
    return 0
}