diff --git a/bin/d b/bin/d index 0262628..72b4b11 100755 --- a/bin/d +++ b/bin/d @@ -1,17 +1,34 @@ #!/bin/sh -# shellcheck disable=2086 +# shellcheck disable=2086,2059 +# dmenu optional patches: preselect / center +# fzf selector: 'fzf --reverse --height=30%%' set -e DIR="$(readlink -f "$(dirname "$0")")" -DMENU_OPTS='-i -c -fn monospace:13 -nb #626262 -nf #bbbbbb -sb #5b97f7 -sf #eeeeee -l 20' + +# compose selector command if not specified +if [ -z "$SELECTOR" ]; then + if command -v dmenu >/dev/null; then + SELECTOR='dmenu -i -fn monospace:13 -nb #626262 -nf #bbbbbb -sb #5b97f7 -sf #eeeeee -l 20' + dmenu -h 2>&1 | grep -qF ' [-n number]' && SELECTOR="$SELECTOR -n %i" + dmenu -h 2>&1 | grep -qP '\[-\w*c\w*\]' && SELECTOR="$SELECTOR -c" + elif command -v fzf >/dev/null; then + SELECTOR='fzf --reverse --height=30%%' + else + echo 'require either dmenu or fzf' + exit 1 + fi +fi +EMPTY_RESULT=' 查无结果' +GREETING='﬜ 请输入单词并回车' request() { RESULT="$( curl -SsLG "http://dict.youdao.com/w/eng/$SENTENCE/" \ | awk -v PI=' ' -f "$DIR/dict.awk" - )" + )" display } @@ -25,8 +42,17 @@ pronounce() { } display() { - echo "$RESULT" \ - | dmenu $DMENU_OPTS \ + R="$RESULT" + if [ -z "$R" ]; then + if [ -n "$SENTENCE" ]; then + R="$EMPTY_RESULT : $SENTENCE" + else + R="$GREETING" + fi + fi + SELECT=$(printf "$SELECTOR" "$LINE_NUM") + echo "$R" \ + | $SELECT \ | if IFS= read -r INPUT; then if echo "$INPUT" | grep -qP ' '; then if echo "$INPUT" | grep -q '美'; then @@ -34,8 +60,12 @@ display() { else pronounce "$SENTENCE" 1 & fi - display - elif echo "$INPUT" | grep -P '^ '; then + echo awk '"'$INPUT'" { print NR }' + LINE_NUM=$(echo "$RESULT" | awk -v INPUT="$INPUT" '$0==INPUT { print NR - 1 }') + display $LINE_NUM + elif echo "$INPUT" | grep -qF "$EMPTY_RESULT" || echo "$INPUT" | grep -qF "$GREETING"; then + return + elif echo "$INPUT" | grep -qP '^ '; then printf "%s" "$INPUT" | sed 's/^\s+//' | xsel -b else SENTENCE="$INPUT"