;; 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): the shell. See plan.org. ;; ;; bjosh interactive, with job control, when stdin is a ;; terminal; else runs the lines of stdin ;; bjosh -c LINE runs LINE ;; bjosh FILE ARG... runs the lines of FILE, with $0 FILE, $1 ARG... ;; bjosh --new-commands ;; writes a package of user commands, with an ;; example; see (bjosh user). The first interactive ;; start does this too. ;; ;; The exit code is the status of the last line, or the code of `exit`. ;; ;; - An interactive shell first runs the lines of the start-up file, ;; $XDG_CONFIG_HOME/bjosh/rc or ~/.config/bjosh/rc. ;; - Each bjosh loads the user's commands, when there are any: an ;; interactive one after the start-up file, so that the file can set PATH ;; or BJO for the build; others before the first line. ;; - An interactive bjosh writes the package of user commands, with an ;; example, when its directory is not there. An empty directory there ;; 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 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)) (import (bjoterm terminal)) (import (bjoterm line)) (import (bjosh syntax)) (import (bjosh shell)) (import (bjosh builtins)) (import (bjosh exec)) (import (bjosh editor)) (import (bjosh api)) (import (bjosh user)) ;; =========================================================================== ;; The loop ;; =========================================================================== (: (-> string)) (defun (history-path) (def state (match (getenv "XDG_STATE_HOME") ((Some s) s) (None (path-combine (match (getenv "HOME") ((Some h) h) (None ".")) ".local/state")))) (path-combine state "bjosh/history")) ;; The start-up file. (: (-> string)) (defun (rc-path) (path-combine (config-dir) "rc")) ;; The directory, with ~ for home. (: (-> string)) (defun (shown-directory) (def dir (current-directory)) (def home (match (getenv "HOME") ((Some h) h) (None ""))) (if (and (not (string-empty? home)) (string-starts-with? dir home)) (str "~" (string-drop dir (string-length home))) dir)) ;; The prompt: `custom-prompt` of $PROMPT, else the user's prompt function, ;; else the directory, and $ green after status 0, else red. A prompt ;; function that raises writes its message once, and is not used again ;; until `reload`. (: (-> Shell string)) (defun (prompt sh) (def user (record-ref (record-ref sh extension) prompt)) (match (var-ref sh "PROMPT") ((Some template) (custom-prompt sh template)) (None (match (if (record-ref sh prompt-failed?) None user) ((Some f) (match (try (f (shell-view sh)) #:catch (System.Exception)) ((Ok text) text) ((Err e) (shell-error (str "the prompt of your commands raised: " (.-Message e))) (prompt-failed! sh) (default-prompt sh)))) (None (default-prompt sh)))))) (: (-> Shell string)) (defun (default-prompt sh) (def color (if (= (record-ref sh status) 0) "32" "31")) (str "\u{1B}[1;34m" (shown-directory) "\u{1B}[0m \u{1B}[" color "m$\u{1B}[0m ")) ;; Writes the package of user commands, with its example, when its ;; directory is not there. For an interactive start. (: (-> void)) (defun (set-up-commands) (unless (directory-exists? (commands-dir)) (match (write-example) (None (println (str "bjosh: wrote your commands to " (commands-dir) "/src/commands.bjo." " Edit them there, then run reload. Building them the first time..."))) ((Some message) (shell-error message))))) ;; Loads the user's commands into `sh`. A failure writes its message. (: (-> Shell Shell)) (defun (with-extension sh) (match (load-extension #f) (None unit) ((Some (Ok ext)) (set-extension! sh ext)) ((Some (Err message)) (shell-error message))) sh) (import/extern (user-name (: System.Environment.UserName string #:get #:no-raise)) (machine-name (: System.Environment.MachineName string #:get #:no-raise))) ;; The text of a prompt escape: \w, \W, \u, \h, \$, \e, \n or \\. (: (-> char (Option string))) (defun (prompt-escape c) (cond ((= c #\w) (Some (shown-directory))) ((= c #\W) (Some (let ((dir (shown-directory))) (if (= dir "/") dir (match (path-filename dir) ((Some n) n) (None dir)))))) ((= c #\u) (Some user-name)) ((= c #\h) (Some machine-name)) ((= c #\$) (Some (if (= user-name "root") "#" "$"))) ((= c #\e) (Some "\u{1B}")) ((= c #\n) (Some "\n")) ((= c #\\) (Some "\\")) (else None))) ;; $PROMPT, with its escapes replaced (see `prompt-escape`), and the text ;; between them expanded as in double quotes. A part that does not parse ;; is shown as written. (: (-> Shell string string)) (defun (custom-prompt sh template) (def chars (string->vec template)) (def out (stringbuilder-empty)) (def pending (stringbuilder-empty)) (defun (flush!) (def text (stringbuilder->string pending)) (stringbuilder-clear! pending) (unless (string-empty? text) (stringbuilder-add-string! out (match (expand-quoted sh text) ((Ok expanded) expanded) ((Err _) text))))) (let go ((i 0)) (when (< i (vec-length chars)) (def c (vec-ref chars i)) (def escape (if (and (= c #\\) (< (+ i 1) (vec-length chars))) (prompt-escape (vec-ref chars (+ i 1))) None)) (match escape ((Some text) (flush!) (stringbuilder-add-string! out text) (go (+ i 2))) (None (stringbuilder-add! pending c) (go (+ i 1)))))) (flush!) (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)) (defun (interactive term) (def jc (match (job-control) ((Ok jc) (Some jc)) ((Err _) (shell-error "no job control: & and Ctrl-Z do not work") None))) ;; 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) ((Ok text) (ignore (run-text sh text))) ((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)))) ((LineText text) (ignore (line-history-save ed path)) (ignore (run-text sh text))) (LineCancelled (set-status! sh 130)) (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) ((Some code) code) (None (go))))) (: (-> Shell string int)) (defun (run-script sh text) (ignore (run-text sh text)) (match (record-ref sh exit-code) ((Some code) code) (None (record-ref sh status)))) (: (-> (Vec string) int)) (defun (run-file args) (match (file-read-text (vec-ref args 0)) ((Ok text) (run-script (with-extension (make-shell None None args)) text)) ((Err e) (shell-error (fs-error-message e)) 127))) (defun (main args) (cond ((= args ["--new-commands"]) (match (write-example) (None (println (str "Wrote " (commands-dir) ". Edit src/commands.bjo there, and run reload in bjosh.")) 0) ((Some message) (shell-error message) 1))) ((and (>= (vec-length args) 2) (= (vec-ref args 0) "-c")) (run-script (with-extension (make-shell None None (vec-add-first (vec-slice args 2 (- (vec-length args) 2)) "bjosh"))) (vec-ref args 1))) ((vec-empty? args) (match (terminal-open) ((Ok term) (interactive term)) ((Err _) (run-script (with-extension (make-shell None None ["bjosh"])) (read-all (parameter-ref current-input-port)))))) (else (run-file args))))