Merge from emacs-24 branch
[bpt/emacs.git] / lisp / tmm.el
1 ;;; tmm.el --- text mode access to menu-bar
2
3 ;; Copyright (C) 1994-1996, 2000-2012 Free Software Foundation, Inc.
4
5 ;; Author: Ilya Zakharevich <ilya@math.mps.ohio-state.edu>
6 ;; Maintainer: FSF
7 ;; Keywords: convenience
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; This package provides text mode access to the menu bar.
27
28 ;;; Code:
29
30 (require 'electric)
31
32 (defgroup tmm nil
33 "Text mode access to menu-bar."
34 :prefix "tmm-"
35 :group 'menu)
36
37 ;;; The following will be localized, added only to pacify the compiler.
38 (defvar tmm-short-cuts)
39 (defvar tmm-old-mb-map nil)
40 (defvar tmm-c-prompt nil)
41 (defvar tmm-km-list)
42 (defvar tmm-next-shortcut-digit)
43 (defvar tmm-table-undef)
44
45 ;;;###autoload (define-key global-map "\M-`" 'tmm-menubar)
46 ;;;###autoload (define-key global-map [menu-bar mouse-1] 'tmm-menubar-mouse)
47
48 ;;;###autoload
49 (defun tmm-menubar (&optional x-position)
50 "Text-mode emulation of looking and choosing from a menubar.
51 See the documentation for `tmm-prompt'.
52 X-POSITION, if non-nil, specifies a horizontal position within the menu bar;
53 we make that menu bar item (the one at that position) the default choice."
54 (interactive)
55 (run-hooks 'menu-bar-update-hook)
56 ;; Obey menu-bar-final-items; put those items last.
57 (let ((menu-bar (tmm-get-keybind [menu-bar]))
58 menu-bar-item)
59 (let ((list menu-bar-final-items))
60 (while list
61 (let ((item (car list)))
62 ;; ITEM is the name of an item that we want to put last.
63 ;; Find it in MENU-BAR and move it to the end.
64 (let ((this-one (assq item menu-bar)))
65 (setq menu-bar (append (delq this-one menu-bar)
66 (list this-one)))))
67 (setq list (cdr list))))
68 (if x-position
69 (let ((tail menu-bar) (column 0)
70 this-one name visible)
71 (while (and tail (<= column x-position))
72 (setq this-one (car tail))
73 (if (and (consp this-one)
74 (consp (cdr this-one))
75 (setq name ;simple menu
76 (cond ((stringp (nth 1 this-one))
77 (nth 1 this-one))
78 ;extended menu
79 ((stringp (nth 2 this-one))
80 (setq visible (plist-get
81 (nthcdr 4 this-one) :visible))
82 (unless (and visible (not (eval visible)))
83 (nth 2 this-one))))))
84 (setq column (+ column (length name) 1)))
85 (setq tail (cdr tail)))
86 (setq menu-bar-item (car this-one))))
87 (tmm-prompt menu-bar nil menu-bar-item)))
88
89 ;;;###autoload
90 (defun tmm-menubar-mouse (event)
91 "Text-mode emulation of looking and choosing from a menubar.
92 This command is used when you click the mouse in the menubar
93 on a console which has no window system but does have a mouse.
94 See the documentation for `tmm-prompt'."
95 (interactive "e")
96 (tmm-menubar (car (posn-x-y (event-start event)))))
97
98 (defcustom tmm-mid-prompt "==>"
99 "String to insert between shortcut and menu item.
100 If nil, there will be no shortcuts. It should not consist only of spaces,
101 or else the correct item might not be found in the `*Completions*' buffer."
102 :type 'string
103 :group 'tmm)
104
105 (defvar tmm-mb-map nil
106 "A place to store minibuffer map.")
107
108 (defcustom tmm-completion-prompt
109 "Press PageUp key to reach this buffer from the minibuffer.
110 Alternatively, you can use Up/Down keys (or your History keys) to change
111 the item in the minibuffer, and press RET when you are done, or press the
112 marked letters to pick up your choice. Type C-g or ESC ESC ESC to cancel.
113 "
114 "Help text to insert on the top of the completion buffer.
115 To save space, you can set this to nil,
116 in which case the standard introduction text is deleted too."
117 :type '(choice string (const nil))
118 :group 'tmm)
119
120 (defcustom tmm-shortcut-style '(downcase upcase)
121 "What letters to use as menu shortcuts.
122 Must be either one of the symbols `downcase' or `upcase',
123 or else a list of the two in the order you prefer."
124 :type '(choice (const downcase)
125 (const upcase)
126 (repeat (choice (const downcase) (const upcase))))
127 :group 'tmm)
128
129 (defcustom tmm-shortcut-words 2
130 "How many successive words to try for shortcuts, nil means all.
131 If you use only one of `downcase' or `upcase' for `tmm-shortcut-style',
132 specify nil for this variable."
133 :type '(choice integer (const nil))
134 :group 'tmm)
135
136 (defface tmm-inactive
137 '((t :inherit shadow))
138 "Face used for inactive menu items."
139 :group 'tmm)
140
141 ;;;###autoload
142 (defun tmm-prompt (menu &optional in-popup default-item)
143 "Text-mode emulation of calling the bindings in keymap.
144 Creates a text-mode menu of possible choices. You can access the elements
145 in the menu in two ways:
146 *) via history mechanism from minibuffer;
147 *) Or via completion-buffer that is automatically shown.
148 The last alternative is currently a hack, you cannot use mouse reliably.
149
150 MENU is like the MENU argument to `x-popup-menu': either a
151 keymap or an alist of alists.
152 DEFAULT-ITEM, if non-nil, specifies an initial default choice.
153 Its value should be an event that has a binding in MENU."
154 ;; If the optional argument IN-POPUP is t,
155 ;; then MENU is an alist of elements of the form (STRING . VALUE).
156 ;; That is used for recursive calls only.
157 (let ((gl-str "Menu bar") ;; The menu bar itself is not a menu keymap
158 ; so it doesn't have a name.
159 tmm-km-list out history history-len tmm-table-undef tmm-c-prompt
160 tmm-old-mb-map tmm-short-cuts
161 chosen-string choice
162 (not-menu (not (keymapp menu))))
163 (run-hooks 'activate-menubar-hook)
164 ;; Compute tmm-km-list from MENU.
165 ;; tmm-km-list is an alist of (STRING . MEANING).
166 ;; It has no other elements.
167 ;; The order of elements in tmm-km-list is the order of the menu bar.
168 (dolist (elt menu)
169 (cond
170 ((stringp elt) (setq gl-str elt))
171 ((listp elt) (tmm-get-keymap elt not-menu))
172 ((vectorp elt)
173 (dotimes (i (length elt))
174 (tmm-get-keymap (cons i (aref elt i)) not-menu)))))
175 ;; Choose an element of tmm-km-list; put it in choice.
176 (if (and not-menu (= 1 (length tmm-km-list)))
177 ;; If this is the top-level of an x-popup-menu menu,
178 ;; and there is just one pane, choose that one silently.
179 ;; This way we only ask the user one question,
180 ;; for which element of that pane.
181 (setq choice (cdr (car tmm-km-list)))
182 (unless tmm-km-list
183 (error "Empty menu reached"))
184 (and tmm-km-list
185 (let ((index-of-default 0))
186 (if tmm-mid-prompt
187 (setq tmm-km-list (tmm-add-shortcuts tmm-km-list))
188 t)
189 ;; Find the default item's index within the menu bar.
190 ;; We use this to decide the initial minibuffer contents
191 ;; and initial history position.
192 (if default-item
193 (let ((tail menu) visible)
194 (while (and tail
195 (not (eq (car-safe (car tail)) default-item)))
196 ;; Be careful to count only the elements of MENU
197 ;; that actually constitute menu bar items.
198 (if (and (consp (car tail))
199 (or (stringp (car-safe (cdr (car tail))))
200 (and
201 (eq (car-safe (cdr (car tail))) 'menu-item)
202 (progn
203 (setq visible
204 (plist-get
205 (nthcdr 4 (car tail)) :visible))
206 (or (not visible) (eval visible))))))
207 (setq index-of-default (1+ index-of-default)))
208 (setq tail (cdr tail)))))
209 (let ((prompt (concat "^." (regexp-quote tmm-mid-prompt))))
210 (setq history
211 (reverse (delq nil
212 (mapcar
213 (lambda (elt)
214 (if (string-match prompt (car elt))
215 (car elt)))
216 tmm-km-list)))))
217 (setq history-len (length history))
218 (setq history (append history history history history))
219 (setq tmm-c-prompt (nth (- history-len 1 index-of-default) history))
220 (setq out
221 (if default-item
222 (car (nth index-of-default tmm-km-list))
223 (minibuffer-with-setup-hook #'tmm-add-prompt
224 (completing-read
225 (concat gl-str
226 " (up/down to change, PgUp to menu): ")
227 tmm-km-list nil t nil
228 (cons 'history
229 (- (* 2 history-len) index-of-default))))))))
230 (setq choice (cdr (assoc out tmm-km-list)))
231 (and (null choice)
232 (> (length out) (length tmm-c-prompt))
233 (string= (substring out 0 (length tmm-c-prompt)) tmm-c-prompt)
234 (setq out (substring out (length tmm-c-prompt))
235 choice (cdr (assoc out tmm-km-list))))
236 (and (null choice) out
237 (setq out (try-completion out tmm-km-list)
238 choice (cdr (assoc out tmm-km-list)))))
239 ;; CHOICE is now (STRING . MEANING). Separate the two parts.
240 (setq chosen-string (car choice))
241 (setq choice (cdr choice))
242 (cond (in-popup
243 ;; We just did the inner level of a -popup menu.
244 choice)
245 ;; We just did the outer level. Do the inner level now.
246 (not-menu (tmm-prompt choice t))
247 ;; We just handled a menu keymap and found another keymap.
248 ((keymapp choice)
249 (if (symbolp choice)
250 (setq choice (indirect-function choice)))
251 (condition-case nil
252 (require 'mouse)
253 (error nil))
254 (tmm-prompt choice))
255 ;; We just handled a menu keymap and found a command.
256 (choice
257 (if chosen-string
258 (progn
259 (setq last-command-event chosen-string)
260 (call-interactively choice))
261 choice)))))
262
263 (defun tmm-add-shortcuts (list)
264 "Add shortcuts to cars of elements of the list.
265 Takes a list of lists with a string as car, returns list with
266 shortcuts added to these cars.
267 Stores a list of all the shortcuts in the free variable `tmm-short-cuts'."
268 (let ((tmm-next-shortcut-digit ?0))
269 (mapcar 'tmm-add-one-shortcut (reverse list))))
270
271 (defsubst tmm-add-one-shortcut (elt)
272 ;; uses the free vars tmm-next-shortcut-digit and tmm-short-cuts
273 (cond
274 ((eq (cddr elt) 'ignore)
275 (cons (concat " " (make-string (length tmm-mid-prompt) ?\-)
276 (car elt))
277 (cdr elt)))
278 (t
279 (let* ((str (car elt))
280 (paren (string-match "(" str))
281 (pos 0) (word 0) char)
282 (catch 'done ; ??? is this slow?
283 (while (and (or (not tmm-shortcut-words) ; no limit on words
284 (< word tmm-shortcut-words)) ; try n words
285 (setq pos (string-match "\\w+" str pos)) ; get next word
286 (not (and paren (> pos paren)))) ; don't go past "(binding.."
287 (if (or (= pos 0)
288 (/= (aref str (1- pos)) ?.)) ; avoid file extensions
289 (let ((shortcut-style
290 (if (listp tmm-shortcut-style) ; convert to list
291 tmm-shortcut-style
292 (list tmm-shortcut-style))))
293 (while shortcut-style ; try upcase and downcase variants
294 (setq char (funcall (car shortcut-style) (aref str pos)))
295 (if (not (memq char tmm-short-cuts)) (throw 'done char))
296 (setq shortcut-style (cdr shortcut-style)))))
297 (setq word (1+ word))
298 (setq pos (match-end 0)))
299 (while (<= tmm-next-shortcut-digit ?9) ; no letter shortcut, pick a digit
300 (setq char tmm-next-shortcut-digit)
301 (setq tmm-next-shortcut-digit (1+ tmm-next-shortcut-digit))
302 (if (not (memq char tmm-short-cuts)) (throw 'done char)))
303 (setq char nil))
304 (if char (setq tmm-short-cuts (cons char tmm-short-cuts)))
305 (cons (concat (if char (concat (char-to-string char) tmm-mid-prompt)
306 ;; keep them lined up in columns
307 (make-string (1+ (length tmm-mid-prompt)) ?\s))
308 str)
309 (cdr elt))))))
310
311 ;; This returns the old map.
312 (defun tmm-define-keys (minibuffer)
313 (let ((map (make-sparse-keymap)))
314 (suppress-keymap map t)
315 (dolist (c tmm-short-cuts)
316 (if (listp tmm-shortcut-style)
317 (define-key map (char-to-string c) 'tmm-shortcut)
318 ;; only one kind of letters are shortcuts, so map both upcase and
319 ;; downcase input to the same
320 (define-key map (char-to-string (downcase c)) 'tmm-shortcut)
321 (define-key map (char-to-string (upcase c)) 'tmm-shortcut)))
322 (if minibuffer
323 (progn
324 (define-key map [pageup] 'tmm-goto-completions)
325 (define-key map [prior] 'tmm-goto-completions)
326 (define-key map "\ev" 'tmm-goto-completions)
327 (define-key map "\C-n" 'next-history-element)
328 (define-key map "\C-p" 'previous-history-element)))
329 (prog1 (current-local-map)
330 (use-local-map (append map (current-local-map))))))
331
332 (defun tmm-completion-delete-prompt ()
333 (set-buffer standard-output)
334 (goto-char (point-min))
335 (delete-region (point) (search-forward "Possible completions are:\n")))
336
337 (defun tmm-remove-inactive-mouse-face ()
338 "Remove the mouse-face property from inactive menu items."
339 (let ((inhibit-read-only t)
340 (inactive-string
341 (concat " " (make-string (length tmm-mid-prompt) ?\-)))
342 next)
343 (save-excursion
344 (goto-char (point-min))
345 (while (not (eobp))
346 (setq next (next-single-char-property-change (point) 'mouse-face))
347 (when (looking-at inactive-string)
348 (remove-text-properties (point) next '(mouse-face))
349 (add-text-properties (point) next '(face tmm-inactive)))
350 (goto-char next)))
351 (set-buffer-modified-p nil)))
352
353 (defun tmm-add-prompt ()
354 (add-hook 'minibuffer-exit-hook 'tmm-delete-map nil t)
355 (unless tmm-c-prompt
356 (error "No active menu entries"))
357 (setq tmm-old-mb-map (tmm-define-keys t))
358 ;; Get window and hide it for electric mode to get correct size
359 (save-window-excursion
360 (let ((completions
361 (mapcar 'car minibuffer-completion-table)))
362 (or tmm-completion-prompt
363 (add-hook 'completion-setup-hook
364 'tmm-completion-delete-prompt 'append))
365 (unwind-protect
366 (with-output-to-temp-buffer "*Completions*"
367 (display-completion-list completions))
368 (remove-hook 'completion-setup-hook 'tmm-completion-delete-prompt)))
369 (set-buffer "*Completions*")
370 (tmm-remove-inactive-mouse-face)
371 (when tmm-completion-prompt
372 (let ((buffer-read-only nil))
373 (goto-char (point-min))
374 (insert tmm-completion-prompt))))
375 (save-selected-window
376 (other-window 1) ; Electric-pop-up-window does
377 ; not work in minibuffer
378 (Electric-pop-up-window "*Completions*"))
379 (insert tmm-c-prompt))
380
381 (defun tmm-delete-map ()
382 (remove-hook 'minibuffer-exit-hook 'tmm-delete-map t)
383 (if tmm-old-mb-map
384 (use-local-map tmm-old-mb-map)))
385
386 (defun tmm-shortcut ()
387 "Choose the shortcut that the user typed."
388 (interactive)
389 (let ((c last-command-event) s)
390 (if (symbolp tmm-shortcut-style)
391 (setq c (funcall tmm-shortcut-style c)))
392 (if (memq c tmm-short-cuts)
393 (if (equal (buffer-name) "*Completions*")
394 (progn
395 (goto-char (point-min))
396 (re-search-forward
397 (concat "\\(^\\|[ \t]\\)" (char-to-string c) tmm-mid-prompt))
398 (choose-completion))
399 ;; In minibuffer
400 (delete-region (minibuffer-prompt-end) (point-max))
401 (dolist (elt tmm-km-list)
402 (if (string=
403 (substring (car elt) 0
404 (min (1+ (length tmm-mid-prompt))
405 (length (car elt))))
406 (concat (char-to-string c) tmm-mid-prompt))
407 (setq s (car elt))))
408 (insert s)
409 (exit-minibuffer)))))
410
411 (defun tmm-goto-completions ()
412 "Jump to the completions buffer."
413 (interactive)
414 (let ((prompt-end (minibuffer-prompt-end)))
415 (setq tmm-c-prompt (buffer-substring prompt-end (point-max)))
416 ;; FIXME: Why?
417 (delete-region prompt-end (point-max)))
418 (switch-to-buffer-other-window "*Completions*")
419 (search-forward tmm-c-prompt)
420 (search-backward tmm-c-prompt))
421
422 (defun tmm-get-keymap (elt &optional in-x-menu)
423 "Prepend (DOCSTRING EVENT BINDING) to free variable `tmm-km-list'.
424 The values are deduced from the argument ELT, that should be an
425 element of keymap, an `x-popup-menu' argument, or an element of
426 `x-popup-menu' argument (when IN-X-MENU is not-nil).
427 This function adds the element only if it is not already present.
428 It uses the free variable `tmm-table-undef' to keep undefined keys."
429 (let (km str plist filter visible enable (event (car elt)))
430 (setq elt (cdr elt))
431 (if (eq elt 'undefined)
432 (setq tmm-table-undef (cons (cons event nil) tmm-table-undef))
433 (unless (assoc event tmm-table-undef)
434 (cond ((if (listp elt)
435 (or (keymapp elt) (eq (car elt) 'lambda))
436 (and (symbolp elt) (fboundp elt)))
437 (setq km elt))
438
439 ((if (listp (cdr-safe elt))
440 (or (keymapp (cdr-safe elt))
441 (eq (car (cdr-safe elt)) 'lambda))
442 (and (symbolp (cdr-safe elt)) (fboundp (cdr-safe elt))))
443 (setq km (cdr elt))
444 (and (stringp (car elt)) (setq str (car elt))))
445
446 ((if (listp (cdr-safe (cdr-safe elt)))
447 (or (keymapp (cdr-safe (cdr-safe elt)))
448 (eq (car (cdr-safe (cdr-safe elt))) 'lambda))
449 (and (symbolp (cdr-safe (cdr-safe elt)))
450 (fboundp (cdr-safe (cdr-safe elt)))))
451 (setq km (cddr elt))
452 (and (stringp (car elt)) (setq str (car elt))))
453
454 ((eq (car-safe elt) 'menu-item)
455 ;; (menu-item TITLE COMMAND KEY ...)
456 (setq plist (cdr-safe (cdr-safe (cdr-safe elt))))
457 (when (consp (car-safe plist))
458 (setq plist (cdr-safe plist)))
459 (setq km (nth 2 elt))
460 (setq str (eval (nth 1 elt)))
461 (setq filter (plist-get plist :filter))
462 (if filter
463 (setq km (funcall filter km)))
464 (setq visible (plist-get plist :visible))
465 (if visible
466 (setq km (and (eval visible) km)))
467 (setq enable (plist-get plist :enable))
468 (if enable
469 (setq km (if (eval enable) km 'ignore))))
470
471 ((if (listp (cdr-safe (cdr-safe (cdr-safe elt))))
472 (or (keymapp (cdr-safe (cdr-safe (cdr-safe elt))))
473 (eq (car (cdr-safe (cdr-safe (cdr-safe elt)))) 'lambda))
474 (and (symbolp (cdr-safe (cdr-safe (cdr-safe elt))))
475 (fboundp (cdr-safe (cdr-safe (cdr-safe elt))))))
476 ; New style of easy-menu
477 (setq km (cdr (cddr elt)))
478 (and (stringp (car elt)) (setq str (car elt))))
479
480 ((stringp event) ; x-popup or x-popup element
481 (if (or in-x-menu (stringp (car-safe elt)))
482 (setq str event event nil km elt)
483 (setq str event event nil km (cons 'keymap elt)))))
484 (unless (or (eq km 'ignore) (null str))
485 (let ((binding (where-is-internal km nil t)))
486 (when binding
487 (setq binding (key-description binding))
488 ;; Try to align the keybindings.
489 (let ((colwidth (min 30 (- (/ (window-width) 2) 10))))
490 (setq str
491 (concat str
492 (make-string (max 2 (- colwidth
493 (string-width str)
494 (string-width binding)))
495 ?\s)
496 binding)))))))
497 (and km (stringp km) (setq str km))
498 ;; Verify that the command is enabled;
499 ;; if not, don't mention it.
500 (when (and km (symbolp km) (get km 'menu-enable))
501 (setq km (if (eval (get km 'menu-enable)) km 'ignore)))
502 (and km str
503 (or (assoc str tmm-km-list)
504 (push (cons str (cons event km)) tmm-km-list))))))
505
506 (defun tmm-get-keybind (keyseq)
507 "Return the current binding of KEYSEQ, merging prefix definitions.
508 If KEYSEQ is a prefix key that has local and global bindings,
509 we merge them into a single keymap which shows the proper order of the menu.
510 However, for the menu bar itself, the value does not take account
511 of `menu-bar-final-items'."
512 (let (allbind bind minorbind localbind globalbind)
513 (setq bind (key-binding keyseq))
514 ;; If KEYSEQ is a prefix key, then BIND is either nil
515 ;; or a symbol defined as a keymap (which satisfies keymapp).
516 (if (keymapp bind)
517 (setq bind nil))
518 ;; If we have a non-keymap definition, return that.
519 (or bind
520 (progn
521 ;; Otherwise, it is a prefix, so make a list of the subcommands.
522 ;; Make a list of all the bindings in all the keymaps.
523 (setq minorbind (mapcar 'cdr (minor-mode-key-binding keyseq)))
524 (setq localbind (local-key-binding keyseq))
525 (setq globalbind (copy-sequence (cdr (global-key-binding keyseq))))
526
527 ;; If items have been redefined/undefined locally, remove them from
528 ;; the global list.
529 (dolist (minor minorbind)
530 (dolist (item (cdr minor))
531 (setq globalbind (assq-delete-all (car-safe item) globalbind))))
532 (dolist (item (cdr localbind))
533 (setq globalbind (assq-delete-all (car-safe item) globalbind)))
534
535 (setq globalbind (cons 'keymap globalbind))
536 (setq allbind (cons globalbind (cons localbind minorbind)))
537
538 ;; Merge all the elements of ALLBIND into one keymap.
539 (dolist (in allbind)
540 (if (and (symbolp in) (keymapp in))
541 (setq in (symbol-function in)))
542 (and in (keymapp in)
543 (setq bind (if (keymapp bind)
544 (nconc bind (copy-sequence (cdr in)))
545 (copy-sequence in)))))
546 ;; Return that keymap.
547 bind))))
548
549 (provide 'tmm)
550
551 ;;; tmm.el ends here