comparison .zfun/zsh-autosuggestions/src/strategies/match_prev_cmd.zsh @ 467:e1ce8897030d

zsh: import df6f6f9ff41 of zsh-autosuggestions
author Augie Fackler <raf@durin42.com>
date Mon, 03 Dec 2018 22:37:29 -0500
parents
children
comparison
equal deleted inserted replaced
466:f248cf012d9a 467:e1ce8897030d
1
2 #--------------------------------------------------------------------#
3 # Match Previous Command Suggestion Strategy #
4 #--------------------------------------------------------------------#
5 # Suggests the most recent history item that matches the given
6 # prefix and whose preceding history item also matches the most
7 # recently executed command.
8 #
9 # For example, suppose your history has the following entries:
10 # - pwd
11 # - ls foo
12 # - ls bar
13 # - pwd
14 #
15 # Given the history list above, when you type 'ls', the suggestion
16 # will be 'ls foo' rather than 'ls bar' because your most recently
17 # executed command (pwd) was previously followed by 'ls foo'.
18 #
19 # Note that this strategy won't work as expected with ZSH options that don't
20 # preserve the history order such as `HIST_IGNORE_ALL_DUPS` or
21 # `HIST_EXPIRE_DUPS_FIRST`.
22
23 _zsh_autosuggest_strategy_match_prev_cmd() {
24 # Reset options to defaults and enable LOCAL_OPTIONS
25 emulate -L zsh
26
27 # Enable globbing flags so that we can use (#m)
28 setopt EXTENDED_GLOB
29
30 # TODO: Use (b) flag when we can drop support for zsh older than v5.0.8
31 local prefix="${1//(#m)[\\*?[\]<>()|^~#]/\\$MATCH}"
32
33 # Get all history event numbers that correspond to history
34 # entries that match pattern $prefix*
35 local history_match_keys
36 history_match_keys=(${(k)history[(R)$prefix*]})
37
38 # By default we use the first history number (most recent history entry)
39 local histkey="${history_match_keys[1]}"
40
41 # Get the previously executed command
42 local prev_cmd="$(_zsh_autosuggest_escape_command "${history[$((HISTCMD-1))]}")"
43
44 # Iterate up to the first 200 history event numbers that match $prefix
45 for key in "${(@)history_match_keys[1,200]}"; do
46 # Stop if we ran out of history
47 [[ $key -gt 1 ]] || break
48
49 # See if the history entry preceding the suggestion matches the
50 # previous command, and use it if it does
51 if [[ "${history[$((key - 1))]}" == "$prev_cmd" ]]; then
52 histkey="$key"
53 break
54 fi
55 done
56
57 # Give back the matched history entry
58 typeset -g suggestion="$history[$histkey]"
59 }