Add zsh anything.el plugin
[zsh.git] / .zsh / zaw / sources / bookmark.zsh
1 #
2 # zaw-src-bookmark
3 #
4 # bookmark your favorite command lines, access it using zaw interface.
5 # you can bookmark command line using zaw-history's `bookmark this command line` action,
6 # or bind some key to ``zaw-bookmark-add-buffer`` and use it.
7 #
8
9 zmodload zsh/system
10 autoload -U fill-vars-or-accept
11
12 typeset -g BOOKMARKFILE="${BOOKMARKFILE:-"${HOME}/.zaw-bookmarks"}"
13
14 function zaw-src-bookmark() {
15 if [[ -f "${BOOKMARKFILE}" ]]; then
16 candidates=("${(Qf)$(zsystem flock -r "${BOOKMARKFILE}" && < "${BOOKMARKFILE}")}")
17 fi
18 actions=("zaw-bookmark-execute" "zaw-callback-replace-buffer" "zaw-callback-append-to-buffer" "zaw-bookmark-remove")
19 act_descriptions=("execute" "replace edit buffer" "append to edit buffer" "removed bookmark")
20 options=("-m")
21 }
22
23 zaw-register-src -n bookmark zaw-src-bookmark
24
25
26 #
27 # helper functions for bookmark
28 #
29
30 function zaw-bookmark-execute() {
31 zaw-callback-replace-buffer "$@"
32 fill-vars-or-accept
33 }
34
35 function zaw-bookmark-add() {
36 local -a bookmarks
37
38 : >>| "${BOOKMARKFILE}"
39 (
40 if zsystem flock -t 5 "${BOOKMARKFILE}"; then
41 bookmarks=("${(f)$(< "${BOOKMARKFILE}")}" "${(q@)@}")
42
43 # remove empty lines
44 bookmarks=("${(@)bookmarks:#}")
45
46 # remove duplicated lines, sort and write to ${BOOKMARKFILE}
47 print -rl -- "${(@un)bookmarks}" >| "${BOOKMARKFILE}"
48 else
49 print "can't acquire lock for '${BOOKMARKFILE}'" >&2
50 exit 1
51 fi
52 )
53
54 if [[ $? == 0 ]]; then
55 zle -M "bookmark '${(j:', ':)@}'"
56 fi
57 }
58
59 function zaw-bookmark-add-buffer() {
60 zaw-bookmark-add "${BUFFER}"
61 }
62
63 zle -N zaw-bookmark-add-buffer
64
65 function zaw-bookmark-remove() {
66 local s
67 local -a bookmarks
68
69 : >>| "${BOOKMARKFILE}"
70 (
71 if zsystem flock -t 5 "${BOOKMARKFILE}"; then
72 bookmarks=("${(f)$(< "${BOOKMARKFILE}")}")
73 for s in "${(q@)@}"; do
74 bookmarks=("${(@)bookmarks:#${s}}")
75 done
76
77 # remove duplicated lines, sort and write to ${BOOKMARKFILE}
78 print -rl -- "${(@un)bookmarks}" >| "${BOOKMARKFILE}"
79 else
80 print "can't acquire lock for '${BOOKMARKFILE}'" >&2
81 exit 1
82 fi
83 )
84
85 if [[ $? == 0 ]]; then
86 zle -M "bookmark '${(j:', ':)@}' removed"
87 fi
88 }
89
90 function zaw-bookmark-remove-buffer() {
91 zaw-bookmark-remove "${BUFFER}"
92 }
93
94 zle -N zaw-bookmark-remove-buffer