2473116df0d30855c3efa9a424c642d82ca43133
[lice.git] / minibuffer.lisp
blob2473116df0d30855c3efa9a424c642d82ca43133
1 (in-package :lice)
3 (defvar *history-length* 30
4 "Maximum length for history lists before truncation takes place.
5 A number means that length; t means infinite. Truncation takes place
6 just after a new element is inserted. Setting the :HISTORY-LENGTH
7 property of a history variable overrides this default.")
9 (defvar *minibuffer-text-before-history* nil
10 "Text that was in this minibuffer before any history commands.
11 This is nil if there have not yet been any history commands
12 in this use of the minibuffer.")
14 (defclass minibuffer-window (window)
15 ())
17 (defvar *minibuffer-local-map*
18 (let ((m (make-sparse-keymap)))
19 (define-key m (make-key :char #\m :control t) 'exit-minibuffer)
20 (define-key m (make-key :char #\Newline) 'exit-minibuffer)
21 (define-key m (make-key :char #\Return) 'exit-minibuffer)
22 (define-key m (make-key :char #\j :control t) 'exit-minibuffer)
23 (define-key m (make-key :char #\p :meta t) 'previous-history-element)
24 (define-key m (make-key :char #\n :meta t) 'next-history-element)
25 (define-key m (make-key :char #\g :control t) 'abort-recursive-edit)
27 "Default keymap to use when reading from the minibuffer.")
29 (defvar *minibuffer-local-completion-map*
30 (let ((m (make-sparse-keymap)))
31 (define-key m (make-key :char #\i :control t) 'minibuffer-complete)
32 (define-key m (make-key :char #\Tab) 'minibuffer-complete)
33 (setf (keymap-parent m) *minibuffer-local-map*)
35 "Local keymap for minibuffer input with completion.")
37 (defvar *minibuffer-local-must-match-map*
38 (let ((m (make-sparse-keymap)))
39 (define-key m (make-key :char #\m :control t) 'minibuffer-complete-and-exit)
40 (define-key m (make-key :char #\Newline) 'minibuffer-complete-and-exit)
41 (define-key m (make-key :char #\Return) 'minibuffer-complete-and-exit)
42 (define-key m (make-key :char #\j :control t) 'minibuffer-complete-and-exit)
43 (setf (keymap-parent m) *minibuffer-local-completion-map*)
45 "Local keymap for minibuffer input with completion, for exact match.")
47 (defvar *minibuffer-read-mode*
48 (make-instance 'major-mode
49 :name "minibuffer mode"
50 :map *minibuffer-local-map*))
52 (defvar *minibuffer-complete-mode*
53 (make-instance 'major-mode
54 :name "minibuffer mode"
55 :map *minibuffer-local-completion-map*))
57 (defvar *minibuffer-must-match-mode*
58 (make-instance 'major-mode
59 :name "minibuffer mode"
60 :map *minibuffer-local-must-match-map*))
62 (defvar *minibuffer-completion-table* nil
63 "Alist or obarray used for completion in the minibuffer.
64 This becomes the ALIST argument to `try-completion' and `all-completions'.
65 The value can also be a list of strings or a hash table.
67 The value may alternatively be a function, which is given three arguments:
68 STRING, the current buffer contents;
69 PREDICATE, the predicate for filtering possible matches;
70 CODE, which says what kind of things to do.
71 CODE can be nil, t or `lambda'.
72 nil means to return the best completion of STRING, or nil if there is none.
73 t means to return a list of all possible completions of STRING.
74 `lambda' means to return t if STRING is a valid completion as it stands.")
76 (defvar *minibuffer-history* nil
77 "Default minibuffer history list.
78 This is used for all minibuffer input
79 except when an alternate history list is specified.")
81 ;; FIXME: this should be a minibuffer-mode slot?
82 (defvar *minibuffer-history-position* nil
83 "Current position of redoing in the history list.")
85 ;; FIXME: this should be a minibuffer-mode slot?
86 (defvar *minibuffer-history-variable* '*minibuffer-history*
87 "History list symbol to add minibuffer values to.
88 Each string of minibuffer input, as it appears on exit from the minibuffer,
89 is added with
90 ** (set minibuffer-history-variable
91 ** (cons STRING (symbol-value minibuffer-history-variable)))")
93 ;; FIXME: this should be a minibuffer-mode slot?
94 (defvar *minibuffer-completion-predicate* nil
95 "Within call to `completing-read', this holds the PREDICATE argument.")
97 (defun minibufferp (&optional (buffer (current-buffer)))
98 ;; FIXME: implement
99 nil)
101 (defun make-minibuffer (major-mode)
102 "Return a fresh minibuffer with major mode, MAJOR-MODE."
103 ;; FIXME: Emacs prefixes it with a space so it doesn't show up in
104 ;; buffer listings. How are we gonna do this?
105 (let ((mb (get-buffer-create (generate-new-buffer-name " *minibuffer*"))))
106 (setf (buffer-major-mode mb) major-mode
107 (buffer-mode-line mb) nil)
108 mb))
110 (defun make-minibuffer-window (height cols)
111 (let* ((w (make-instance 'minibuffer-window
112 :x 0 :y (- height 1) :w cols :h 1
113 :line-state (make-array 1 :fill-pointer 1
114 :element-type 'integer :initial-element -1)
115 :cache (make-instance 'line-cache :valid t)
116 :top-line 0
117 :bottom-line 0
118 :point-col 0
119 :point-line 0
120 :buffer (make-minibuffer *minibuffer-read-mode*)
121 :top (make-marker)
122 :bottom (make-marker)
123 :bpoint (make-marker)
124 :point-col 0
125 :point-line 0)))
126 (set-marker (window-top w) 0 (window-buffer w))
127 (set-marker (window-bottom w) 0 (window-buffer w))
130 ;; (defun clear-minibuffer ()
131 ;; "Erase the contents of the minibuffer when it isn't active."
132 ;; (let ((minibuffer (window-buffer (frame-minibuffer-window (selected-frame)))))
133 ;; (erase-buffer minibuffer)))
135 (defun minibuffer-window (&optional (frame (selected-frame)))
136 "Return the window used now for minibuffers.
137 If the optional argument FRAME is specified, return the minibuffer window
138 used by that frame."
139 (frame-minibuffer-window frame))
141 (defun message (string &rest arguments)
142 "Print a one-line message at the bottom of the screen."
143 ;; FIXME: properly implement the echo area
144 (when (zerop (frame-minibuffers-active (selected-frame)))
145 (let ((minibuffer (window-buffer (frame-minibuffer-window (selected-frame))))
146 (msg (apply #'format nil string arguments)))
147 (erase-buffer minibuffer)
148 (buffer-insert minibuffer msg)
149 (with-current-buffer (get-buffer-create "*messages*")
150 (goto-char (point-max))
151 (insert msg #\Newline)))))
153 (defun clear-minibuffer ()
154 "Erase the text in the minibuffer, unless it's active."
155 (when (zerop (frame-minibuffers-active (selected-frame)))
156 (erase-buffer (window-buffer (frame-minibuffer-window (selected-frame))))))
158 (defun show-minibuffer-prompt (frame prompt)
159 "Show PROMPT in the minibuffer. Flip a bit in FRAME to allow
160 switching to the minibuffer."
161 (declare (type string prompt)
162 (ignore frame))
163 (let ((minibuffer (window-buffer (frame-minibuffer-window (selected-frame))))
164 (field (npropertize prompt 'field 't 'front-sticky t 'rear-nonsticky t)))
165 (dformat +debug-v+ "~a~%" field)
166 (erase-buffer minibuffer)
167 (buffer-insert minibuffer field)))
169 (defun minibuffer-prompt-end (&optional (minibuf (current-buffer)))
170 "Return the buffer position of the end of the minibuffer prompt.
171 Return (point-min) if current buffer is not a mini-buffer."
172 (let ((beg (begv minibuf)))
173 (multiple-value-bind (start end) (find-field beg nil :beg t :end t :buf minibuf)
174 (dformat +debug-v+ "exit-mb: ~a ~a ~a~%" start end (buffer-size minibuf))
175 (if (and (= end (zv minibuf))
176 (null (get-char-property beg 'field minibuf)))
178 end))))
180 (defun minibuffer-contents (&optional (minibuf (current-buffer)))
181 "Return the user input in a minbuffer as a string.
182 If MINIBUF is omitted, default to the current buffer.
183 MINIBUF must be a minibuffer."
184 (buffer-substring (minibuffer-prompt-end minibuf) (zv minibuf) minibuf))
186 (defun minibuffer-contents-no-properties (&optional (minibuf (current-buffer)))
187 "Return the user input in a minbuffer as a string.
188 If MINIBUF is omitted, default to the current buffer.
189 MINIBUF must be a minibuffer."
190 (buffer-substring-no-properties (minibuffer-prompt-end minibuf) (zv minibuf) minibuf))
192 (defun minibuffer-completion-contents (&optional (minibuf (current-buffer)))
193 "Return the user input in a minibuffer before point as a string.
194 That is what completion commands operate on.
195 The current buffer must be a minibuffer."
196 ;; FIXME: the emacs source produces an error when the pt is not at
197 ;; the end. I Don't know why, though.
198 (buffer-substring (minibuffer-prompt-end minibuf) (zv minibuf) minibuf))
200 (defun delete-minibuffer-contents (&optional (minibuf (current-buffer)))
201 "Delete all user input in a minibuffer.
202 MINIBUF must be a minibuffer."
203 (let ((end (minibuffer-prompt-end minibuf)))
204 (when (< end (zv minibuf))
205 (delete-region end (zv minibuf)))))
207 (defun setup-minibuffer-for-read (major-mode prompt initial-contents history)
208 (save-window-excursion
209 ;; Create a new minibuffer
210 (let* ((frame (selected-frame))
211 (*minibuffer-history-variable* history)
212 (*minibuffer-history-position* 0)
213 (*minibuffer-text-before-history* nil)
214 (old-minibuffer (window-buffer (frame-minibuffer-window frame)))
215 (new-minibuffer (make-minibuffer major-mode)))
216 (window-save-point (get-current-window))
217 ;; attach it to the current frame
218 (set-window-buffer (frame-minibuffer-window frame) new-minibuffer)
219 (select-window (frame-minibuffer-window frame))
220 ;; Show the prompt
221 (show-minibuffer-prompt frame prompt)
222 ;; move to the end of input
223 (setf (marker-position (buffer-point new-minibuffer)) (buffer-size new-minibuffer))
224 (when initial-contents (insert initial-contents))
225 ;; enter recursive edit
226 (dformat +debug-v+ "ya ohoe~%")
227 (incf (frame-minibuffers-active frame))
228 (unwind-protect
229 (progn
230 (recursive-edit)
231 (let* ((val (minibuffer-contents new-minibuffer))
232 (hist-string (when (> (length val) 0)
233 val)))
234 (when (and *minibuffer-history-variable* hist-string)
235 (let ((hist-val (symbol-value *minibuffer-history-variable*)))
236 ;; If the caller wanted to save the value read on a history list,
237 ;; then do so if the value is not already the front of the list.
238 (when (or (null hist-val)
239 (and (consp hist-val)
240 (not (equal hist-string (car hist-val)))))
241 (push hist-string hist-val)
242 (setf (symbol-value *minibuffer-history-variable*) hist-val))
243 ;; truncate if requested
244 (let ((len (or (get *minibuffer-history-variable* :history-length)
245 *history-length*)))
246 (when (integerp len)
247 (if (< len 0)
248 (setf (symbol-value *minibuffer-history-variable*) nil)
249 (let ((tmp (nthcdr len hist-val)))
250 (when tmp
251 (rplacd tmp nil))))))))
252 ;; return the value
253 val))
254 ;; Restore the buffer
255 (dformat +debug-v+ "minibuffer~%")
256 (set-window-buffer (frame-minibuffer-window frame) old-minibuffer)
257 (kill-buffer new-minibuffer)
258 (decf (frame-minibuffers-active frame))))))
260 (defun test-completion (string alist &optional predicate)
261 "Return non-nil if string is a valid completion.
262 Takes the same arguments as `all-completions' and `try-completion'.
263 If alist is a function, it is called with three arguments:
264 the values string, predicate and `lambda'."
265 (let ((matches (all-completions string alist predicate)))
266 (and (= (length matches) 1)
267 (string= (first matches) string))))
269 (defcommand minibuffer-complete-and-exit ()
270 "If the minibuffer contents is a valid completion then exit.
271 Otherwise try to complete it. If completion leads to a valid completion,
272 a repetition of this command will exit."
273 (let ((str (minibuffer-contents)))
274 (if (test-completion str *minibuffer-completion-table* *minibuffer-completion-predicate*)
275 (throw 'exit nil)
276 (minibuffer-complete))))
279 (defun read-from-minibuffer (prompt &key initial-contents keymap read (history '*minibuffer-history*) default-value)
280 "Read a string from the minibuffer, prompting with string PROMPT.
281 The optional second arg INITIAL-CONTENTS is an obsolete alternative to
282 DEFAULT-VALUE. It normally should be nil in new code, except when
283 HISTORY is a cons. It is discussed in more detail below.
284 Third arg KEYMAP is a keymap to use whilst reading;
285 if omitted or nil, the default is `minibuffer-local-map'.
286 If fourth arg READ is non-nil, then interpret the result as a Lisp object
287 and return that object:
288 in other words, do `(car (read-from-string INPUT-STRING))'
289 Fifth arg HISTORY, if non-nil, specifies a history list and optionally
290 the initial position in the list. It can be a symbol, which is the
291 history list variable to use, or it can be a cons cell
292 (HISTVAR . HISTPOS). In that case, HISTVAR is the history list variable
293 to use, and HISTPOS is the initial position for use by the minibuffer
294 history commands. For consistency, you should also specify that
295 element of the history as the value of INITIAL-CONTENTS. Positions
296 are counted starting from 1 at the beginning of the list.
297 Sixth arg DEFAULT-VALUE is the default value. If non-nil, it is available
298 for history commands; but, unless READ is non-nil, `read-from-minibuffer'
299 does NOT return DEFAULT-VALUE if the user enters empty input! It returns
300 the empty string.
301 Seventh arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
302 the current input method and the setting of `enable-multibyte-characters'.
303 Eight arg KEEP-ALL, if non-nil, says to put all inputs in the history list,
304 even empty or duplicate inputs.
305 If the variable `minibuffer-allow-text-properties' is non-nil,
306 then the string which is returned includes whatever text properties
307 were present in the minibuffer. Otherwise the value has no text properties.
309 The remainder of this documentation string describes the
310 INITIAL-CONTENTS argument in more detail. It is only relevant when
311 studying existing code, or when HISTORY is a cons. If non-nil,
312 INITIAL-CONTENTS is a string to be inserted into the minibuffer before
313 reading input. Normally, point is put at the end of that string.
314 However, if INITIAL-CONTENTS is \(STRING . POSITION), the initial
315 input is STRING, but point is placed at _one-indexed_ position
316 POSITION in the minibuffer. Any integer value less than or equal to
317 one puts point at the beginning of the string. *Note* that this
318 behavior differs from the way such arguments are used in `completing-read'
319 and some related functions, which use zero-indexing for POSITION."
320 (declare (ignore default-value read keymap))
321 (setup-minibuffer-for-read *minibuffer-read-mode* prompt initial-contents history))
323 (defun tree-find (tree obj &key (test #'eq))
324 "find OBJ in TREE. Return the OBJ or nil."
325 (cond ((typep tree obj)
326 (when (funcall test tree obj)
327 tree))
328 (t (or (tree-find (car tree) obj :test test)
329 (tree-find (cdr tree) obj :test test)))))
331 (defun tree-sibling (tree obj &key (test #'eq))
332 "Return the OBJ's sibling in tree or nil."
333 (declare (type (or list window) tree))
334 (cond ((typep tree obj)
335 nil)
336 ((funcall test obj (car tree))
337 (cdr tree))
338 ((funcall test obj (cdr tree))
339 (car tree))
340 (t (or (tree-sibling (car tree) obj :test test)
341 (tree-sibling (cdr tree) obj :test test)))))
343 (defun frame-for-window (window)
344 "Return the frame that holds WINDOW."
345 (find-if (lambda (f)
346 (tree-find (frame-window-tree f) window)) *frame-list*))
348 (defcommand ask-user ()
350 (message "user typed: ~a" (read-from-minibuffer "input: ")))
352 (defcommand exit-minibuffer ()
354 (dformat +debug-v+ "exit-minibuffer~%")
355 (throw 'exit nil))
357 (defcommand abort-recursive-edit ()
358 (throw 'exit t))
360 (defgeneric all-completions (string alist &optional predicate hide-spaces)
361 (:documentation "Return a list of possible matches."))
363 (defmethod all-completions (string (alist list) &optional predicate hide-spaces)
364 (declare (ignore hide-spaces))
365 (let ((tester (or predicate
366 (lambda (s)
367 (string= string s :end2 (min (length string)
368 (length s)))))))
369 (loop for elt in alist
370 for i = (cond ((consp elt)
371 (car elt))
372 ((symbolp elt)
373 ;; FIXME: this is a hack. isn't there a
374 ;; global that decides whether they're
375 ;; printed upcase or not?
376 (string-downcase (symbol-name elt)))
377 (t elt))
378 when (funcall tester i)
379 collect i)))
381 (defmethod all-completions (string (fn function) &optional predicate hide-spaces)
382 (declare (ignore hide-spaces))
383 (funcall fn string predicate nil))
385 (defun try-completion (string alist &optional predicate)
386 (labels ((all-are-good (match strings)
387 (loop for i in strings
388 never (string/= match i :end2 (min (length match)
389 (length i))))))
390 (let* ((possibles (all-completions string alist predicate))
391 (match (make-array 100 ; MOVITZ: the match can't be more than 100 chars
392 :element-type 'character
393 :fill-pointer 0
394 ;; :adjustable t
396 ;; FIXME: this dubplicates effort since the first (length string)
397 ;; chars will be the same.
398 (when possibles
399 (loop for i from 0 below (length (first possibles))
400 do (vector-push-extend (char (first possibles) i) match)
401 unless (all-are-good match possibles)
402 do (progn
403 (decf (fill-pointer match))
404 (return)))
405 match))))
407 (define-condition history-end (lice-condition)
408 () (:documentation "raised when at the end of the history"))
410 (define-condition history-beginning (lice-condition)
411 () (:documentation "raised when at the begining of the history"))
413 (defcommand next-history-element ((&optional n)
414 :prefix)
415 (let ((narg (- *minibuffer-history-position* n))
416 (minimum 0)
417 elt)
418 (when (and (zerop *minibuffer-history-position*)
419 (null *minibuffer-text-before-history*))
420 (setf *minibuffer-text-before-history*
421 (minibuffer-contents-no-properties)))
422 (when (< narg minimum)
423 (signal 'history-end #|"End of history; no next item"|#))
424 (when (> narg (length (symbol-value *minibuffer-history-variable*)))
425 (signal 'history-beginning #|"Beginning of history; no preceding item"|#))
426 (goto-char (point-max))
427 (delete-minibuffer-contents)
428 (setf *minibuffer-history-position* narg)
429 (cond ((= narg 0)
430 (setf elt (or *minibuffer-text-before-history* "")
431 *minibuffer-text-before-history* nil))
433 (setf elt (nth (1- *minibuffer-history-position*)
434 (symbol-value *minibuffer-history-variable*)))))
435 (insert
436 ;; (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
437 ;; (not minibuffer-returned-to-present))
438 ;; (let ((*print-level* nil))
439 ;; (prin1-to-string elt))
440 elt)
441 (goto-char (point-max))))
444 (defcommand previous-history-element ()
445 (next-history-element -1))
447 (defcommand minibuffer-complete ()
448 (let* ((txt (minibuffer-contents))
449 (match (try-completion txt *minibuffer-completion-table*)))
450 (dformat +debug-v+ "txt: ~a match: ~a~%" txt match)
451 (when match
452 (if (= (length match)
453 (length txt))
454 ;; no new text was added, so list the possibilities
455 (let* ((txt (minibuffer-contents))
456 (strings (all-completions txt *minibuffer-completion-table*)))
457 (with-current-buffer (get-buffer-create "*Completions*")
458 (erase-buffer)
459 (insert (format nil "Here are the completions.~%"))
460 (loop for c in strings
461 do (insert (format nil "~a~%" c)))
462 (goto-char (point-min))
463 (display-buffer (current-buffer))))
464 (progn
465 (goto-char (point-max))
466 (insert (subseq match (length txt))))))))
468 (defun completing-read (prompt table &key predicate require-match
469 initial-input (history '*minibuffer-history*) def)
470 "Read a string in the minibuffer, with completion.
471 PROMPT is a string to prompt with; normally it ends in a colon and a space.
472 TABLE is an alist whose elements' cars are strings, or an obarray.
473 TABLE can also be a function to do the completion itself.
474 PREDICATE limits completion to a subset of TABLE.
475 See `try-completion' and `all-completions' for more details
476 on completion, TABLE, and PREDICATE.
478 If REQUIRE-MATCH is non-nil, the user is not allowed to exit unless
479 the input is (or completes to) an element of TABLE or is null.
480 If it is also not t, Return does not exit if it does non-null completion.
481 If the input is null, `completing-read' returns an empty string,
482 regardless of the value of REQUIRE-MATCH.
484 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
485 If it is (STRING . POSITION), the initial input
486 is STRING, but point is placed POSITION characters into the string.
487 This feature is deprecated--it is best to pass nil for INITIAL.
488 HISTORY, if non-nil, specifies a history list
489 and optionally the initial position in the list.
490 It can be a symbol, which is the history list variable to use,
491 or it can be a cons cell (HISTVAR . HISTPOS).
492 In that case, HISTVAR is the history list variable to use,
493 and HISTPOS is the initial position (the position in the list
494 which INITIAL-INPUT corresponds to).
495 Positions are counted starting from 1 at the beginning of the list.
496 DEF, if non-nil, is the default value."
497 (declare (ignore def))
498 (let ((*minibuffer-completion-table* table)
499 (*minibuffer-completion-predicate* predicate))
500 (setup-minibuffer-for-read (if require-match
501 *minibuffer-must-match-mode*
502 *minibuffer-complete-mode*)
503 prompt initial-input history)))
505 ;; (defun y-or-n-p (prompt)
506 ;; "Ask user a \"y or n\" question. Return t if answer is \"y\".
507 ;; Takes one argument, which is the string to display to ask the question.
508 ;; It should end in a space; `y-or-n-p' adds `(y or n) ' to it.
509 ;; No confirmation of the answer is requested; a single character is enough.
510 ;; Also accepts Space to mean yes, or Delete to mean no. (Actually, it uses
511 ;; the bindings in `query-replace-map'; see the documentation of that variable
512 ;; for more information. In this case, the useful bindings are `act', `skip',
513 ;; `recenter', and `quit'.)
515 ;; Under a windowing system a dialog box will be used if `last-nonmenu-event'
516 ;; is nil and `use-dialog-box' is non-nil."
517 ;; ;; FIXME: This needs to be redone when the ECHO AREA works.
518 ;; (string-equal "y" (read-from-minibuffer (concatenate 'string prompt "(y on n)"))))
520 (provide :lice-0.1/minibuffer)