Browse Source

nixpkgs/elvish: better cobra completion support

Thomas Dy 1 year ago
parent
commit
c4bd54bab0

+ 0 - 17
.config/nixpkgs/elvish/lib/cobra.elv

@@ -1,17 +0,0 @@
-use str
-
-fn complete {|command @rest|
-  (external $command) __complete $@rest 2>/dev/null | each {|line|
-    if (str:has-prefix $line ":") {
-      continue
-    }
-
-    var @result = (str:split &max=2 "\t" $line)
-    var name = $result[0]
-    var description = $name
-    if (> (count $result) 1) {
-      set description = $description' ('$result[1]')'
-    }
-    edit:complex-candidate $result[0] &display=$description &code-suffix=' '
-  }
-}

+ 61 - 0
.config/nixpkgs/elvish/lib/completion.elv

@@ -0,0 +1,61 @@
+use str
+use math
+use path
+
+fn make-filecomp {|predicate|
+  put {|command @rest|
+    var target = $rest[-1]
+
+    put $target* | each {|candidate|
+      var is-dir = (path:is-dir &follow-symlink=$true $candidate)
+      if ($predicate $candidate $is-dir) {
+        if $is-dir {
+          var display = (styled $candidate blue bold)/
+          edit:complex-candidate $candidate &display=$display &code-suffix=/
+        } else {
+          put $candidate
+        }
+      }
+    }
+  }
+}
+
+var files~ = (make-filecomp {|candidate is-dir| not $is-dir})
+var dirs~ = (make-filecomp {|candidate is-dir| put $is-dir})
+var any~ = (make-filecomp {|@_| put $true})
+
+fn cobra {|command @rest|
+  var result = [((external $command) __complete $@rest 2>/dev/null)]
+
+  var code = (num $result[-1][1..])
+  var error = (> (% $code 2) 0)
+  set code = (math:floor (/ $code 2))
+  var no-space = (> (% $code 2) 0)
+  set code = (math:floor (/ $code 2))
+  var no-filecomp = (> (% $code 2) 0)
+
+  if $error {
+    return
+  }
+
+  var candidate = {|line|
+    var @result = (str:split &max=2 "\t" $line)
+    var name = $result[0]
+    var description = $name
+    if (> (count $result) 1) {
+      set description = $description' ('$result[1]')'
+    }
+    var suffix = ' '
+    if $no-space {
+      set suffix = ''
+    }
+
+    edit:complex-candidate $result[0] &display=$description &code-suffix=$suffix
+  }
+
+  if (> (count $result) 1) {
+    each $candidate $result[..-1]
+  } elif (not $no-filecomp) {
+    any $command $@rest
+  }
+}

+ 4 - 0
.config/nixpkgs/elvish/lib/config.elv

@@ -4,6 +4,7 @@ use nix-shell
 use direlv
 use title
 use eval-export
+use completion
 
 edit:add-var ls~ { |@a|
   e:ls --color=auto --group-directories-first -F --quoting-style literal $@a
@@ -40,6 +41,9 @@ set edit:after-command = [{|m|
 
 eval (carapace _carapace|slurp)
 
+# restrict completion to only directories
+set edit:completion:arg-completer[cd] = $completion:dirs~
+
 # import local.elv if present, for example, from ~/.config/elvish/lib/local.elv
 try {
   use local