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