define (1915B)
1 #!/bin/sh 2 set -e 3 history_file=~/.cache/define.hist 4 history_length=100 5 6 show_help() { 7 echo "usage: ${0##*/} [OPTIONS] TERM[S]" 8 echo "shows definitions for each TERM from dict.org" 9 echo 10 echo "Options:" 11 echo " -g, --gui use dmenu for input and notify for output" 12 echo " -np, --no-pager do not use a pager for long output" 13 echo " -h, --help show this message" 14 } 15 16 prepare_history_file() { 17 mkdir -p "$(dirname "$history_file")" 18 [ ! -f "$history_file" ] && touch "$history_file" || : 19 } 20 21 trim_history_file() { 22 if [ "$(wc -l "$history_file"|awk '{print $1}')" -ge $history_length ]; then 23 tail -n $history_length "$history_file" > "${history_file}.tmp" && \ 24 mv "${history_file}.tmp" "${history_file}" 25 fi 26 } 27 28 add_to_history() { 29 printf '%s\n' "$1" >> "$history_file" 30 } 31 32 define() { 33 add_to_history "$1" 34 curl --silent dict://dict.org/d:"$1" 35 trim_history_file 36 } 37 38 remove_comm_msgs() { 39 grep -vE '[0-9][0-9] ' | \ 40 sed 's/^\.//' 41 } 42 43 die() { 44 printf '%s\n' "$1" >&2 45 exit 1 46 } 47 48 gui=0 49 pager=1 50 while :; do 51 case "$1" in 52 -h|-\?|--help) 53 show_help 54 exit 0 55 ;; 56 -g|--gui) 57 gui=1 58 ;; 59 -np|--no-pager) 60 pager=0 61 ;; 62 --) # end all options 63 shift 64 break 65 ;; 66 -?*) 67 die 'ERROR: Unknown option specified' 68 ;; 69 *) # no more options 70 break 71 esac 72 shift 73 done 74 75 prepare_history_file 76 77 if [ "$gui" = 1 ]; then 78 suggestions="$(printf '%s\n' "$(xclip -o)"; cat "$history_file")" 79 word=$(echo "$suggestions" | dmenu -i -p "Dictionary lookup:") || exit 1 80 notify -t 10000 "define: $word" "$(define "$word" | remove_comm_msgs)" 81 exit 0 82 else 83 [ $# -lt 1 ] && (show_help && exit 1) 84 fi 85 86 definition="" 87 for word in "$@"; do 88 definition="${definition}\n$(define "$word" | remove_comm_msgs)" 89 done 90 if [ "$(printf "%s" "$definition" | wc -l)" -gt "$(tput lines)" ] && \ 91 [ "$pager" = 1 ]; then 92 printf "%s" "$definition" | tail -n +2 | less 93 else 94 printf "%s" "$definition" | tail -n +2 95 fi