From 4eef978b6b7862a2ac0901539d3e46c56db49d4ef4c502e8ca62960a8e4b3a85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20Bj=C3=B6rnstam?= Date: Tue, 1 Dec 2026 14:23:40 +0100 Subject: [PATCH] line-read: a menu of the candidates below the input; 0.2.2 As fish does: Tab that can add nothing opens a menu, Tab and Shift-Tab choose a candidate into the input, Escape restores it, and another key closes the menu. Names are shown without their common directory. Co-Authored-By: Claude Opus 5.5 --- manifest.bjodat | 2 +- src/line.bjo | 215 +++++++++++++++++++++++++++++++++++------------- tests/line.bjo | 35 ++++++++ 3 files changed, 194 insertions(+), 58 deletions(-) diff --git a/manifest.bjodat b/manifest.bjodat index 3559c05..5989f13 100644 --- a/manifest.bjodat +++ b/manifest.bjodat @@ -1,6 +1,6 @@ (package (name (bjoterm)) - (version "0.2.1") + (version "0.2.2") (description "The terminal for Bjolang programs: raw mode, key events and escape sequences. Linux.") (license "MPL-2.0") diff --git a/src/line.bjo b/src/line.bjo index 96e2405..c5ab610 100644 --- a/src/line.bjo +++ b/src/line.bjo @@ -44,7 +44,7 @@ LineEditor LineResult Completion Suggestion suggestion-after make-line-editor line-read line-history line-history-add! line-history-load! line-history-save - simulate-line cursor-row-after-reflow input-window completion-listing) + simulate-line cursor-row-after-reflow input-window completion-listing menu-lines) ;; =========================================================================== ;; Types @@ -100,21 +100,33 @@ (type (: Search (Record (: query string) (: at int) (: failed? bool) (: before-text (Vec string)) (: before-cursor int)))) +;; The candidates that Tab shows below the input, to choose from. +;; - `items` and `descriptions`: from the `Completion`. +;; - `start` and `end`: the clusters that a choice replaces. `end` is the +;; end of the chosen candidate, or of the word as typed before the first. +;; - `selected`: the chosen item, or -1 before the first. +;; - `before-text` and `before-cursor`: the input when the menu opened, +;; restored by Escape and C-g. +(type (: Menu (Record (: items (Vec string)) (: descriptions (Vec string)) + (: start int) (: end int) (: selected int) + (: before-text (Vec string)) (: before-cursor int)))) + ;; The state of one `line-read`. ;; - `text`: grapheme clusters; "\n" separates lines. ;; - `cursor`: an index into `text`, from 0 to its length. ;; - `killing?`: the last key killed text, so the next kill adds to `kill`. ;; - `hist-at`: the history entry shown; the history's length for the ;; input being written, which is kept in `draft` meanwhile. +;; - `menu`: the candidates of Tab, shown below the input while it is open. (type (: State (Record (: text (Vec string)) (: cursor int) (: kill string) (: killing? bool) (: hist-at int) (: draft (Vec string)) - (: search (Option Search))))) + (: search (Option Search)) + (: menu (Option Menu))))) ;; What one key does. (type (: Step (Union (: Edited State) (: Finished State LineResult) - (: ShowList State (Vec string) (Vec string)) (: ClearScreen State) (: SuspendNow State) (: Bell State)))) @@ -233,8 +245,10 @@ ;; - History: Up and Down on the first and last line, C-p, C-n; C-r ;; searches back, again C-r for an older match, C-g ends the search. ;; - Tab completes with `#:completer`: it inserts the candidates' common -;; prefix, or lists them when that adds nothing, as fish does. Without -;; a completer it inserts a tab. +;; prefix, or, when that adds nothing, opens a menu of them below the +;; input, as fish does. Without a completer it inserts a tab. In the +;; menu, Tab and Shift-Tab choose the next and the one before, Escape +;; restores the input, and another key closes it (see `menu-step`). ;; - A suggestion from `#:suggester`: at the end of the input, Right, C-f, ;; End and C-e accept all of it; M-f, C-Right and M-Right one word. ;; - Enter accepts (see `#:input-done?`), M-Enter and C-j start a new line, @@ -280,7 +294,7 @@ (def text (clusters initial)) (State (text text) (cursor (vec-length text)) (kill "") (killing? #f) (hist-at (vec-length (record-ref ed history))) (draft []) - (search None))) + (search None) (menu None))) (: (-> LineEditor Terminal string string (Option (-> (Vec string))) string LineResult)) (defun (edit-loop ed term prompt cont notices initial) @@ -314,7 +328,17 @@ ((Some s) (clusters (record-ref s ghost))) (None [])))) (def lay (layout-state st prompt cont width ghost)) - (def shown (window-of lay width (if whole? None (Some height)) top)) + (def input (window-of lay width (if whole? None (Some height)) top)) + ;; The menu, below the input, in the rows the screen has left. + (def menu-rows + (match (if whole? None (record-ref st menu)) + ((Some m) (menu-lines (record-ref m items) (record-ref m descriptions) (record-ref m selected) + width (Some (max 1 (- height (vec-length (record-ref input rows)) 1))))) + (None []))) + (def shown (record-set input + (text (str (record-ref input text) + (string-join (vec-map (fun (l) (str "\n" l)) menu-rows) ""))) + (rows (vec-append (record-ref input rows) (vec-map (fun (_) [1]) menu-rows))))) (write-string out (str "\r" (cursor-up (rows-up width)) clear-below (record-ref shown text) (cursor-up (- (last-row shown) (record-ref shown cursor-row))) @@ -362,10 +386,6 @@ (leave lay) (terminal-suspend term) (go next)) - ((ShowList next items descriptions) - (leave lay) - (write-string out (completion-listing items descriptions (fst (terminal-size term)))) - (go next)) ((Finished _ (LineKey ev text)) (def (Tuple width _) (terminal-size term)) (write-string out (str "\r" (cursor-up (rows-up width)) clear-below)) @@ -384,31 +404,82 @@ (_ unit)) result)))) -;; The list of candidates that Tab writes, each row ended by "\n". -;; - Without descriptions: in columns, as `columns`. -;; - With descriptions: one candidate a row, its description after it, -;; dimmed and cut to fit `width`. The candidates' column is as wide as -;; the widest, up to half of `width`. +;; The rows of the menu of `items`. +;; - Names are shown without the directory part that all of them have, so +;; that "src/a.bjo" and "src/b.bjo" show as "a.bjo" and "b.bjo". +;; - Without descriptions: in columns as wide as the widest, filling rows +;; first. With them: one item a row, its description after it, dimmed +;; and cut to fit `width`, in a column as wide as the widest item, up +;; to half of `width`. +;; - `selected` is shown in reverse; -1 shows none. +;; - With `max-rows`, a longer menu shows the rows around the selected +;; item, and a last row that says how many more there are. +(: (-> (Vec string) (Vec string) int int (Option int) (Vec string))) +(defun (menu-lines items descriptions selected width max-rows) + (def names (shown-names items)) + (def n (vec-length names)) + (def described? (not (or (vec-empty? descriptions) (all? string-empty? descriptions)))) + (def widest (loop (:for name (in-vec names)) + (:acc w (folding 0 (max w (text-width name)))))) + (def per-row (if described? 1 (max 1 (quotient width (+ widest 2))))) + (defun (name-at i) + (def name (fit-width (vec-ref names i) (max 1 (- width 1)))) + (if (= i selected) (styled name [StyleReverse]) name)) + (def rows + (if described? + (let ((cell (min (+ widest 2) (max 1 (quotient width 2))))) + (loop (:for i (range 0 n)) + (:acc out (vecing + (let* ((d (if (< i (vec-length descriptions)) (vec-ref descriptions i) "")) + (w (text-width (vec-ref names i))) + (room (- width (max cell (+ w 2))))) + (if (or (string-empty? d) (<= room 3)) + (name-at i) + (str (name-at i) (string-pad-left "" (max 2 (- cell w))) + (styled (fit-width d room) ghost-style)))))))) + (loop (:for r (range 0 (quotient (+ n (- per-row 1)) per-row))) + (:acc out (vecing + (let ((last (min n (* (+ r 1) per-row)))) + (string-join + (loop (:for i (range (* r per-row) last)) + (:acc cells (vecing + (if (= (+ i 1) last) + (name-at i) + (str (name-at i) + (string-pad-left "" (- (+ widest 2) (text-width (vec-ref names i))))))))) + ""))))))) + (def total (vec-length rows)) + (match max-rows + ((Some limit) + (if (<= total limit) + rows + (let* ((room (max 1 (- limit 1))) + (at (if (< selected 0) 0 (quotient selected per-row))) + (top (max 0 (min (- total room) (- at (- room 1)))))) + (vec-add (vec-slice rows top room) + (styled (str "\u{2026} " (int->string (- total room)) " more rows") ghost-style))))) + (None rows))) + +;; `items` without the directory part that all of them have, and without +;; a space at the end. A name that would be empty keeps its directory. +(: (-> (Vec string) (Vec string))) +(defun (shown-names items) + (def names (vec-map string-trim-right items)) + (def common (if (vec-empty? names) "" (common-prefix names))) + (let cut ((dir (let ((parts (string-split common "/"))) + (string-drop-right common (string-length (vec-ref parts (- (vec-length parts) 1))))))) + (cond + ((string-empty? dir) names) + ((any? (fun (name) (= name dir)) names) + (def shorter (string-drop-right dir 1)) + (def parts (string-split shorter "/")) + (cut (string-drop-right shorter (string-length (vec-ref parts (- (vec-length parts) 1)))))) + (else (vec-map (fun (name) (string-drop name (string-length dir))) names))))) + +;; The menu of `items`, each row ended by "\n". See `menu-lines`. (: (-> (Vec string) (Vec string) int string)) (defun (completion-listing items descriptions width) - (if (or (vec-empty? descriptions) (all? string-empty? descriptions)) - (columns items width) - (let* ((widest (loop (:for item (in-vec items)) - (:acc w (folding 0 (max w (text-width item)))))) - (cell (min (+ widest 2) (max 1 (quotient width 2)))) - (out (stringbuilder-empty))) - (loop (:for item (in-vec items)) - (:for i (range 0 (vec-length items))) - (:do (def d (if (< i (vec-length descriptions)) (vec-ref descriptions i) "")) - (def w (text-width item)) - (stringbuilder-add-string! out item) - (unless (string-empty? d) - (def room (- width (max cell (+ w 2)))) - (when (> room 3) - (stringbuilder-add-string! out (string-pad-left "" (max 2 (- cell w)))) - (stringbuilder-add-string! out (styled (fit-width d room) ghost-style)))) - (stringbuilder-add-string! out "\n"))) - (stringbuilder->string out)))) + (string-join (vec-map (fun (l) (str l "\n")) (menu-lines items descriptions -1 width None)) "")) ;; `s` cut to `width` columns, with … at the end when it is cut. (: (-> string int string)) @@ -424,25 +495,6 @@ (str (string-join out "") "\u{2026}") (go more (+ w cw) (vec-add out c)))))))) -;; `items` in columns as wide as the widest, filling rows first, each row -;; ended by "\n". -(: (-> (Vec string) int string)) -(defun (columns items width) - (def widest (let go ((i 0) (w 0)) - (if (= i (vec-length items)) - w - (go (+ i 1) (max w (text-width (vec-ref items i))))))) - (def cell (+ widest 2)) - (def per-row (max 1 (quotient width cell))) - (def out (stringbuilder-empty)) - (loop (:for item (in-vec items)) - (:for i (range 0 (vec-length items))) - (:do (stringbuilder-add-string! out item) - (if (or (= (remainder (+ i 1) per-row) 0) (= (+ i 1) (vec-length items))) - (stringbuilder-add-string! out "\n") - (stringbuilder-add-string! out (string-pad-left "" (- cell (text-width item))))))) - (stringbuilder->string out)) - ;; Runs the editor on `events` without a terminal, as `line-read` would. ;; Returns the result, or None when the events ran out first, and the ;; buffer's text at the end. For tests. @@ -461,8 +513,7 @@ ((Edited next) (go next (+ i 1))) ((Bell next) (go next (+ i 1))) ((ClearScreen next) (go next (+ i 1))) - ((SuspendNow next) (go next (+ i 1))) - ((ShowList next _ _) (go next (+ i 1))))))) + ((SuspendNow next) (go next (+ i 1))))))) ;; =========================================================================== ;; Layout @@ -648,6 +699,7 @@ (None None) ((Some f) (if (or (some? (record-ref st search)) + (some? (record-ref st menu)) (vec-empty? text) (not (= (record-ref st cursor) (vec-length text)))) None @@ -839,7 +891,53 @@ (def common (common-prefix candidates)) (cond ((> (vec-length (clusters common)) k) (Edited (replace-with common))) - (else (ShowList st candidates (record-ref c descriptions))))))))) + (else + (Edited (record-set st (menu (Some (Menu (items candidates) (descriptions (record-ref c descriptions)) + (start (- cursor k)) (end cursor) (selected -1) + (before-text (record-ref st text)) + (before-cursor cursor))))))))))))) + +;; What `ev` does while the menu is open. +;; - Tab and C-i choose the next item, Shift-Tab the one before. +;; - Escape and C-g close the menu and restore the input. +;; - Enter after a choice closes the menu and keeps it. +;; - Another key closes the menu, and does what it does. +(: (-> LineEditor State Menu TermEvent Step)) +(defun (menu-step ed st m ev) + (def closed (record-set st (menu None))) + (match ev + ((TermKey KeyTab (Mods (shift? back?) (alt? #f) (ctrl? #f))) (Edited (choose st m (if back? -1 1)))) + ((TermKey (KeyChar #\i) (Mods (alt? #f) (ctrl? #t))) (Edited (choose st m 1))) + ((TermKey KeyEscape _) (Edited (restore-menu st m))) + ((TermKey (KeyChar #\g) (Mods (alt? #f) (ctrl? #t))) (Edited (restore-menu st m))) + ((TermKey KeyEnter (Mods (alt? #f))) + (if (< (record-ref m selected) 0) (editing ed closed ev) (Edited closed))) + ((TermResized _ _) (Edited st)) + (_ (editing ed closed ev)))) + +;; The input with the item `delta` steps from the chosen one in place of +;; the word. +(: (-> State Menu int State)) +(defun (choose st m delta) + (def items (record-ref m items)) + (def n (vec-length items)) + (def selected (record-ref m selected)) + (def i (if (< selected 0) + (if (> delta 0) 0 (- n 1)) + (remainder (+ selected delta n) n))) + (def chosen (clusters (vec-ref items i))) + (def text (record-ref st text)) + (def start (record-ref m start)) + (def end (record-ref m end)) + (def after (+ start (vec-length chosen))) + (record-set st (text (vec-append (vec-append (vec-slice text 0 start) chosen) + (vec-slice text end (- (vec-length text) end)))) + (cursor after) + (menu (Some (record-set m (selected i) (end after)))))) + +(: (-> State Menu State)) +(defun (restore-menu st m) + (record-set st (text (record-ref m before-text)) (cursor (record-ref m before-cursor)) (menu None))) ;; The next older match of `query` from history index `from` down, or None. (: (-> LineEditor string int (Option (Tuple int int)))) @@ -897,7 +995,10 @@ (else (match (record-ref prev search) ((Some s) (searching ed prev s ev)) - (None (editing ed prev ev)))))) + (None + (match (record-ref prev menu) + ((Some m) (menu-step ed prev m ev)) + (None (editing ed prev ev)))))))) (: (-> LineEditor State TermEvent Step)) (defun (editing ed prev ev) diff --git a/tests/line.bjo b/tests/line.bjo index 2296a06..ef09875 100644 --- a/tests/line.bjo +++ b/tests/line.bjo @@ -214,6 +214,41 @@ "buffer \"x vec-map \"") (expect "no candidate changes nothing" (run-on completing (keys [(typed "zz") [(key KeyTab) (key KeyTab)]])) "buffer \"zz\"") + (def menu-ed (make-line-editor #:completer (Some (fun (before) + (Completion (prefix "d/a") (candidates ["d/ab " "d/ac "]) + (descriptions [])))))) + (def tab (key KeyTab)) + (def back-tab (TermKey KeyTab (Mods (shift? #t) (alt? #f) (ctrl? #f)))) + (expect "Tab that adds nothing opens the menu, and changes nothing" + (run-on menu-ed (keys [(typed "x d/a") [tab]])) "buffer \"x d/a\"") + (expect "the next Tab chooses the first" + (run-on menu-ed (keys [(typed "x d/a") [tab tab]])) "buffer \"x d/ab \"") + (expect "and the next the second" + (run-on menu-ed (keys [(typed "x d/a") [tab tab tab]])) "buffer \"x d/ac \"") + (expect "and then the first again" + (run-on menu-ed (keys [(typed "x d/a") [tab tab tab tab]])) "buffer \"x d/ab \"") + (expect "Shift-Tab goes back" + (run-on menu-ed (keys [(typed "x d/a") [tab back-tab]])) "buffer \"x d/ac \"") + (expect "Escape restores the input" + (run-on menu-ed (keys [(typed "x d/a") [tab tab (key KeyEscape)]])) "buffer \"x d/a\"") + (expect "another key keeps the choice and does what it does" + (run-on menu-ed (keys [(typed "x d/a") [tab tab] (typed "z")])) "buffer \"x d/ab z\"") + (expect "Enter keeps the choice, and does not run the line" + (run-on menu-ed (keys [(typed "x d/a") [tab tab enter]])) "buffer \"x d/ab \"") + (expect "Enter with nothing chosen runs it" + (run-on menu-ed (keys [(typed "x d/a") [tab enter]])) "text \"x d/a\"") + (expect "the text after the cursor stays" + (run-on menu-ed (keys [(typed "x d/a;y") [(key KeyLeft) (key KeyLeft) tab tab]])) + "buffer \"x d/ab ;y\"") + (expect "the menu shows names without their common directory" + (menu-lines ["d/ab " "d/ac "] [] -1 40 None) ["ab ac"]) + (expect "but keeps one that would be empty" + (menu-lines ["d/" "d/e/"] [] -1 40 None) ["d/ d/e/"]) + (expect "the chosen one is in reverse" + (menu-lines ["ab" "cd"] [] 1 40 None) [(str "ab " (styled "cd" [StyleReverse]))]) + (expect "a long menu shows the rows around the chosen one" + (menu-lines ["a" "b" "c" "d" "e"] [] 3 3 (Some 3)) + ["c" (styled "d" [StyleReverse]) (styled "\u{2026} 3 more rows" [(StyleFg (Ansi 8))])]) (expect "Tab without a completer inserts a tab" (run-fresh (keys [(typed "a") [(key KeyTab)] [enter]])) "text \"a\\t\"")