History suggestions, frecency, cd by keyword, fish completions; bjoterm 0.2.0
The editor suggests history lines whose command exists, cd lines by the frecency of their directory, paths ignoring case, and the visited directory that cd KEYWORD... goes to. Tab completes arguments with fish's completions when fish is on PATH, and paths by the start of each part (~/P/B/B). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5012a5d993
commit
61d5a96eda
10 changed files with 751 additions and 110 deletions
|
|
@ -29,7 +29,10 @@ non-trivial functions. No essays.
|
|||
- `(bjosh values)`: values (`Json`), streams of them, text and tables.
|
||||
- `(bjosh commands)`: the value commands, and their table.
|
||||
- `(bjosh pipeline)`: value commands next to each other, as one unit.
|
||||
- `(bjosh editor)`: when Enter runs a line, and the completer.
|
||||
- `(bjosh editor)`: when Enter runs a line, the completer (fish's
|
||||
completions when fish is on PATH), and the suggester.
|
||||
- `(bjosh dirs)`: the visited directories, ranked by frecency, saved in
|
||||
`$XDG_STATE_HOME/bjosh/dirs`.
|
||||
- `(bjosh api)`: what a package of user commands imports: `Extension`,
|
||||
`ShellCommand`, `ShellView`.
|
||||
- `(bjosh user)`: builds and loads the package of user commands, in
|
||||
|
|
|
|||
4
bjo.lock
4
bjo.lock
|
|
@ -1,5 +1,5 @@
|
|||
(lock
|
||||
(locked
|
||||
(package (name (bjoterm)) (version "0.1.2")
|
||||
(package (name (bjoterm)) (version "0.2.0")
|
||||
(source (git (url "https://rikspucko.koketteriet.se/bjoli/bjoterm.git")))
|
||||
(commit "3021b14aac63b458fbaa589c4a5b02a9dd58c5432bfe7d3e0cb5667d9f618970"))))
|
||||
(commit "2b7749013d8b784c8185d3d14a291ef66a096257c33f151c0f7331301a5e861a"))))
|
||||
|
|
|
|||
|
|
@ -10,5 +10,5 @@
|
|||
;; The line editor and the terminal. To work on both at once, use
|
||||
;; (source (path (dir "../bjoterm"))) instead.
|
||||
(package (name (bjoterm))
|
||||
(version (version-at-least "0.1.2"))
|
||||
(version (version-at-least "0.2.0"))
|
||||
(source (git (url "https://rikspucko.koketteriet.se/bjoli/bjoterm.git"))))))
|
||||
|
|
|
|||
15
plan.org
15
plan.org
|
|
@ -357,7 +357,20 @@ the text above:*
|
|||
same command: the order of the two would matter. A stage with ~>&2~
|
||||
before another one in a pipe is an error, as one with ~>~ is.
|
||||
- An alias of its own name (~alias ls='ls -d'~) runs the program.
|
||||
- The completer does not complete aliases yet.
|
||||
- The completer completes aliases and the user's commands, with their
|
||||
help. Arguments complete with fish's completions when fish is on
|
||||
~PATH~ (~complete --do-complete~, at most 2 seconds), else with paths.
|
||||
Paths match with case, then without, then with each part as the start
|
||||
of a name (~~/P/B/B~).
|
||||
- The suggester, as fish's: a history line whose command exists (for
|
||||
~cd~, the one whose directory has the highest frecency), else
|
||||
directories and paths, else the visited directory that ~cd KEYWORD...~
|
||||
goes to.
|
||||
- An interactive shell saves the visited directories with their
|
||||
frecency, and the directory history, in ~$XDG_STATE_HOME/bjosh~. ~cd~
|
||||
with words that name no directory goes to the best match there and
|
||||
writes it. Only an interactive shell does that: a script's ~cd~ to a
|
||||
missing directory fails.
|
||||
- Tests: ~tests/syntax.bjo~ (72), ~tests/expand.bjo~ (26),
|
||||
~tests/editor.bjo~ (24), ~tests/run.bjo~ (60), ~tests/values.bjo~
|
||||
(59), ~tests/interactive.bjo~ (16). bjoterm's
|
||||
|
|
|
|||
|
|
@ -15,13 +15,14 @@
|
|||
(import (bjoterm line))
|
||||
(import (bjosh syntax))
|
||||
(import (bjosh shell))
|
||||
(import (bjosh dirs))
|
||||
(import (bjosh api))
|
||||
(import (bjosh user))
|
||||
(import (bjosh commands))
|
||||
(import (bjosh values))
|
||||
(import (text json))
|
||||
|
||||
(export builtin? run-builtin builtin-names find-program shell-value-command step-directory)
|
||||
(export builtin? builtin-help run-builtin builtin-names find-program shell-value-command step-directory)
|
||||
|
||||
(type (: Builtin (Record (: name string)
|
||||
(: usage string)
|
||||
|
|
@ -52,13 +53,20 @@
|
|||
(Ok unit))
|
||||
((Err e) (Err (.-Message e)))))
|
||||
|
||||
;; cd [DIR | - | KEYWORD...]
|
||||
;; - In an interactive shell, words that name no directory are keywords:
|
||||
;; cd goes to the visited directory they match best (see `dirs-match`),
|
||||
;; and writes it.
|
||||
;; - Each change is a visit in the frecency store.
|
||||
(: (-> Shell (Vec string) int))
|
||||
(defun (cd sh args)
|
||||
(def old (current-directory))
|
||||
(def jump (jump-target sh args))
|
||||
(def target
|
||||
(cond
|
||||
((vec-empty? args) (getenv "HOME"))
|
||||
((= (vec-ref args 0) "-") (getenv "OLDPWD"))
|
||||
((some? jump) jump)
|
||||
(else (Some (vec-ref args 0)))))
|
||||
(match target
|
||||
(None (shell-error "cd: no HOME or OLDPWD") 1)
|
||||
|
|
@ -66,12 +74,32 @@
|
|||
(match (change-directory dir)
|
||||
((Ok _)
|
||||
(unless (= (current-directory) old)
|
||||
(dir-visited! sh old))
|
||||
(when (and (not (vec-empty? args)) (= (vec-ref args 0) "-"))
|
||||
(dir-visited! sh old)
|
||||
(dir-arrived! sh))
|
||||
(when (or (some? jump) (and (not (vec-empty? args)) (= (vec-ref args 0) "-")))
|
||||
(println (current-directory)))
|
||||
0)
|
||||
((Err message) (shell-error (str "cd: " dir ": " message)) 1)))))
|
||||
|
||||
;; The visited directory that `args` match, when the shell saves its
|
||||
;; directories (an interactive one) and `args` are keywords that name no
|
||||
;; directory.
|
||||
(: (-> Shell (Vec string) (Option string)))
|
||||
(defun (jump-target sh args)
|
||||
(if (and (record-ref sh persist?)
|
||||
(not (vec-empty? args))
|
||||
(not (directory-exists? (vec-ref args 0)))
|
||||
(all? (fun (w) (and (not (string-empty? w))
|
||||
(not (string-contains? w "/"))
|
||||
(not (string-starts-with? w "."))
|
||||
(not (string-starts-with? w "-"))
|
||||
(not (string-starts-with? w "~"))))
|
||||
args))
|
||||
(match (dirs-match (record-ref sh dirs) args (current-directory))
|
||||
([] None)
|
||||
(found (Some (record-ref (vec-ref found 0) path))))
|
||||
None))
|
||||
|
||||
;; Moves one step back (`back?`) or forward in the directory history.
|
||||
;; - The directory left goes to the other side.
|
||||
;; - A directory that is gone is taken out of the history, and the step
|
||||
|
|
@ -477,6 +505,13 @@
|
|||
(: (Vec string))
|
||||
(def builtin-names (vec-map builtin-name (builtins)))
|
||||
|
||||
;; The help of the shell command `name`; "" when there is none.
|
||||
(: (-> string string))
|
||||
(defun (builtin-help name)
|
||||
(match (find (fun (b) (= (builtin-name b) name)) (builtins))
|
||||
((Some b) (record-ref b help))
|
||||
(None "")))
|
||||
|
||||
;; Runs the shell command `name`. Returns its status; 127 when there is no
|
||||
;; such command.
|
||||
(: (-> Shell string (Vec string) int))
|
||||
|
|
|
|||
146
src/dirs.bjo
Normal file
146
src/dirs.bjo
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
;; This Source Code Form is subject to the terms of the Mozilla Public
|
||||
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
;; (bjosh dirs): the directories the shell has been in, ranked by frecency.
|
||||
;;
|
||||
;; - Each directory has a count of visits and the time of the last one.
|
||||
;; Its score is the count times a weight for how recent the last visit
|
||||
;; is: 16 within an hour, 8 within a day, 2 within a week, else 1.
|
||||
;; - The store keeps `dirs-size` directories; the lowest scores go first.
|
||||
;; - Saved as lines of count, last visit in Unix ms and path, separated by
|
||||
;; tabs. A line that does not read is skipped.
|
||||
;; - `dirs-match`: the directories whose path has every keyword, in order
|
||||
;; and ignoring case, with the last one in the last component, as zoxide
|
||||
;; matches.
|
||||
|
||||
(import (std prelude))
|
||||
|
||||
(export
|
||||
DirEntry dirs-load dirs-save dirs-visit dirs-score dirs-match dirs-ranked
|
||||
lines-load lines-save state-path)
|
||||
|
||||
(type (: DirEntry (Record (: path string) (: count int) (: last long))))
|
||||
|
||||
(import/extern
|
||||
(now-ms (: System.DateTimeOffset.UtcNow System.DateTimeOffset #:get #:no-raise))
|
||||
(unix-ms (: System.DateTimeOffset.ToUnixTimeMilliseconds (-> System.DateTimeOffset long) #:no-raise)))
|
||||
|
||||
;; The most directories kept.
|
||||
(: int)
|
||||
(def dirs-size 1000)
|
||||
|
||||
(: (-> long))
|
||||
(defun (now)
|
||||
(unix-ms now-ms))
|
||||
|
||||
;; `name` in the shell's state directory: $XDG_STATE_HOME/bjosh, or
|
||||
;; ~/.local/state/bjosh.
|
||||
(: (-> string string))
|
||||
(defun (state-path name)
|
||||
(def state (match (getenv "XDG_STATE_HOME")
|
||||
((Some d) d)
|
||||
(None (path-combine (match (getenv "HOME") ((Some h) h) (None ".")) ".local/state"))))
|
||||
(path-combine state "bjosh" name))
|
||||
|
||||
;; The frecency of `e` at time `at`.
|
||||
(: (-> DirEntry long int))
|
||||
(defun (score-at e at)
|
||||
(def age (- at (record-ref e last)))
|
||||
(def weight (cond
|
||||
((< age 3600000L) 16)
|
||||
((< age 86400000L) 8)
|
||||
((< age 604800000L) 2)
|
||||
(else 1)))
|
||||
(* (record-ref e count) weight))
|
||||
|
||||
;; The score of `path` now; 0 when it is not in the store.
|
||||
(: (-> (Map string DirEntry) string int))
|
||||
(defun (dirs-score dirs path)
|
||||
(match (map-try-ref dirs path)
|
||||
((Some e) (score-at e (now)))
|
||||
(None 0)))
|
||||
|
||||
;; The store with a visit to `path` now.
|
||||
(: (-> (Map string DirEntry) string (Map string DirEntry)))
|
||||
(defun (dirs-visit dirs path)
|
||||
(def at (now))
|
||||
(def entry (match (map-try-ref dirs path)
|
||||
((Some e) (DirEntry (path path) (count (+ (record-ref e count) 1)) (last at)))
|
||||
(None (DirEntry (path path) (count 1) (last at)))))
|
||||
(def added (map-set dirs path entry))
|
||||
(if (<= (map-length added) dirs-size)
|
||||
added
|
||||
(let ((lowest (vec-ref (dirs-ranked added) (- (map-length added) 1))))
|
||||
(map-remove added (record-ref lowest path)))))
|
||||
|
||||
;; The entries, highest score first.
|
||||
(: (-> (Map string DirEntry) (Vec DirEntry)))
|
||||
(defun (dirs-ranked dirs)
|
||||
(def at (now))
|
||||
(def entries (map-fold (fun (_ e acc) (vec-add acc e)) [] dirs))
|
||||
(vec-sort-by (fun (a b) (- (score-at b at) (score-at a at))) entries))
|
||||
|
||||
;; The entries that match `keywords`, highest score first, leaving out
|
||||
;; `except` and directories that are gone.
|
||||
(: (-> (Map string DirEntry) (Vec string) string (Vec DirEntry)))
|
||||
(defun (dirs-match dirs keywords except)
|
||||
(vec-filter (fun (e)
|
||||
(def path (record-ref e path))
|
||||
(and (not (= path except))
|
||||
(keywords-match? (string-downcase path) (vec-map string-downcase keywords))
|
||||
(directory-exists? path)))
|
||||
(dirs-ranked dirs)))
|
||||
|
||||
;; Whether `path` has each of `keywords` in order, and the last in its last
|
||||
;; component.
|
||||
(: (-> string (Vec string) bool))
|
||||
(defun (keywords-match? path keywords)
|
||||
(def n (vec-length keywords))
|
||||
(and (> n 0)
|
||||
(let go ((i 0) (rest path))
|
||||
(cond
|
||||
((= i n) #t)
|
||||
(else
|
||||
(match (string-split-once rest (vec-ref keywords i))
|
||||
(None #f)
|
||||
((Some (Tuple _ after))
|
||||
(if (and (= i (- n 1)) (string-contains? after "/"))
|
||||
#f
|
||||
(go (+ i 1) after)))))))))
|
||||
|
||||
;; Reads the store from `file`. A missing file is an empty store.
|
||||
(: (-> string (Map string DirEntry)))
|
||||
(defun (dirs-load file)
|
||||
(vec-fold (fun (line dirs)
|
||||
(match (string-split line "\t")
|
||||
([count last path]
|
||||
(match (Tuple (string->int count) (string->long last))
|
||||
((Tuple (Some c) (Some l)) (map-set dirs path (DirEntry (path path) (count c) (last l))))
|
||||
(_ dirs)))
|
||||
(_ dirs)))
|
||||
(map-empty)
|
||||
(lines-load file)))
|
||||
|
||||
;; Writes the store to `file`. Errors are ignored: the store is a
|
||||
;; convenience.
|
||||
(: (-> (Map string DirEntry) string void))
|
||||
(defun (dirs-save dirs file)
|
||||
(lines-save (vec-map (fun (e) (str (int->string (record-ref e count)) "\t"
|
||||
(long->string (record-ref e last)) "\t"
|
||||
(record-ref e path)))
|
||||
(dirs-ranked dirs))
|
||||
file))
|
||||
|
||||
;; The lines of `file` that are not empty; none when it cannot be read.
|
||||
(: (-> string (Vec string)))
|
||||
(defun (lines-load file)
|
||||
(match (file-read-text file)
|
||||
((Ok text) (vec-filter (fun (l) (not (string-empty? l))) (string-split text "\n")))
|
||||
((Err _) [])))
|
||||
|
||||
;; Writes `lines` to `file`, making its directory. Errors are ignored.
|
||||
(: (-> (Vec string) string void))
|
||||
(defun (lines-save lines file)
|
||||
(ignore (try (directory-create (path-combine file "..")) #:catch (System.Exception)))
|
||||
(ignore (file-write-text file (string-join (vec-map (fun (l) (str l "\n")) lines) ""))))
|
||||
486
src/editor.bjo
486
src/editor.bjo
|
|
@ -5,21 +5,25 @@
|
|||
;; (bjosh editor): what the shell gives the line editor.
|
||||
;;
|
||||
;; - `input-done?`: whether Enter runs the input or starts a new line.
|
||||
;; - `complete`: the completer. The first word of a command completes from
|
||||
;; the shell commands and the programs on PATH; other words, and words
|
||||
;; with a /, from file names. Names are quoted with \ where the parser
|
||||
;; needs it. Directories end with /, everything else with a space.
|
||||
;; - `suggest`: the suggester, as fish's autosuggestions, for `cd` and
|
||||
;; paths. See `suggest`.
|
||||
;; - `complete`: the completer. See `complete`.
|
||||
;; - `suggest`: the suggester, as fish's autosuggestions. See `suggest`.
|
||||
;; - Names are quoted with \ where the parser needs it. Directories end
|
||||
;; with /, other names with a space.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std maths))
|
||||
(import (std run))
|
||||
(import (bjoterm line))
|
||||
(import (bjosh syntax))
|
||||
(import (bjosh api))
|
||||
(import (bjosh shell))
|
||||
(import (bjosh dirs))
|
||||
(import (bjosh builtins))
|
||||
(import (bjosh commands))
|
||||
|
||||
(export input-done? complete suggest word-start command-position? quote-name file-candidates)
|
||||
(export
|
||||
input-done? complete suggest word-start command-position? quote-name
|
||||
file-candidates path-candidates abbreviated-candidates command-line-at)
|
||||
|
||||
|
||||
;; Whether Enter runs `text`: #f while a quote is open, or the line ends
|
||||
|
|
@ -73,6 +77,10 @@
|
|||
(def parts (string-split (path->string/lossy p) "/"))
|
||||
(vec-ref parts (- (vec-length parts) 1)))
|
||||
|
||||
(: (-> (-> %a (Vec %b)) (Vec %a) (Vec %b)))
|
||||
(defun (vec-flat f v)
|
||||
(vec-fold (fun (x acc) (vec-append acc (f x))) [] v))
|
||||
|
||||
(: (-> string (Vec string)))
|
||||
(defun (path-names dir)
|
||||
(match (directory-files dir)
|
||||
|
|
@ -85,18 +93,189 @@
|
|||
((Ok paths) (vec-map base-name paths))
|
||||
((Err _) [])))
|
||||
|
||||
;; Programs on PATH and shell commands that start with `prefix`.
|
||||
;; ===========================================================================
|
||||
;; Names
|
||||
;; ===========================================================================
|
||||
|
||||
;; The entries of `dir` that start with `part`, each with whether it is a
|
||||
;; directory. With `fold?`, case is ignored. Hidden ones only for a `part`
|
||||
;; that starts with a dot.
|
||||
(: (-> string string bool (Vec (Tuple string bool))))
|
||||
(defun (entries-matching dir part fold?)
|
||||
(def p (if fold? (string-downcase part) part))
|
||||
(defun (wanted? n)
|
||||
(and (string-starts-with? (if fold? (string-downcase n) n) p)
|
||||
(or (string-starts-with? part ".") (not (string-starts-with? n ".")))))
|
||||
(vec-append (vec-map (fun (n) (Tuple n #t)) (vec-filter wanted? (directory-names dir)))
|
||||
(vec-map (fun (n) (Tuple n #f)) (vec-filter wanted? (path-names dir)))))
|
||||
|
||||
;; `n` quoted, with / after a directory and a space after a file.
|
||||
(: (-> (Tuple string bool) string))
|
||||
(defun (entry-text e)
|
||||
(def (Tuple n dir?) e)
|
||||
(str (quote-name n) (if dir? "/" " ")))
|
||||
|
||||
;; The files and directories that start with `word`, which can have a
|
||||
;; directory before it. With `fold?`, the last part ignores case.
|
||||
(: (-> string bool (Vec string)))
|
||||
(defun (path-candidates word fold?)
|
||||
(def parts (string-split word "/"))
|
||||
(def name-part (vec-ref parts (- (vec-length parts) 1)))
|
||||
(def dir-part (string-take word (- (string-length word) (string-length name-part))))
|
||||
(def dir (if (string-empty? dir-part) "." (expand-home (unquote-name dir-part))))
|
||||
(vec-sort (vec-map (fun (e) (str dir-part (entry-text e)))
|
||||
(entries-matching dir (unquote-name name-part) fold?))))
|
||||
|
||||
;; The files and directories that start with `word`.
|
||||
(: (-> string (Vec string)))
|
||||
(defun (command-candidates prefix)
|
||||
(defun (file-candidates word)
|
||||
(path-candidates word #f))
|
||||
|
||||
;; `word` with each part taken as the start of a name, as ~/P/B/B for
|
||||
;; ~/Programmering/Bjolang/Bjolang. A part matches with case, or without
|
||||
;; when nothing does. At most 50.
|
||||
(: (-> string (Vec string)))
|
||||
(defun (abbreviated-candidates word)
|
||||
(def parts (string-split word "/"))
|
||||
(def n (vec-length parts))
|
||||
(def root (vec-ref parts 0))
|
||||
(def start (cond
|
||||
((string-empty? root) (Some (Tuple "/" "/")))
|
||||
((= root "~") (Some (Tuple "~/" (expand-home "~"))))
|
||||
(else None)))
|
||||
(defun (matching dir part)
|
||||
(def exact (entries-matching dir part #f))
|
||||
(if (vec-empty? exact) (entries-matching dir part #t) exact))
|
||||
(if (< n 2)
|
||||
[]
|
||||
(let go ((i (if (some? start) 1 0))
|
||||
(at (match start ((Some s) [s]) (None [(Tuple "" ".")]))))
|
||||
(def part (unquote-name (vec-ref parts i)))
|
||||
(cond
|
||||
((> (vec-length at) 50) [])
|
||||
((= i (- n 1))
|
||||
(vec-sort (vec-flat (fun (t)
|
||||
(def (Tuple shown dir) t)
|
||||
(vec-map (fun (e) (str shown (entry-text e))) (matching dir part)))
|
||||
at)))
|
||||
((vec-contains? ["" "." ".."] part)
|
||||
(go (+ i 1) (vec-map (fun (t) (Tuple (str (fst t) part "/") (path-combine (snd t) part))) at)))
|
||||
(else
|
||||
(go (+ i 1)
|
||||
(vec-flat (fun (t)
|
||||
(def (Tuple shown dir) t)
|
||||
(vec-map (fun (e) (Tuple (str shown (quote-name (fst e)) "/") (path-combine dir (fst e))))
|
||||
(vec-filter snd (matching dir part))))
|
||||
at)))))))
|
||||
|
||||
;; The candidates for a path: those that start with `word`, else those
|
||||
;; that do ignoring case, else `abbreviated-candidates`.
|
||||
(: (-> string (Vec string)))
|
||||
(defun (paths-for word)
|
||||
(def exact (path-candidates word #f))
|
||||
(cond
|
||||
((not (vec-empty? exact)) exact)
|
||||
(else
|
||||
(def folded (path-candidates word #t))
|
||||
(if (vec-empty? folded) (abbreviated-candidates word) folded))))
|
||||
|
||||
;; `path` with ~ for home, quoted.
|
||||
(: (-> string string))
|
||||
(defun (shown-path path)
|
||||
(def home (match (getenv "HOME") ((Some h) h) (None "")))
|
||||
(if (and (not (string-empty? home)) (string-starts-with? path (str home "/")))
|
||||
(str "~/" (quote-name (string-drop path (+ (string-length home) 1))))
|
||||
(quote-name path)))
|
||||
|
||||
;; Whether `word` is written as a path: it has a / or starts with ~.
|
||||
(: (-> string bool))
|
||||
(defun (path-like? word)
|
||||
(or (string-contains? word "/") (string-starts-with? word "~")))
|
||||
|
||||
;; ===========================================================================
|
||||
;; Completion
|
||||
;; ===========================================================================
|
||||
|
||||
;; The completer: the candidates for the word before the cursor.
|
||||
;; - $NAME: shell and environment variables.
|
||||
;; - The first word of a command: shell commands, the user's commands,
|
||||
;; aliases and programs on PATH, with their help.
|
||||
;; - After `cd`: directories, else visited directories that match (see
|
||||
;; `dirs-match`).
|
||||
;; - A word with a / or ~: paths.
|
||||
;; - Another word: fish's completions for the command, with their
|
||||
;; descriptions, when fish is on PATH; else paths.
|
||||
;; - Paths: those that start with the word, else ignoring case, else with
|
||||
;; each part as the start of a name (see `abbreviated-candidates`).
|
||||
(: (-> Shell string Completion))
|
||||
(defun (complete sh text)
|
||||
(def start (word-start text))
|
||||
(def word (string-drop text start))
|
||||
(defun (plain candidates)
|
||||
(Completion (prefix word) (candidates candidates) (descriptions [])))
|
||||
(cond
|
||||
((string-starts-with? word "$")
|
||||
(plain (vec-map (fun (n) (str "$" n " "))
|
||||
(vec-filter (fun (n) (string-starts-with? n (string-drop word 1))) (var-names sh)))))
|
||||
((and (command-position? text start) (not (path-like? word))) (command-completion sh word))
|
||||
((cd-line? text start) (plain (cd-candidates sh word)))
|
||||
((path-like? word) (plain (paths-for word)))
|
||||
(else
|
||||
(match (fish-completion sh text word)
|
||||
((Some c) c)
|
||||
(None (plain (paths-for word)))))))
|
||||
|
||||
;; The directories for `cd WORD`; else visited directories that match.
|
||||
(: (-> Shell string (Vec string)))
|
||||
(defun (cd-candidates sh word)
|
||||
(def dirs (vec-filter (fun (c) (string-ends-with? c "/")) (paths-for word)))
|
||||
(if (or (not (vec-empty? dirs)) (not (jump-keyword? word)))
|
||||
dirs
|
||||
(vec-map (fun (e) (str (shown-path (record-ref e path)) "/"))
|
||||
(dirs-match (record-ref sh dirs) [(unquote-name word)] (current-directory)))))
|
||||
|
||||
;; Whether `word` can name a visited directory to jump to: not empty, and
|
||||
;; not a path, an option or -.
|
||||
(: (-> string bool))
|
||||
(defun (jump-keyword? word)
|
||||
(and (not (string-empty? word))
|
||||
(not (path-like? word))
|
||||
(not (string-starts-with? word "."))
|
||||
(not (string-starts-with? word "-"))))
|
||||
|
||||
;; Commands that start with `word`, with their help: shell commands, the
|
||||
;; user's commands, aliases and programs on PATH.
|
||||
(: (-> Shell string Completion))
|
||||
(defun (command-completion sh word)
|
||||
(def ext (record-ref sh extension))
|
||||
(def help
|
||||
(vec-append
|
||||
(vec-append (vec-map (fun (n) (Tuple n (builtin-help n))) builtin-names)
|
||||
(vec-flat (fun (c) [(Tuple (record-ref c short) (record-ref c help))
|
||||
(Tuple (record-ref c long) (record-ref c help))])
|
||||
(vec-append (value-commands) (record-ref ext commands))))
|
||||
(vec-append (vec-map (fun (c) (Tuple (record-ref c name) (record-ref c help))) (record-ref ext shell-commands))
|
||||
(map-fold (fun (k v acc) (vec-add acc (Tuple k (str "alias for " v)))) [] (record-ref sh aliases)))))
|
||||
(def programs (path-programs))
|
||||
(defun (described name)
|
||||
(match (find (fun (t) (= (fst t) name)) help)
|
||||
((Some (Tuple _ h)) h)
|
||||
(None "")))
|
||||
(defun (starting fold?)
|
||||
(def w (if fold? (string-downcase word) word))
|
||||
(sorted-distinct (vec-filter (fun (n) (string-starts-with? (if fold? (string-downcase n) n) w))
|
||||
(vec-append (vec-map fst help) programs))))
|
||||
(def exact (starting #f))
|
||||
(def names (if (vec-empty? exact) (starting #t) exact))
|
||||
(Completion (prefix word)
|
||||
(candidates (vec-map (fun (n) (str (quote-name n) " ")) names))
|
||||
(descriptions (vec-map described names))))
|
||||
|
||||
;; The programs on PATH.
|
||||
(: (-> (Vec string)))
|
||||
(defun (path-programs)
|
||||
(def dirs (match (getenv "PATH") ((Some p) (string-split p ":")) (None [])))
|
||||
(def programs
|
||||
(let go ((i 0) (all []))
|
||||
(if (= i (vec-length dirs))
|
||||
all
|
||||
(go (+ i 1) (vec-append all (path-names (vec-ref dirs i)))))))
|
||||
(vec-map (fun (n) (str (quote-name n) " "))
|
||||
(sorted-distinct (vec-filter (fun (n) (string-starts-with? n prefix))
|
||||
(vec-append (vec-append builtin-names (value-names)) programs)))))
|
||||
(vec-flat path-names dirs))
|
||||
|
||||
;; `names` sorted, each once.
|
||||
(: (-> (Vec string) (Vec string)))
|
||||
|
|
@ -108,83 +287,238 @@
|
|||
((and (> i 0) (= (vec-ref sorted i) (vec-ref sorted (- i 1)))) (go (+ i 1) out))
|
||||
(else (go (+ i 1) (vec-add out (vec-ref sorted i)))))))
|
||||
|
||||
;; Files and directories that start with `word`, which can have a
|
||||
;; directory before it. Directories end with /, files with a space.
|
||||
(: (-> string (Vec string)))
|
||||
(defun (file-candidates word)
|
||||
(def parts (string-split word "/"))
|
||||
(def name-part (vec-ref parts (- (vec-length parts) 1)))
|
||||
(def dir-part (string-take word (- (string-length word) (string-length name-part))))
|
||||
(def dir (cond
|
||||
((string-empty? dir-part) ".")
|
||||
((string-starts-with? dir-part "~/")
|
||||
(str (match (getenv "HOME") ((Some h) h) (None "~")) (string-drop dir-part 1)))
|
||||
(else dir-part)))
|
||||
(defun (wanted? n)
|
||||
(and (string-starts-with? n name-part)
|
||||
(or (string-starts-with? name-part ".") (not (string-starts-with? n ".")))))
|
||||
(vec-sort
|
||||
(vec-append (vec-map (fun (n) (str dir-part (quote-name n) "/"))
|
||||
(vec-filter wanted? (directory-names dir)))
|
||||
(vec-map (fun (n) (str dir-part (quote-name n) " "))
|
||||
(vec-filter wanted? (path-names dir))))))
|
||||
;; The command that the end of `text` is in: the text after the last |, ;,
|
||||
;; & or ( outside quotes, without leading spaces.
|
||||
(: (-> string string))
|
||||
(defun (command-line-at text)
|
||||
(def chars (string->vec text))
|
||||
(def n (vec-length chars))
|
||||
(let go ((i 0) (quote None) (after 0))
|
||||
(cond
|
||||
((= i n) (string-trim-left (string-drop text after)))
|
||||
(else
|
||||
(def c (vec-ref chars i))
|
||||
(match quote
|
||||
((Some q) (go (+ i 1) (if (= c q) None quote) after))
|
||||
(None
|
||||
(cond
|
||||
((= c #\\) (go (+ i 2) None after))
|
||||
((or (= c #\') (= c #\")) (go (+ i 1) (Some c) after))
|
||||
((string-contains? "|;&(" (char->string c)) (go (+ i 1) None (+ i 1)))
|
||||
(else (go (+ i 1) None after)))))))))
|
||||
|
||||
(: (-> string Completion))
|
||||
(defun (complete text)
|
||||
(def start (word-start text))
|
||||
(def word (string-drop text start))
|
||||
(Completion (prefix word)
|
||||
(candidates (if (and (command-position? text start) (not (string-contains? word "/")))
|
||||
(command-candidates word)
|
||||
(file-candidates word)))))
|
||||
;; `line` with its first word replaced by its alias.
|
||||
(: (-> Shell string string))
|
||||
(defun (with-alias sh line)
|
||||
(match (string-split-once line " ")
|
||||
((Some (Tuple name rest))
|
||||
(match (alias-ref sh name)
|
||||
((Some text) (str text " " rest))
|
||||
(None line)))
|
||||
(None line)))
|
||||
|
||||
;; fish's completions of the command at the end of `text`, for `word`.
|
||||
;; None when fish is not on PATH, fails, takes more than 2 seconds, or
|
||||
;; has none. The line goes to fish as an argument, not as code.
|
||||
(: (-> Shell string string (Option Completion)))
|
||||
(defun (fish-completion sh text word)
|
||||
(match (find-program "fish")
|
||||
(None None)
|
||||
((Some fish)
|
||||
(def line (with-alias sh (command-line-at text)))
|
||||
(def argv (vec-append (match (find-program "timeout") ((Some t) [t "2"]) (None []))
|
||||
[fish "--no-config" "-c" "complete --do-complete=$argv[1]" "--" line]))
|
||||
(match (run/strings '(errors-into-file "/dev/null" ,argv))
|
||||
((Ok lines)
|
||||
(def found (vec-map (fun (l) (match (string-split-once l "\t")
|
||||
((Some (Tuple c d)) (Tuple c d))
|
||||
(None (Tuple l ""))))
|
||||
(vec-filter (fun (l) (not (string-empty? l))) lines)))
|
||||
(if (vec-empty? found)
|
||||
None
|
||||
(Some (Completion (prefix word)
|
||||
(candidates (vec-map (fun (t) (fish-candidate (fst t))) found))
|
||||
(descriptions (vec-map snd found))))))
|
||||
((Err _) None)))))
|
||||
|
||||
;; A candidate from fish: quoted, with a space after it unless it ends
|
||||
;; with / or =.
|
||||
(: (-> string string))
|
||||
(defun (fish-candidate c)
|
||||
(cond
|
||||
((string-ends-with? c "/") (str (quote-name (string-drop-right c 1)) "/"))
|
||||
((string-ends-with? c "=") c)
|
||||
((string-starts-with? c "~/") (str "~/" (quote-name (string-drop c 2)) " "))
|
||||
(else (str (quote-name c) " "))))
|
||||
|
||||
;; ===========================================================================
|
||||
;; Suggestions
|
||||
;; ===========================================================================
|
||||
|
||||
;; The text to show after `text`, for `#:suggester`. Only for one line.
|
||||
;; - `cd WORD`: the newest `cd` line in `history` that starts with `text`
|
||||
;; and whose directory exists from here; else the directories that start
|
||||
;; with WORD.
|
||||
;; - Another argument: the files and directories that start with it.
|
||||
;; - From names: the rest of the only one, or of their common prefix.
|
||||
;; A file gets no space after it.
|
||||
(: (-> string (Vec string) (Option string)))
|
||||
(defun (suggest text history)
|
||||
;; The suggester: what to show after `text`, as fish's autosuggestions.
|
||||
;; Only for one line that is not empty.
|
||||
;; 1. A line of `history` that starts with `text`, is longer, and runs a
|
||||
;; command that exists. For `cd`, its directory must exist, and the
|
||||
;; line whose directory has the highest frecency wins; else the newest.
|
||||
;; Then the same ignoring case, newest first.
|
||||
;; 2. After `cd`: the directories that start with the word, else ignoring
|
||||
;; case, else the visited directory that the words match, shown as
|
||||
;; "-> DIR" (see `dirs-match`).
|
||||
;; 3. Another argument: the files and directories that start with it,
|
||||
;; else ignoring case.
|
||||
;; From names: the rest of the only one, or of their common prefix. A file
|
||||
;; gets no space after it. A match ignoring case must be the only one, and
|
||||
;; accepting it replaces the word.
|
||||
(: (-> Shell string (Vec string) (Option Suggestion)))
|
||||
(defun (suggest sh text history)
|
||||
(def start (word-start text))
|
||||
(def word (string-drop text start))
|
||||
(cond
|
||||
((string-contains? text "\n") None)
|
||||
((cd-line? text start)
|
||||
(match (cd-from-history text history)
|
||||
((Some rest) (Some rest))
|
||||
(None (extension word (vec-filter (fun (c) (string-ends-with? c "/")) (file-candidates word))))))
|
||||
((command-position? text start) None)
|
||||
((string-empty? word) None)
|
||||
(else (extension word (file-candidates word)))))
|
||||
((string-empty? (string-trim text)) None)
|
||||
(else
|
||||
(match (history-suggestion sh text history)
|
||||
((Some s) (Some s))
|
||||
(None
|
||||
(cond
|
||||
((cd-line? text start) (cd-suggestion sh text start word))
|
||||
((jump-line? text) (jump-suggestion sh text))
|
||||
((command-position? text start) None)
|
||||
((string-empty? word) None)
|
||||
(else (names-suggestion text start word (fun (c) #t)))))))))
|
||||
|
||||
;; Whether `text` is `cd` and the word from `start`.
|
||||
(: (-> string int bool))
|
||||
(defun (cd-line? text start)
|
||||
(= (string-trim (string-take text start)) "cd"))
|
||||
|
||||
;; The rest of the newest `cd DIR` line in `history` that starts with
|
||||
;; `text`, is longer, and names a directory that exists.
|
||||
(: (-> string (Vec string) (Option string)))
|
||||
(defun (cd-from-history text history)
|
||||
(let go ((i (- (vec-length history) 1)))
|
||||
;; Whether `text` is `cd` and more than one word.
|
||||
(: (-> string bool))
|
||||
(defun (jump-line? text)
|
||||
(and (string-starts-with? text "cd ")
|
||||
(> (vec-length (line-words text)) 2)))
|
||||
|
||||
(: (-> string (Vec string)))
|
||||
(defun (line-words text)
|
||||
(vec-filter (fun (w) (not (string-empty? w))) (string-split text " ")))
|
||||
|
||||
;; From the candidates for `word` that `keep?` takes: the rest of the only
|
||||
;; one or of their common prefix; else the only one that matches ignoring
|
||||
;; case, replacing the word.
|
||||
(: (-> string int string (-> string bool) (Option Suggestion)))
|
||||
(defun (names-suggestion text start word keep?)
|
||||
(match (extension word (vec-filter keep? (file-candidates word)))
|
||||
((Some rest) (Some (suggestion-after text rest)))
|
||||
(None
|
||||
(match (vec-filter keep? (path-candidates word #t))
|
||||
([only]
|
||||
(def name (string-trim-right only))
|
||||
(if (> (string-length name) (string-length word))
|
||||
(Some (Suggestion (ghost (string-drop name (string-length word)))
|
||||
(line (str (string-take text start) name))))
|
||||
None))
|
||||
(_ None)))))
|
||||
|
||||
(: (-> Shell string int string (Option Suggestion)))
|
||||
(defun (cd-suggestion sh text start word)
|
||||
(match (names-suggestion text start word (fun (c) (string-ends-with? c "/")))
|
||||
((Some s) (Some s))
|
||||
(None (jump-suggestion sh text))))
|
||||
|
||||
;; For `cd KEYWORD...` that names no directory: the visited directory that
|
||||
;; the keywords match, shown as " -> DIR".
|
||||
(: (-> Shell string (Option Suggestion)))
|
||||
(defun (jump-suggestion sh text)
|
||||
(def words (vec-drop (line-words text) 1))
|
||||
(if (or (vec-empty? words)
|
||||
(not (all? jump-keyword? words))
|
||||
(directory-exists? (unquote-name (vec-ref words 0))))
|
||||
None
|
||||
(match (dirs-match (record-ref sh dirs) (vec-map unquote-name words) (current-directory))
|
||||
([] None)
|
||||
(found
|
||||
(def path (shown-path (record-ref (vec-ref found 0) path)))
|
||||
(Some (Suggestion (ghost (str " \u{2192} " path)) (line (str "cd " path))))))))
|
||||
|
||||
;; The suggestion from `history`. See `suggest`.
|
||||
(: (-> Shell string (Vec string) (Option Suggestion)))
|
||||
(defun (history-suggestion sh text history)
|
||||
(def cd? (string-starts-with? text "cd "))
|
||||
(defun (candidates fold?)
|
||||
(def t (if fold? (string-downcase text) text))
|
||||
(let go ((i (- (vec-length history) 1)) (out []))
|
||||
(cond
|
||||
((< i 0) out)
|
||||
(else
|
||||
(def entry (vec-ref history i))
|
||||
(go (- i 1)
|
||||
(if (and (> (string-length entry) (string-length text))
|
||||
(string-starts-with? (if fold? (string-downcase entry) entry) t)
|
||||
(= (string-length (string-downcase entry)) (string-length entry))
|
||||
(not (vec-contains? out entry))
|
||||
(runnable? sh entry))
|
||||
(vec-add out entry)
|
||||
out))))))
|
||||
(defun (best entries)
|
||||
(cond
|
||||
((< i 0) None)
|
||||
((vec-empty? entries) None)
|
||||
((not cd?) (Some (vec-ref entries 0)))
|
||||
(else
|
||||
(def entry (vec-ref history i))
|
||||
(def start (word-start entry))
|
||||
(if (and (> (string-length entry) (string-length text))
|
||||
(string-starts-with? entry text)
|
||||
(not (string-contains? entry "\n"))
|
||||
(cd-line? entry start)
|
||||
(directory-exists? (expand-home (unquote-name (string-drop entry start)))))
|
||||
(Some (string-drop entry (string-length text)))
|
||||
(go (- i 1)))))))
|
||||
(Some (vec-fold (fun (e acc)
|
||||
(if (> (cd-score sh e) (cd-score sh acc)) e acc))
|
||||
(vec-ref entries 0)
|
||||
entries)))))
|
||||
(match (best (candidates #f))
|
||||
((Some e) (Some (suggestion-after text (string-drop e (string-length text)))))
|
||||
(None
|
||||
(match (candidates #t)
|
||||
([] None)
|
||||
(found
|
||||
(def e (vec-ref found 0))
|
||||
(Some (Suggestion (ghost (string-drop e (string-length text))) (line e))))))))
|
||||
|
||||
;; The frecency of the directory of a `cd DIR` line.
|
||||
(: (-> Shell string int))
|
||||
(defun (cd-score sh line)
|
||||
(match (try (path-absolute (expand-home (unquote-name (string-trim (string-drop line 3)))))
|
||||
#:catch (System.Exception))
|
||||
((Ok path) (dirs-score (record-ref sh dirs)
|
||||
(if (and (> (string-length path) 1) (string-ends-with? path "/"))
|
||||
(string-drop-right path 1)
|
||||
path)))
|
||||
((Err _) 0)))
|
||||
|
||||
;; Whether a history line can run: one line, whose first command exists.
|
||||
;; A `cd` line must name a directory that exists.
|
||||
(: (-> Shell string bool))
|
||||
(defun (runnable? sh entry)
|
||||
(def words (line-words entry))
|
||||
(cond
|
||||
((string-contains? entry "\n") #f)
|
||||
((vec-empty? words) #f)
|
||||
((= (vec-ref words 0) "cd")
|
||||
(or (= (vec-length words) 1)
|
||||
(and (= (vec-length words) 2)
|
||||
(directory-exists? (expand-home (unquote-name (vec-ref words 1)))))))
|
||||
(else (command-exists? sh (vec-ref words 0)))))
|
||||
|
||||
;; Whether `name` is a command: an assignment, a shell command, an alias,
|
||||
;; a user command, a value command or a program.
|
||||
(: (-> Shell string bool))
|
||||
(defun (command-exists? sh name)
|
||||
(or (string-contains? name "=")
|
||||
(not (char-alphabetic-or-path? name))
|
||||
(builtin? name)
|
||||
(some? (alias-ref sh name))
|
||||
(some? (user-shell-command sh name))
|
||||
(some? (user-value-command sh name (fun (_) #f)))
|
||||
(vec-contains? (value-names) name)
|
||||
(some? (find-program (expand-home (unquote-name name))))))
|
||||
|
||||
;; Whether `name` starts like a command name, not like syntax such as (.
|
||||
(: (-> string bool))
|
||||
(defun (char-alphabetic-or-path? name)
|
||||
(not (string-contains? "({!$" (string-take name 1))))
|
||||
|
||||
;; What `word` can be extended by from `candidates`: the rest of the only
|
||||
;; one, or of their common prefix. A trailing space is left out.
|
||||
|
|
|
|||
30
src/main.bjo
30
src/main.bjo
|
|
@ -25,9 +25,14 @@
|
|||
;; turns this off.
|
||||
;; - The prompt is $PROMPT when it is set (see `custom-prompt`), else the
|
||||
;; user's prompt function, else the directory and $.
|
||||
;; - The line editor suggests `cd` directories and paths as fish does (see
|
||||
;; `suggest`). On an empty line, Alt-Left and Alt-Right go back and
|
||||
;; forward in the directory history, as `prevd` and `nextd`.
|
||||
;; - The line editor suggests lines from the history, directories and paths
|
||||
;; as fish does (see `suggest`), and Tab completes with fish's
|
||||
;; completions when fish is on PATH (see `complete`).
|
||||
;; - An interactive shell keeps the directories it visits, ranked by
|
||||
;; frecency, and its directory history, in $XDG_STATE_HOME/bjosh (see
|
||||
;; (bjosh dirs)). `cd KEYWORD...` goes to the best match.
|
||||
;; - On an empty line, Alt-Left and Alt-Right go back and forward in the
|
||||
;; directory history, as `prevd` and `nextd`.
|
||||
|
||||
(import (std prelude))
|
||||
(import (std run))
|
||||
|
|
@ -182,13 +187,25 @@
|
|||
(def jc (match (job-control)
|
||||
((Ok jc) (Some jc))
|
||||
((Err _) (shell-error "no job control: & and Ctrl-Z do not work") None)))
|
||||
(def ed (make-line-editor #:completer (Some complete) #:input-done? (Some input-done?)
|
||||
#:suggester (Some suggest) #:command-key? (Some directory-key?)
|
||||
#:suspend? #f))
|
||||
;; The editor is made before the shell, which holds it.
|
||||
(def current (make-box None))
|
||||
(def ed (make-line-editor
|
||||
#:completer (Some (fun (text)
|
||||
(match (box-ref current)
|
||||
((Some sh) (complete sh text))
|
||||
(None (Completion (prefix "") (candidates []) (descriptions []))))))
|
||||
#:input-done? (Some input-done?)
|
||||
#:suggester (Some (fun (text history)
|
||||
(match (box-ref current)
|
||||
((Some sh) (suggest sh text history))
|
||||
(None None))))
|
||||
#:command-key? (Some directory-key?)
|
||||
#:suspend? #f))
|
||||
(def path (history-path))
|
||||
(ignore (line-history-load! ed path))
|
||||
(ignore (try (directory-create (path-combine path "..")) #:catch (System.Exception)))
|
||||
(def sh (make-shell jc (Some ed) ["bjosh"]))
|
||||
(box-set! current (Some sh))
|
||||
(def rc (rc-path))
|
||||
(when (file-exists? rc)
|
||||
(match (file-read-text rc)
|
||||
|
|
@ -196,6 +213,7 @@
|
|||
((Err e) (shell-error (str rc ": " (fs-error-message e))))))
|
||||
(set-up-commands)
|
||||
(ignore (with-extension sh))
|
||||
(dirs-persist! sh)
|
||||
(let go ()
|
||||
(report-jobs sh)
|
||||
(match (line-read ed term (prompt sh) #:notices (Some (fun () (job-changes sh))))
|
||||
|
|
|
|||
|
|
@ -22,12 +22,14 @@
|
|||
(import (bjosh syntax))
|
||||
(import (bjosh expand))
|
||||
(import (bjosh api))
|
||||
(import (bjosh dirs))
|
||||
|
||||
(export
|
||||
Shell JobEntry make-shell subshell shell-error
|
||||
alias-ref alias-set! alias-remove! set-subst-status! set-extension! prompt-failed!
|
||||
user-value-command user-shell-command
|
||||
set-status! request-exit! warn-stopped! var-export! dir-visited! dir-set-history!
|
||||
dir-arrived! dirs-persist! var-names
|
||||
var-ref var-set! var-unset! shell-expander job-set-state!
|
||||
job-add! job-remove! job-find job-current job-mark-recent! jobs-stopped?
|
||||
job-text-line job-mark job-state-text foreground! report-jobs job-changes state->status error-text)
|
||||
|
|
@ -55,6 +57,9 @@
|
|||
;; - `dir-back` and `dir-forward`: the directory history, newest last.
|
||||
;; `cd` adds to `dir-back` and empties `dir-forward`; `prevd` and `nextd`
|
||||
;; move between them.
|
||||
;; - `dirs`: the frecency store of (bjosh dirs). Read from the state file
|
||||
;; by every shell; written, with `dir-back`, only when `persist?`, by an
|
||||
;; interactive shell.
|
||||
(type (: Shell (Record (: vars (Map string string) #:mutable)
|
||||
(: status int #:mutable)
|
||||
(: jc (Option JobControl))
|
||||
|
|
@ -70,7 +75,9 @@
|
|||
(: extension Extension #:mutable)
|
||||
(: prompt-failed? bool #:mutable)
|
||||
(: dir-back (Vec string) #:mutable)
|
||||
(: dir-forward (Vec string) #:mutable))))
|
||||
(: dir-forward (Vec string) #:mutable)
|
||||
(: dirs (Map string DirEntry) #:mutable)
|
||||
(: persist? bool #:mutable))))
|
||||
|
||||
(import/extern
|
||||
(pid (: System.Environment.ProcessId int #:get #:no-raise)))
|
||||
|
|
@ -80,7 +87,8 @@
|
|||
(Shell (vars (map-empty)) (status 0) (jc jc) (editor editor) (args args)
|
||||
(jobs []) (recent []) (exit-code None) (warned-stopped? #f)
|
||||
(aliases (map-empty)) (capture? #f) (subst-status None)
|
||||
(extension no-extension) (prompt-failed? #f) (dir-back []) (dir-forward [])))
|
||||
(extension no-extension) (prompt-failed? #f) (dir-back []) (dir-forward [])
|
||||
(dirs (dirs-load (state-path "dirs"))) (persist? #f)))
|
||||
|
||||
;; A copy of `sh` for $(...): the same variables, aliases and status, which
|
||||
;; it can change for itself, and no jobs or job control.
|
||||
|
|
@ -91,7 +99,8 @@
|
|||
(jobs []) (recent []) (exit-code None) (warned-stopped? #f)
|
||||
(aliases (record-ref sh aliases)) (capture? #t) (subst-status None)
|
||||
(extension (record-ref sh extension)) (prompt-failed? (record-ref sh prompt-failed?))
|
||||
(dir-back (record-ref sh dir-back)) (dir-forward (record-ref sh dir-forward))))
|
||||
(dir-back (record-ref sh dir-back)) (dir-forward (record-ref sh dir-forward))
|
||||
(dirs (record-ref sh dirs)) (persist? #f)))
|
||||
|
||||
(: (-> Shell (Option int) void))
|
||||
(defun (set-subst-status! sh status) (record-set! sh (subst-status status)))
|
||||
|
|
@ -112,6 +121,23 @@
|
|||
(defun (dir-set-history! sh back forward)
|
||||
(record-set! sh (dir-back back) (dir-forward forward)))
|
||||
|
||||
;; Records a visit to the current directory in the frecency store. When
|
||||
;; `persist?`, adds it to the saved store, which other shells write too,
|
||||
;; and saves that and the directory history.
|
||||
(: (-> Shell void))
|
||||
(defun (dir-arrived! sh)
|
||||
(def base (if (record-ref sh persist?) (dirs-load (state-path "dirs")) (record-ref sh dirs)))
|
||||
(record-set! sh (dirs (dirs-visit base (current-directory))))
|
||||
(when (record-ref sh persist?)
|
||||
(dirs-save (record-ref sh dirs) (state-path "dirs"))
|
||||
(lines-save (record-ref sh dir-back) (state-path "dir-history"))))
|
||||
|
||||
;; Makes `sh` save its frecency store and directory history, and reads the
|
||||
;; directory history saved before.
|
||||
(: (-> Shell void))
|
||||
(defun (dirs-persist! sh)
|
||||
(record-set! sh (persist? #t) (dir-back (lines-load (state-path "dir-history")))))
|
||||
|
||||
(: (-> Shell Extension void))
|
||||
(defun (set-extension! sh ext)
|
||||
(record-set! sh (extension ext) (prompt-failed? #f)))
|
||||
|
|
@ -200,6 +226,20 @@
|
|||
((Some v) (Some v))
|
||||
(None (getenv name))))))
|
||||
|
||||
;; The names of the shell variables and of the environment the shell
|
||||
;; started with, sorted. From /proc/self/environ: .NET cannot list the
|
||||
;; environment.
|
||||
(: (-> Shell (Vec string)))
|
||||
(defun (var-names sh)
|
||||
(def env (match (file-read-text "/proc/self/environ")
|
||||
((Ok text) (vec-map (fun (entry) (match (string-split-once entry "=")
|
||||
((Some (Tuple name _)) name)
|
||||
(None entry)))
|
||||
(vec-filter (fun (e) (not (string-empty? e))) (string-split text "\u{0}"))))
|
||||
((Err _) [])))
|
||||
(def shell (map-fold (fun (k _ acc) (vec-add acc k)) [] (record-ref sh vars)))
|
||||
(vec-sort (vec-append env shell)))
|
||||
|
||||
;; Sets `name`: in the environment when it is there, else as a shell
|
||||
;; variable.
|
||||
(: (-> Shell string string void))
|
||||
|
|
|
|||
|
|
@ -10,6 +10,9 @@
|
|||
(import (std simpletest))
|
||||
(import (bjoterm line))
|
||||
(import (bjosh editor))
|
||||
(import (bjosh shell))
|
||||
(import (bjosh dirs))
|
||||
(import (bjosh builtins))
|
||||
|
||||
(import/extern
|
||||
(temp-dir (: System.IO.Path.GetTempPath (-> string)))
|
||||
|
|
@ -47,29 +50,78 @@
|
|||
(expect "not hidden files" (file-candidates "") ["a\\ b " "abc.txt " "abd/"])
|
||||
(expect "hidden files for a dot" (file-candidates ".h") [".hidden "])
|
||||
(expect "in a directory" (file-candidates "abd/i") ["abd/inner "])
|
||||
(expect "the second word completes files" (record-ref (complete "cat ab") candidates) ["abc.txt " "abd/"])
|
||||
(expect "the first word completes commands"
|
||||
(any? (fun (c) (= c "jobs ")) (record-ref (complete "jo") candidates)) #t)
|
||||
(expect "a first word with a / completes files" (record-ref (complete "./ab") candidates)
|
||||
["./abc.txt " "./abd/"])
|
||||
(set-environment-variable! "XDG_STATE_HOME" (path-combine dir "state"))
|
||||
(def sh (make-shell None None ["bjosh"]))
|
||||
(defun (cands text) (record-ref (complete sh text) candidates))
|
||||
;; The ghost and the line of a suggestion.
|
||||
(defun (sg text history)
|
||||
(match (suggest sh text history)
|
||||
((Some s) (Some (Tuple (record-ref s ghost) (record-ref s line))))
|
||||
(None None)))
|
||||
(defun (g text history)
|
||||
(match (sg text history) ((Some t) (Some (fst t))) (None None)))
|
||||
|
||||
;; Completion.
|
||||
(expect "the second word completes files" (cands "cat ab") ["abc.txt " "abd/"])
|
||||
(expect "the first word completes commands" (any? (fun (c) (= c "jobs ")) (cands "jo")) #t)
|
||||
(expect "with their help"
|
||||
(let ((c (complete sh "prevd")))
|
||||
(Tuple (record-ref c candidates) (record-ref c descriptions)))
|
||||
(Tuple ["prevd "] ["go back in the directory history; also Alt-Left"]))
|
||||
(expect "a first word with a / completes files" (cands "./ab") ["./abc.txt " "./abd/"])
|
||||
(expect "a path ignoring case when nothing else matches" (cands "./ABC") ["./abc.txt "])
|
||||
(expect "each part as the start of a name" (cands "ls ./a/in") ["./abd/inner "])
|
||||
(expect "abbreviated" (abbreviated-candidates "a/i") ["abd/inner "])
|
||||
(expect "variables" (vec-contains? (cands "echo $HOM") "$HOME ") #t)
|
||||
(expect "the command at the end" (command-line-at "ls | git ch") "git ch")
|
||||
(expect "not inside quotes" (command-line-at "echo 'a|b' x") "echo 'a|b' x")
|
||||
(expect "after &&" (command-line-at "make && ./run -") "./run -")
|
||||
(when (some? (find-program "fish"))
|
||||
(expect "fish's completions, with descriptions"
|
||||
(let ((c (complete sh "systemctl sta")))
|
||||
(Tuple (vec-contains? (record-ref c candidates) "start ")
|
||||
(any? (fun (d) (not (string-empty? d))) (record-ref c descriptions))))
|
||||
(Tuple #t #t)))
|
||||
|
||||
;; Suggestions.
|
||||
(ignore (directory-create (path-combine dir "abd/deeper")))
|
||||
(ignore (directory-create (path-combine dir "other")))
|
||||
(expect "cd suggests the only directory" (suggest "cd ot" []) (Some "her/"))
|
||||
(expect "and not files" (suggest "cd abc" []) None)
|
||||
(expect "the common prefix of several" (suggest "cd abd/" []) (Some "deeper/"))
|
||||
(expect "a path argument suggests files, with no space" (suggest "cat abc" []) (Some ".txt"))
|
||||
(expect "several files, their common prefix" (suggest "cat a" []) None)
|
||||
(expect "in a directory" (suggest "cat abd/in" []) (Some "ner"))
|
||||
(expect "not the command" (suggest "ab" []) None)
|
||||
(expect "not an empty argument" (suggest "cat " []) None)
|
||||
(expect "not a second line" (suggest "echo 'a\ncat abc" []) None)
|
||||
(ignore (directory-create (path-combine dir "Mixed")))
|
||||
(expect "cd suggests the only directory" (g "cd ot" []) (Some "her/"))
|
||||
(expect "and not files" (g "cd abc" []) None)
|
||||
(expect "the common prefix of several" (g "cd abd/" []) (Some "deeper/"))
|
||||
(expect "a directory ignoring case replaces the word" (sg "cd mix" []) (Some (Tuple "ed/" "cd Mixed/")))
|
||||
(expect "a path argument suggests files, with no space" (g "cat abc" []) (Some ".txt"))
|
||||
(expect "several files, their common prefix" (g "cat a" []) None)
|
||||
(expect "in a directory" (g "cat abd/in" []) (Some "ner"))
|
||||
(expect "not the command" (g "ab" []) None)
|
||||
(expect "not an empty argument" (g "cat " []) None)
|
||||
(expect "not a second line" (g "echo 'a\ncat abc" []) None)
|
||||
(expect "cd from the history, newest first"
|
||||
(suggest "cd a" ["cd abd" "cd abd/deeper" "ls"]) (Some "bd/deeper"))
|
||||
(g "cd a" ["cd abd" "cd abd/deeper" "ls"]) (Some "bd/deeper"))
|
||||
(expect "not a directory that is gone"
|
||||
(suggest "cd o" ["cd other" "cd old-gone"]) (Some "ther"))
|
||||
(expect "only cd lines" (suggest "cd o" ["cdx other"]) (Some "ther/"))
|
||||
(g "cd o" ["cd other" "cd old-gone"]) (Some "ther"))
|
||||
(expect "only cd lines" (g "cd o" ["cdx other"]) (Some "ther/"))
|
||||
(expect "any line from the history" (g "ec" ["echo hi"]) (Some "ho hi"))
|
||||
(expect "the newest" (g "ec" ["echo hi" "echo ho"]) (Some "ho ho"))
|
||||
(expect "not one whose command is gone" (g "nosuch" ["nosuch-command-x a"]) None)
|
||||
(expect "ignoring case, it replaces the line" (sg "EC" ["echo hi"]) (Some (Tuple "ho hi" "echo hi")))
|
||||
(defun (visit! path)
|
||||
(set-current-directory! path)
|
||||
(dir-arrived! sh)
|
||||
(set-current-directory! dir))
|
||||
(visit! (path-combine dir "other"))
|
||||
(visit! (path-combine dir "other"))
|
||||
(visit! (path-combine dir "abd/deeper"))
|
||||
(expect "cd from the history by frecency" (g "cd " ["cd other" "cd abd/deeper"]) (Some "other"))
|
||||
(set-current-directory! (path-combine dir "other"))
|
||||
(def deeper (path-combine dir "abd/deeper"))
|
||||
(expect "a visited directory the words match"
|
||||
(sg "cd deep" []) (Some (Tuple (str " \u{2192} " deeper) (str "cd " deeper))))
|
||||
(expect "with several words" (g "cd abd dee" []) (Some (str " \u{2192} " deeper)))
|
||||
(expect "not the directory you are in" (g "cd oth" []) None)
|
||||
(expect "Tab after cd completes them too" (cands "cd deep") [(str deeper "/")])
|
||||
(set-current-directory! dir)
|
||||
(set-current-directory! here)
|
||||
(ignore (directory-delete-tree dir))
|
||||
0)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue