Suggestions for cd and paths, and a directory history; bjoterm 0.1.2

The editor suggests, as fish does, the newest cd line of the history whose
directory exists, else the directories or files that start with the word.
prevd, nextd and cdh move in the directory history, and so do Alt-Left and
Alt-Right on an empty line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-12-01 13:10:06 +01:00
parent 77c6d7977a
commit 5012a5d993
8 changed files with 262 additions and 14 deletions

View file

@ -1,5 +1,5 @@
(lock (lock
(locked (locked
(package (name (bjoterm)) (version "0.1.1") (package (name (bjoterm)) (version "0.1.2")
(source (git (url "https://rikspucko.koketteriet.se/bjoli/bjoterm.git"))) (source (git (url "https://rikspucko.koketteriet.se/bjoli/bjoterm.git")))
(commit "dc8a3325b88999134a06dca9bd8e576a309a75a86d638550cea2dcc4a7e3cb42")))) (commit "3021b14aac63b458fbaa589c4a5b02a9dd58c5432bfe7d3e0cb5667d9f618970"))))

View file

@ -10,5 +10,5 @@
;; The line editor and the terminal. To work on both at once, use ;; The line editor and the terminal. To work on both at once, use
;; (source (path (dir "../bjoterm"))) instead. ;; (source (path (dir "../bjoterm"))) instead.
(package (name (bjoterm)) (package (name (bjoterm))
(version (version-at-least "0.1.1")) (version (version-at-least "0.1.2"))
(source (git (url "https://rikspucko.koketteriet.se/bjoli/bjoterm.git")))))) (source (git (url "https://rikspucko.koketteriet.se/bjoli/bjoterm.git"))))))

View file

