Add zsh-autosuggestion
[zsh.git] / .zsh / external / zsh-autosuggestions / src / strategies / match_prev_cmd.zsh
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 local prefix="$1"
25
26 # Get all history event numbers that correspond to history
27 # entries that match pattern $prefix*
28 local history_match_keys
29 history_match_keys=(${(k)history[(R)$prefix*]})
30
31 # By default we use the first history number (most recent history entry)
32 local histkey="${history_match_keys[1]}"
33
34 # Get the previously executed command
35 local prev_cmd="$(_zsh_autosuggest_escape_command "${history[$((HISTCMD-1))]}")"
36
37 # Iterate up to the first 200 history event numbers that match $prefix
38 for key in "${(@)history_match_keys[1,200]}"; do
39 # Stop if we ran out of history
40 [[ $key -gt 1 ]] || break
41
42 # See if the history entry preceding the suggestion matches the
43 # previous command, and use it if it does
44 if [[ "${history[$((key - 1))]}" == "$prev_cmd" ]]; then
45 histkey="$key"
46 break
47 fi
48 done
49
50 # Echo the matched history entry
51 echo -E "$history[$histkey]"
52 }