d87f29f564286c4a233e454d8208b83b97b1366d

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

Message

refactor(vim-interaction): clean up code and open gvim instance if none open (#10209)

Co-authored-by: Kevin Bader <keb@visotech.at>

Diff

 1diff --git a/plugins/vim-interaction/vim-interaction.plugin.zsh b/plugins/vim-interaction/vim-interaction.plugin.zsh
 2index 53ec453e84902cd4013b9ba52371aa44fbfe068f..b73f9b4da5b2d9fe4d5c6600982901b89880f6d0 100644
 3--- a/plugins/vim-interaction/vim-interaction.plugin.zsh
 4+++ b/plugins/vim-interaction/vim-interaction.plugin.zsh
 5@@ -4,8 +4,7 @@
 6 # Derek Wyatt (derek@{myfirstnamemylastname}.org
 7 # 
 8 
 9-function callvim
10-{
11+function callvim {
12   if [[ $# == 0 ]]; then
13     cat <<EOH
14 usage: callvim [-b cmd] [-a cmd] [-n name] [file ... fileN]
15@@ -19,11 +18,20 @@ EOH
16     return 0
17   fi
18 
19-  local cmd=""
20-  local before="<esc>"
21-  local after=""
22-  # Look up the newest instance
23+  # Look up the newest instance or start one
24   local name="$(gvim --serverlist | tail -n 1)"
25+  [[ -n "$name" ]] || {
26+    # run gvim or exit if it fails
27+    gvim || return $?
28+
29+    # wait for gvim instance to fully load
30+    while name=$(gvim --serverlist) && [[ -z "$name" ]]; do
31+      sleep 0.1
32+    done
33+  }
34+
35+  local before="<esc>" files after cmd
36+
37   while getopts ":b:a:n:" option
38   do
39     case $option in
40@@ -36,22 +44,20 @@ EOH
41     esac
42   done
43   shift $((OPTIND-1))
44-  if [[ ${after#:} != $after && ${after%<cr>} == $after ]]; then
45-    after="$after<cr>"
46-  fi
47-  if [[ ${before#:} != $before && ${before%<cr>} == $before ]]; then
48-    before="$before<cr>"
49-  fi
50-  local files
51-  if [[ $# -gt 0 ]]; then
52-    # absolute path of files resolving symlinks (:A) and quoting special chars (:q)
53-    files=':args! '"${@:A:q}<cr>"
54-  fi
55+
56+  # If before or after commands begin with : and don't end with <cr>, append it
57+  [[ ${after}  = :* && ${after}  != *\<cr\> ]] && after+="<cr>"
58+  [[ ${before} = :* && ${before} != *\<cr\> ]] && before+="<cr>"
59+  # Open files passed (:A means abs path resolving symlinks, :q means quoting special chars)
60+  [[ $# -gt 0 ]] && files=':args! '"${@:A:q}<cr>"
61+  # Pass the built vim command to gvim
62   cmd="$before$files$after"
63-  gvim --servername "$name" --remote-send "$cmd"
64-  if typeset -f postCallVim > /dev/null; then
65-    postCallVim
66-  fi
67+
68+  # Run the gvim command
69+  gvim --servername "$name" --remote-send "$cmd" || return $?
70+
71+  # Run postCallVim if defined (maybe to bring focus to gvim, see README)
72+  (( ! $+functions[postCallVim] )) || postCallVim
73 }
74 
75 alias v=callvim