bjosh/src/editor.bjo

237 lines
9.2 KiB
Text
Raw Normal View History

;; 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 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`.
(import (std prelude))
(import (std maths))
(import (bjoterm line))
(import (bjosh syntax))
(import (bjosh builtins))
(import (bjosh commands))
(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
;; with |, &&, || or \. A line with another error runs, to show it.
(: (-> string bool))
(defun (input-done? text)
(and (not (odd-backslashes-at-end? text))
(match (parse-line/message text)
((Ok _) #t)
((Err message) (not (string-contains? message "end of input"))))))
;; Whether `text` ends with a \ that escapes the line break after it.
(: (-> string bool))
(defun (odd-backslashes-at-end? text)
(def chars (string->vec text))
(let go ((i (vec-length chars)) (n 0))
(if (and (> i 0) (= (vec-ref chars (- i 1)) #\\))
(go (- i 1) (+ n 1))
(= (remainder n 2) 1))))
;; Where the word before the cursor starts: after the last space or
;; operator character.
(: (-> string int))
(defun (word-start text)
(def chars (string->vec text))
(let go ((i (vec-length chars)))
(cond
((= i 0) 0)
((string-contains? " \t\n|&;<>" (char->string (vec-ref chars (- i 1)))) i)
(else (go (- i 1))))))
;; Whether the word at `start` is the first word of a command.
(: (-> string int bool))
(defun (command-position? text start)
(def before (string-trim-right (string-take text start)))
(or (string-empty? before)
(string-contains? "|&;" (string-take-right before 1))))
;; `name` with \ before characters that the parser would read as syntax.
(: (-> string string))
(defun (quote-name name)
(string-join (vec-map (fun (c)
(def text (char->string c))
(if (string-contains? " \t'\"\\$`|&;<>()*?[]#~" text) (str "\\" text) text))
(string->vec name))
""))
;; The last part of a path.
(: (-> Path string))
(defun (base-name p)
(def parts (string-split (path->string/lossy p) "/"))
(vec-ref parts (- (vec-length parts) 1)))
(: (-> string (Vec string)))
(defun (path-names dir)
(match (directory-files dir)
((Ok paths) (vec-map base-name paths))
((Err _) [])))
(: (-> string (Vec string)))
(defun (directory-names dir)
(match (directory-subdirectories dir)
((Ok paths) (vec-map base-name paths))
((Err _) [])))
;; Programs on PATH and shell commands that start with `prefix`.
(: (-> string (Vec string)))
(defun (command-candidates prefix)
(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)))))
;; `names` sorted, each once.
(: (-> (Vec string) (Vec string)))
(defun (sorted-distinct names)
(def sorted (vec-sort names))
(let go ((i 0) (out []))
(cond
((= i (vec-length sorted)) out)
((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))))))
(: (-> 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)))))
;; ===========================================================================
;; 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)))