d88887195fd5535ef2fd95180baa73af2a8c88f8

Author
Marc Cornellà <marc.cornella@live.com>
Committer
GitHub <noreply@github.com>
Date

Message

fix(magic-enter): fix various bugs in the plugin (#9466)

Diff

 1diff --git a/plugins/magic-enter/magic-enter.plugin.zsh b/plugins/magic-enter/magic-enter.plugin.zsh
 2index 2d4d578b6da42296fc8fc01d0aef7cae772a8431..55b893535ca3895ea91de3687acaf17dd1b650a8 100644
 3--- a/plugins/magic-enter/magic-enter.plugin.zsh
 4+++ b/plugins/magic-enter/magic-enter.plugin.zsh
 5@@ -1,27 +1,38 @@
 6-# Bind quick stuff to enter!
 7-#
 8-# Pressing enter in a git directory runs `git status`
 9-# in other directories `ls`
10-magic-enter () {
11-  # If commands are not already set, use the defaults
12-  [ -z "$MAGIC_ENTER_GIT_COMMAND" ] && MAGIC_ENTER_GIT_COMMAND="git status -u ."
13-  [ -z "$MAGIC_ENTER_OTHER_COMMAND" ] && MAGIC_ENTER_OTHER_COMMAND="ls -lh ."
14+# Default commands
15+: ${MAGIC_ENTER_GIT_COMMAND:="git status -u ."} # run when in a git repository
16+: ${MAGIC_ENTER_OTHER_COMMAND:="ls -lh ."}      # run anywhere else
17 
18-  if [[ -z $BUFFER ]]; then
19-    echo ""
20-    if git rev-parse --is-inside-work-tree &>/dev/null; then
21-      eval "$MAGIC_ENTER_GIT_COMMAND"
22-    else
23-      eval "$MAGIC_ENTER_OTHER_COMMAND"
24-    fi
25-    zle redisplay
26+magic-enter() {
27+  # Only run MAGIC_ENTER commands when in PS1 and command line is empty
28+  # http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#User_002dDefined-Widgets
29+  if [[ -n "$BUFFER" || "$CONTEXT" != start ]]; then
30+    return
31+  fi
32+
33+  if command git rev-parse --is-inside-work-tree &>/dev/null; then
34+    BUFFER="$MAGIC_ENTER_GIT_COMMAND"
35   else
36-    zle accept-line
37+    BUFFER="$MAGIC_ENTER_OTHER_COMMAND"
38   fi
39 }
40 
41-zle -N magic-enter
42+# Wrapper for the accept-line zle widget (run when pressing Enter)
43+
44+# If the wrapper already exists don't redefine it
45+(( ! ${+functions[_magic-enter_accept-line]} )) || return 0
46+
47+case "$widgets[accept-line]" in
48+  # Override the current accept-line widget, calling the old one
49+  user:*) zle -N _magic-enter_orig_accept-line "${widgets[accept-line]#user:}"
50+    function _magic-enter_accept-line() {
51+      magic-enter
52+      zle _magic-enter_orig_accept-line -- "$@"
53+    } ;;
54+  # If no user widget defined, call the original accept-line widget
55+  builtin) function _magic-enter_accept-line() {
56+      magic-enter
57+      zle .accept-line
58+    } ;;
59+esac
60 
61-bindkey -M emacs "^M" magic-enter
62-bindkey -M vicmd "^M" magic-enter
63-bindkey -M viins "^M" magic-enter
64+zle -N accept-line _magic-enter_accept-line