@ -21,7 +21,7 @@
(import (bjosh values)) (import (bjosh values))
(import (text json)) (import (text json))
(export builtin? run-builtin builtin-names find-program shell-value-command) (export builtin? run-builtin builtin-names find-program shell-value-command step-directory)
(type (: Builtin (Record (: name string) (type (: Builtin (Record (: name string)
(: usage string) (: usage string)
@ -41,6 +41,17 @@
status status
(go (+ i 1) (max status (f (vec-ref items i))))))) (go (+ i 1) (max status (f (vec-ref items i)))))))
;; Changes to `dir`, and sets OLDPWD and PWD. Returns the error message.
(: (-> string (Result string Unit)))
(defun (change-directory dir)
(def old (current-directory))
(match (try (set-current-directory! dir) #:catch (System.Exception))
((Ok _)
(set-environment-variable! "OLDPWD" old)
(set-environment-variable! "PWD" (current-directory))
(Ok unit))
((Err e) (Err (.-Message e)))))
(: (-> Shell (Vec string) int)) (: (-> Shell (Vec string) int))
(defun (cd sh args) (defun (cd sh args)
(def old (current-directory)) (def old (current-directory))
@ -52,14 +63,75 @@
(match target (match target
(None (shell-error "cd: no HOME or OLDPWD") 1) (None (shell-error "cd: no HOME or OLDPWD") 1)
((Some dir) ((Some dir)
(match (try (set-current-directory! dir) #:catch (System.Exception)) (match (change-directory dir)
((Ok _) ((Ok _)
(set-environment-variable! "OLDPWD" old) (unless (= (current-directory) old)
(set-environment-variable! "PWD" (current-directory)) (dir-visited! sh old))
(when (and (not (vec-empty? args)) (= (vec-ref args 0) "-")) (when (and (not (vec-empty? args)) (= (vec-ref args 0) "-"))
(println (current-directory))) (println (current-directory)))
0) 0)
((Err e) (shell-error (str "cd: " dir ": " (.-Message e))) 1))))) ((Err message) (shell-error (str "cd: " dir ": " message)) 1)))))
;; 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
;; fails.
;; - Returns 1 when there is no step to take; the error is written unless
;; `quiet?`.
(: (-> Shell bool bool int))
(defun (step-directory sh back? quiet?)
(def name (if back? "prevd" "nextd"))
(def from (if back? (record-ref sh dir-back) (record-ref sh dir-forward)))
(def to (if back? (record-ref sh dir-forward) (record-ref sh dir-back)))
(def n (vec-length from))
(cond
((= n 0)
(unless quiet?
(shell-error (str name ": no " (if back? "previous" "next") " directory")))
1)
(else
(def target (vec-ref from (- n 1)))
(def rest (vec-slice from 0 (- n 1)))
(def old (current-directory))
(match (change-directory target)
((Ok _)
(def moved (vec-add to old))
(if back? (dir-set-history! sh rest moved) (dir-set-history! sh moved rest))
0)
((Err message)
(if back? (dir-set-history! sh rest to) (dir-set-history! sh to rest))
(shell-error (str name ": " target ": " message))
1)))))
;; prevd and nextd: N steps, 1 by default.
(: (-> bool (-> Shell (Vec string) int)))
(defun (dir-stepper back?)
(fun (sh args)
(def name (if back? "prevd" "nextd"))
(match (if (vec-empty? args) (Some 1) (string->int (vec-ref args 0)))
((Some n) #:when (> n 0)
(let go ((i 0))
(cond
((= i n) 0)
((= (step-directory sh back? #f) 0) (go (+ i 1)))
(else 1))))
(_ (shell-error (str name ": " (vec-ref args 0) ": not a positive number")) 2))))
;; cdh: lists the directories before this one, newest first and numbered;
;; cdh N goes to number N, as cd does.
(: (-> Shell (Vec string) int))
(defun (cdh sh args)
(def back (record-ref sh dir-back))
(def n (vec-length back))
(cond
((vec-empty? args)
(loop (:for i (range 0 n))
(:do (println (str (string-pad-left (int->string (+ i 1)) 3) " " (vec-ref back (- n i 1))))))
0)
(else
(match (string->int (vec-ref args 0))
((Some k) #:when (and (> k 0) (<= k n)) (cd sh [(vec-ref back (- n k))]))
(_ (shell-error (str "cdh: " (vec-ref args 0) ": not a number from 1 to " (int->string n))) 2)))))
(: (-> Shell (Vec string) int)) (: (-> Shell (Vec string) int))
(defun (pwd sh args) (defun (pwd sh args)
@ -331,6 +403,9 @@
(: (-> (Vec Builtin))) (: (-> (Vec Builtin)))
(defun (builtins) (defun (builtins)
[(Builtin (name "cd") (usage "cd [DIR|-]") (help "change the directory; - is the one before") (run cd)) [(Builtin (name "cd") (usage "cd [DIR|-]") (help "change the directory; - is the one before") (run cd))
(Builtin (name "prevd") (usage "prevd [N]") (help "go back in the directory history; also Alt-Left") (run (dir-stepper #t)))
(Builtin (name "nextd") (usage "nextd [N]") (help "go forward in the directory history; also Alt-Right") (run (dir-stepper #f)))
(Builtin (name "cdh") (usage "cdh [N]") (help "list the directories before this one, or go to number N") (run cdh))
(Builtin (name "pwd") (usage "pwd") (help "write the current directory") (run pwd)) (Builtin (name "pwd") (usage "pwd") (help "write the current directory") (run pwd))
(Builtin (name "exit") (usage "exit [CODE]") (help "end the shell") (run exit-shell)) (Builtin (name "exit") (usage "exit [CODE]") (help "end the shell") (run exit-shell))
(Builtin (name "export") (usage "export NAME[=VALUE]...") (help "put variables in the environment") (run export)) (Builtin (name "export") (usage "export NAME[=VALUE]...") (help "put variables in the environment") (run export))

View file

@ -9,6 +9,8 @@
;; the shell commands and the programs on PATH; other words, and words ;; the shell commands and the programs on PATH; other words, and words
;; with a /, from file names. Names are quoted with \ where the parser ;; with a /, from file names. Names are quoted with \ where the parser
;; needs it. Directories end with /, everything else with a space. ;; needs it. Directories end with /, everything else with a space.
;; - `suggest`: the suggester, as fish's autosuggestions, for `cd` and
;; paths. See `suggest`.
(import (std prelude)) (import (std prelude))
(import (std maths)) (import (std maths))
@ -17,7 +19,7 @@
(import (bjosh builtins)) (import (bjosh builtins))
(import (bjosh commands)) (import (bjosh commands))
(export input-done? complete word-start command-position? quote-name file-candidates) (export input-done? complete suggest word-start command-position? quote-name file-candidates)
;; Whether Enter runs `text`: #f while a quote is open, or the line ends ;; Whether Enter runs `text`: #f while a quote is open, or the line ends
@ -135,3 +137,100 @@
(candidates (if (and (command-position? text start) (not (string-contains? word "/"))) (candidates (if (and (command-position? text start) (not (string-contains? word "/")))
(command-candidates word) (command-candidates word)
(file-candidates word))))) (file-candidates word)))))
;; ===========================================================================
;; 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)
(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)))))
;; 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)))
(cond
((< i 0) None)
(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)))))))
;; 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.
(: (-> string (Vec string) (Option string)))
(defun (extension word candidates)
(def matching (vec-filter (fun (c) (string-starts-with? c word)) candidates))
(cond
((vec-empty? matching) None)
(else
(def common (string-trim-right (common-prefix matching)))
(if (> (string-length common) (string-length word))
(Some (string-drop common (string-length word)))
None))))
;; The longest prefix that all of `items` have.
(: (-> (Vec string) string))
(defun (common-prefix items)
(def first (string->vec (vec-ref items 0)))
(def n (loop (:for item (in-vec items))
(:acc k (folding (vec-length first)
(let ((cs (string->vec item)))
(let go ((i 0))
(if (and (< i k) (< i (vec-length cs))
(= (vec-ref first i) (vec-ref cs i)))
(go (+ i 1))
i)))))))
(string-join (vec-map char->string (vec-slice first 0 n)) ""))
;; `name` with the \ escapes of `quote-name` taken out.
(: (-> string string))
(defun (unquote-name name)
(def out (stringbuilder-empty))
(let go ((cs (string->list name)))
(match cs
(Nil unit)
((Cons #\\ (Cons c more)) (stringbuilder-add! out c) (go more))
((Cons c more) (stringbuilder-add! out c) (go more))))
(stringbuilder->string out))
;; `path` with a leading ~ as $HOME.
(: (-> string string))
(defun (expand-home path)
(match (getenv "HOME")
((Some home)
(cond
((= path "~") home)
((string-starts-with? path "~/") (str home (string-drop path 1)))
(else path)))
(None path)))

View file

@ -25,6 +25,9 @@
;; turns this off. ;; turns this off.
;; - The prompt is $PROMPT when it is set (see `custom-prompt`), else the ;; - The prompt is $PROMPT when it is set (see `custom-prompt`), else the
;; user's prompt function, else the directory and $. ;; 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`.
(import (std prelude)) (import (std prelude))
(import (std run)) (import (std run))
@ -159,12 +162,28 @@
(flush!) (flush!)
(stringbuilder->string out)) (stringbuilder->string out))
;; Whether `ev` is Alt-Left or Alt-Right on an empty line: the keys the
;; shell takes for the directory history.
(: (-> TermEvent string bool))
(defun (directory-key? ev text)
(and (string-empty? (string-trim text))
(some? (directory-step ev))))
;; #t for back, #f for forward, for Alt-Left and Alt-Right.
(: (-> TermEvent (Option bool)))
(defun (directory-step ev)
(match ev
((TermKey KeyLeft (Mods (alt? #t) (ctrl? #f))) (Some #t))
((TermKey KeyRight (Mods (alt? #t) (ctrl? #f))) (Some #f))
(_ None)))
(: (-> Terminal int)) (: (-> Terminal int))
(defun (interactive term) (defun (interactive term)
(def jc (match (job-control) (def jc (match (job-control)
((Ok jc) (Some jc)) ((Ok jc) (Some jc))
((Err _) (shell-error "no job control: & and Ctrl-Z do not work") None))) ((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?) (def ed (make-line-editor #:completer (Some complete) #:input-done? (Some input-done?)
#:suggester (Some suggest) #:command-key? (Some directory-key?)
#:suspend? #f)) #:suspend? #f))
(def path (history-path)) (def path (history-path))
(ignore (line-history-load! ed path)) (ignore (line-history-load! ed path))
@ -184,7 +203,13 @@
(ignore (line-history-save ed path)) (ignore (line-history-save ed path))
(ignore (run-text sh text))) (ignore (run-text sh text)))
(LineCancelled (set-status! sh 130)) (LineCancelled (set-status! sh 130))
(LineEof (ignore (run-text sh "exit")))) (LineEof (ignore (run-text sh "exit")))
((LineKey ev _)
(match (directory-step ev)
((Some back?)
(unless (= (step-directory sh back? #t) 0)
(write-string (parameter-ref current-output-port) "\u{7}")))
(None unit))))
(match (record-ref sh exit-code) (match (record-ref sh exit-code)
((Some code) code) ((Some code) code)
(None (go))))) (None (go)))))

View file

@ -27,7 +27,7 @@
Shell JobEntry make-shell subshell shell-error Shell JobEntry make-shell subshell shell-error
alias-ref alias-set! alias-remove! set-subst-status! set-extension! prompt-failed! alias-ref alias-set! alias-remove! set-subst-status! set-extension! prompt-failed!
user-value-command user-shell-command user-value-command user-shell-command
set-status! request-exit! warn-stopped! var-export! set-status! request-exit! warn-stopped! var-export! dir-visited! dir-set-history!
var-ref var-set! var-unset! shell-expander job-set-state! 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-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) job-text-line job-mark job-state-text foreground! report-jobs job-changes state->status error-text)
@ -52,6 +52,9 @@
;; - `extension`: the user's commands and prompt (see (bjosh user)). ;; - `extension`: the user's commands and prompt (see (bjosh user)).
;; - `prompt-failed?`: the user's prompt raised; it is not used until ;; - `prompt-failed?`: the user's prompt raised; it is not used until
;; `reload`. ;; `reload`.
;; - `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.
(type (: Shell (Record (: vars (Map string string) #:mutable) (type (: Shell (Record (: vars (Map string string) #:mutable)
(: status int #:mutable) (: status int #:mutable)
(: jc (Option JobControl)) (: jc (Option JobControl))
@ -65,7 +68,9 @@
(: capture? bool) (: capture? bool)
(: subst-status (Option int) #:mutable) (: subst-status (Option int) #:mutable)
(: extension Extension #:mutable) (: extension Extension #:mutable)
(: prompt-failed? bool #:mutable)))) (: prompt-failed? bool #:mutable)
(: dir-back (Vec string) #:mutable)
(: dir-forward (Vec string) #:mutable))))
(import/extern (import/extern
(pid (: System.Environment.ProcessId int #:get #:no-raise))) (pid (: System.Environment.ProcessId int #:get #:no-raise)))
@ -75,7 +80,7 @@
(Shell (vars (map-empty)) (status 0) (jc jc) (editor editor) (args args) (Shell (vars (map-empty)) (status 0) (jc jc) (editor editor) (args args)
(jobs []) (recent []) (exit-code None) (warned-stopped? #f) (jobs []) (recent []) (exit-code None) (warned-stopped? #f)
(aliases (map-empty)) (capture? #f) (subst-status None) (aliases (map-empty)) (capture? #f) (subst-status None)
(extension no-extension) (prompt-failed? #f))) (extension no-extension) (prompt-failed? #f) (dir-back []) (dir-forward [])))
;; A copy of `sh` for $(...): the same variables, aliases and status, which ;; A copy of `sh` for $(...): the same variables, aliases and status, which
;; it can change for itself, and no jobs or job control. ;; it can change for itself, and no jobs or job control.
@ -85,11 +90,28 @@
(editor (record-ref sh editor)) (args (record-ref sh args)) (editor (record-ref sh editor)) (args (record-ref sh args))
(jobs []) (recent []) (exit-code None) (warned-stopped? #f) (jobs []) (recent []) (exit-code None) (warned-stopped? #f)
(aliases (record-ref sh aliases)) (capture? #t) (subst-status None) (aliases (record-ref sh aliases)) (capture? #t) (subst-status None)
(extension (record-ref sh extension)) (prompt-failed? (record-ref sh prompt-failed?)))) (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))))
(: (-> Shell (Option int) void)) (: (-> Shell (Option int) void))
(defun (set-subst-status! sh status) (record-set! sh (subst-status status))) (defun (set-subst-status! sh status) (record-set! sh (subst-status status)))
;; The most directories `dir-back` keeps; the oldest go first.
(: int)
(def dir-history-size 100)
;; Records that the shell left `old` for another directory, by `cd`.
(: (-> Shell string void))
(defun (dir-visited! sh old)
(def added (vec-add (record-ref sh dir-back) old))
(def extra (- (vec-length added) dir-history-size))
(record-set! sh (dir-back (if (> extra 0) (vec-slice added extra dir-history-size) added))
(dir-forward [])))
(: (-> Shell (Vec string) (Vec string) void))
(defun (dir-set-history! sh back forward)
(record-set! sh (dir-back back) (dir-forward forward)))
(: (-> Shell Extension void)) (: (-> Shell Extension void))
(defun (set-extension! sh ext) (defun (set-extension! sh ext)
(record-set! sh (extension ext) (prompt-failed? #f))) (record-set! sh (extension ext) (prompt-failed? #f)))

View file

@ -52,6 +52,24 @@
(any? (fun (c) (= c "jobs ")) (record-ref (complete "jo") candidates)) #t) (any? (fun (c) (= c "jobs ")) (record-ref (complete "jo") candidates)) #t)
(expect "a first word with a / completes files" (record-ref (complete "./ab") candidates) (expect "a first word with a / completes files" (record-ref (complete "./ab") candidates)
["./abc.txt " "./abd/"]) ["./abc.txt " "./abd/"])
;; 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)
(expect "cd from the history, newest first"
(suggest "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/"))
(set-current-directory! here) (set-current-directory! here)
(ignore (directory-delete-tree dir)) (ignore (directory-delete-tree dir))
0) 0)

View file

@ -109,6 +109,15 @@
(expect "cd and pwd" (c "cd /tmp; pwd") "/tmp") (expect "cd and pwd" (c "cd /tmp; pwd") "/tmp")
(expect "cd -" (c "cd /tmp; cd /; cd -") "/tmp") (expect "cd -" (c "cd /tmp; cd /; cd -") "/tmp")
(expect "cd to nowhere" (string-contains? (c "cd /no/such/dir") "code: 1") #t) (expect "cd to nowhere" (string-contains? (c "cd /no/such/dir") "code: 1") #t)
(expect "prevd goes back" (c "cd /tmp; cd /; prevd; pwd") "/tmp")
(expect "and nextd forward" (c "cd /tmp; cd /; prevd; nextd; pwd") "/")
(expect "prevd N" (c "cd /tmp; cd /usr; cd /; prevd 2; pwd") "/tmp")
(expect "cd empties the way forward" (string-contains? (c "cd /tmp; cd /; prevd; cd /usr; nextd") "no next directory") #t)
(expect "prevd with no history" (string-contains? (c "prevd") "code: 1") #t)
(expect "cdh lists newest first" (c "cd /tmp; cd /usr; cd /; cdh")
(str " 1 /usr\n 2 /tmp\n 3 " (current-directory)))
(expect "cdh N goes there" (c "cd /tmp; cd /usr; cd /; cdh 2; pwd") "/tmp")
(expect "the same directory is not history" (c "cd /tmp; cd /tmp; cdh") (str " 1 " (current-directory)))
(expect "type" (c "type cd") "cd is a shell command") (expect "type" (c "type cd") "cd is a shell command")
(expect "a shell command in a pipe" (c "cd | cat") (expect "a shell command in a pipe" (c "cd | cat")
"err: bjosh: cd: a shell command cannot be in a pipe\ncode: 2") "err: bjosh: cd: a shell command cannot be in a pipe\ncode: 2")