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