popup.el 53.6 KB
Newer Older
1
;;; popup.el --- Visual Popup User Interface
2

Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
3
;; Copyright (C) 2009-2015  Tomohiro Matsuyama
4

Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
5
;; Author: Tomohiro Matsuyama <m2ym.pub@gmail.com>
6
;; Keywords: lisp
7
;; Version: 0.5.3
8
;; Package-Requires: ((cl-lib "0.3"))
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
25 26 27 28
;; popup.el is a visual popup user interface library for Emacs. This
;; provides a basic API and common UI widgets such as popup tooltips
;; and popup menus.
;; See README.markdown for more information.
29 30 31

;;; Code:

32
(require 'cl-lib)
33

34
(defconst popup-version "0.5.3")
35

36 37


38
;;; Utilities
39

40 41 42 43 44 45 46
(defun popup-calculate-max-width (max-width)
  "Determines whether the width desired is
character or window proportion based, And returns the result."
  (cl-typecase max-width
    (integer max-width)
    (float (* (ceiling (/ (round (* max-width (window-width))) 10.0)) 10))))

47
(defvar popup-use-optimized-column-computation t
48 49
  "Use the optimized column computation routine.
If there is a problem, please set it nil.")
50

Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
51 52
(defmacro popup-aif (test then &rest else)
  "Anaphoric if."
53
  (declare (indent 2))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
54 55 56 57 58 59 60 61
  `(let ((it ,test))
     (if it ,then ,@else)))

(defmacro popup-awhen (test &rest body)
  "Anaphoric when."
  (declare (indent 1))
  `(let ((it ,test))
     (when it ,@body)))
62 63 64

(defun popup-x-to-string (x)
  "Convert any object to string effeciently.
65
This is faster than `prin1-to-string' in many cases."
66
  (cl-typecase x
67 68 69 70 71 72 73
    (string x)
    (symbol (symbol-name x))
    (integer (number-to-string x))
    (float (number-to-string x))
    (t (format "%s" x))))

(defun popup-substring-by-width (string width)
74 75 76
  "Return a cons cell of substring and remaining string by
splitting with WIDTH."
  ;; Expand tabs into 4 spaces
77
  (setq string (replace-regexp-in-string "\t" "    " string))
78 79 80 81
  (cl-loop with len = (length string)
           with w = 0
           for l from 0
           for c in (append string nil)
82
           while (<= (cl-incf w (char-width c)) width)
83 84 85 86
           finally return
           (if (< l len)
               (cons (substring string 0 l) (substring string l))
             (list string))))
87 88

(defun popup-fill-string (string &optional width max-width justify squeeze)
89 90 91
  "Split STRING into fixed width strings and return a cons cell
like \(WIDTH . ROWS). Here, the car WIDTH indicates the actual
maxim width of ROWS.
92

93 94 95 96
The argument WIDTH specifies the width of filling each
paragraph. WIDTH nil means don't perform any justification and
word wrap. Note that this function doesn't add any padding
characters at the end of each row.
97

98 99
MAX-WIDTH, if WIDTH is nil, specifies the maximum number of
columns.
100

101 102 103 104
The optional fourth argument JUSTIFY specifies which kind of
justification to do: `full', `left', `right', `center', or
`none' (equivalent to nil).  A value of t means handle each
paragraph as specified by its text properties.
105

106 107
SQUEEZE nil means leave whitespaces other than line breaks
untouched."
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  (if (eq width 0)
      (error "Can't fill string with 0 width"))
  (if width
      (setq max-width width))
  (with-temp-buffer
    (let ((tab-width 4)
          (fill-column width)
          (left-margin 0)
          (kinsoku-limit 1)
          indent-tabs-mode
          row rows)
      (insert string)
      (untabify (point-min) (point-max))
      (if width
          (fill-region (point-min) (point-max) justify (not squeeze)))
      (goto-char (point-min))
      (setq width 0)
      (while (prog2
                 (let ((line (buffer-substring
                              (point) (progn (end-of-line) (point)))))
                   (if max-width
                       (while (progn
                                (setq row (truncate-string-to-width line max-width)
                                      width (max width (string-width row)))
                                (push row rows)
                                (if (not (= (length row) (length line)))
                                    (setq line (substring line (length row))))))
                     (setq width (max width (string-width line)))
                     (push line rows)))
                 (< (point) (point-max))
               (beginning-of-line 2)))
      (cons width (nreverse rows)))))

(defmacro popup-save-buffer-state (&rest body)
  (declare (indent 0))
  `(save-excursion
     (let ((buffer-undo-list t)
145
           (inhibit-read-only t)
146 147 148 149 150
           (modified (buffer-modified-p)))
       (unwind-protect
           (progn ,@body)
         (set-buffer-modified-p modified)))))

151 152 153 154 155 156 157
(defun popup-vertical-motion (column direction)
  "A portable version of `vertical-motion'."
  (if (>= emacs-major-version 23)
      (vertical-motion (cons column direction))
    (vertical-motion direction)
    (move-to-column (+ (current-column) column))))

158
(defun popup-last-line-of-buffer-p ()
159 160
  "Return non-nil if the cursor is at the last line of the
buffer."
161 162 163 164 165 166
  (save-excursion (end-of-line) (/= (forward-line) 0)))

(defun popup-lookup-key-by-event (function event)
  (or (funcall function (vector event))
      (if (symbolp event)
          (popup-aif (get event 'event-symbol-element-mask)
167 168 169 170
              (funcall function
                       (vector (logior (or (get (car it) 'ascii-character)
                                           0)
                                       (cadr it))))))))
171 172 173



174
;;; Core
175 176

(defgroup popup nil
177
  "Visual Popup User Interface"
178 179 180 181 182 183 184 185
  :group 'lisp
  :prefix "popup-")

(defface popup-face
  '((t (:background "lightgray" :foreground "black")))
  "Face for popup."
  :group 'popup)

186
(defface popup-summary-face
187
  '((t (:inherit popup-face :foreground "dimgray")))
188 189 190
  "Face for popup summary."
  :group 'popup)

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
(defface popup-scroll-bar-foreground-face
  '((t (:background "black")))
  "Foreground face for scroll-bar."
  :group 'popup)

(defface popup-scroll-bar-background-face
  '((t (:background "gray")))
  "Background face for scroll-bar."
  :group 'popup)

(defvar popup-instances nil
  "Popup instances.")

(defvar popup-scroll-bar-foreground-char
  (propertize " " 'face 'popup-scroll-bar-foreground-face)
  "Foreground character for scroll-bar.")

(defvar popup-scroll-bar-background-char
  (propertize " " 'face 'popup-scroll-bar-background-face)
  "Background character for scroll-bar.")

212
(cl-defstruct popup
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
213
  point row column width height min-height direction overlays keymap
214
  parent depth
215
  face mouse-face selection-face summary-face
216
  margin-left margin-right margin-left-cancel scroll-bar symbol
217
  cursor offset scroll-top current-height list newlines
TAKAGI Kentaro's avatar
TAKAGI Kentaro committed
218
  pattern original-list invis-overlays)
219 220

(defun popup-item-propertize (item &rest properties)
221 222
  "Same as `propertize' except that this avoids overriding
existed value with `nil' property."
223 224 225 226 227 228
  (cl-loop for (k v) on properties by 'cddr
           if v append (list k v) into props
           finally return
           (apply 'propertize
                  (popup-x-to-string item)
                  props)))
229 230

(defun popup-item-property (item property)
231 232
  "Same as `get-text-property' except that this returns nil if
ITEM is not string."
233 234 235
  (if (stringp item)
      (get-text-property 0 property item)))

236 237 238 239 240 241 242 243 244 245
(cl-defun popup-make-item (name
                           &key
                           value
                           face
                           mouse-face
                           selection-face
                           sublist
                           document
                           symbol
                           summary)
246 247
  "Utility function to make popup item. See also
`popup-item-propertize'."
248 249
  (popup-item-propertize name
                         'value value
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
250 251
                         'popup-face face
                         'popup-mouse-face mouse-face
252 253 254 255 256 257 258 259
                         'selection-face selection-face
                         'document document
                         'symbol symbol
                         'summary summary
                         'sublist sublist))

(defsubst popup-item-value (item)               (popup-item-property item 'value))
(defsubst popup-item-value-or-self (item)       (or (popup-item-value item) item))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
260 261
(defsubst popup-item-face (item)                (popup-item-property item 'popup-face))
(defsubst popup-item-mouse-face (item)          (popup-item-property item 'popup-mouse-face))
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
(defsubst popup-item-selection-face (item)      (popup-item-property item 'selection-face))
(defsubst popup-item-document (item)            (popup-item-property item 'document))
(defsubst popup-item-summary (item)             (popup-item-property item 'summary))
(defsubst popup-item-symbol (item)              (popup-item-property item 'symbol))
(defsubst popup-item-sublist (item)             (popup-item-property item 'sublist))

(defun popup-item-documentation (item)
  (let ((doc (popup-item-document item)))
    (if (functionp doc)
        (setq doc (funcall doc (popup-item-value-or-self item))))
    doc))

(defun popup-item-show-help-1 (item)
  (let ((doc (popup-item-documentation item)))
    (when doc
      (with-current-buffer (get-buffer-create " *Popup Help*")
        (erase-buffer)
        (insert doc)
        (goto-char (point-min))
        (display-buffer (current-buffer)))
      t)))

284 285 286
(defun popup-item-show-help-with-event-loop (item)
  (save-window-excursion
    (when (popup-item-show-help-1 item)
287 288 289
      (cl-loop do (clear-this-command-keys)
               for key = (read-key-sequence-vector nil)
               do
290 291
               (cl-case (key-binding key)
                 (scroll-other-window
292
                  (scroll-other-window))
293
                 (scroll-other-window-down
294
                  (scroll-other-window-down nil))
295
                 (otherwise
296
                  (setq unread-command-events (append key unread-command-events))
297
                  (cl-return)))))))
298

299
(defun popup-item-show-help (item &optional persist)
300 301 302 303 304
  "Display the documentation of ITEM with `display-buffer'. If
PERSIST is nil, the documentation buffer will be closed
automatically, meaning interal event loop ensures the buffer to
be closed. Otherwise, the buffer will be just displayed as
usual."
305 306
  (when item
    (if (not persist)
307
        (popup-item-show-help-with-event-loop item)
308 309 310 311 312 313
      (popup-item-show-help-1 item))))

(defun popup-set-list (popup list)
  (popup-set-filtered-list popup list)
  (setf (popup-pattern popup) nil)
  (setf (popup-original-list popup) list))
314

315
(defun popup-set-filtered-list (popup list)
316 317 318 319 320 321
  (let ((offset
         (if (> (popup-direction popup) 0)
             0
           (max (- (popup-height popup) (length list)) 0))))
    (setf (popup-list popup) list
          (popup-offset popup) offset)))
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

(defun popup-selected-item (popup)
  (nth (popup-cursor popup) (popup-list popup)))

(defun popup-selected-line (popup)
  (- (popup-cursor popup) (popup-scroll-top popup)))

(defun popup-line-overlay (popup line)
  (aref (popup-overlays popup) line))

(defun popup-selected-line-overlay (popup)
  (popup-line-overlay popup (popup-selected-line popup)))

(defun popup-hide-line (popup line)
  (let ((overlay (popup-line-overlay popup line)))
    (overlay-put overlay 'display nil)
    (overlay-put overlay 'after-string nil)))

(defun popup-line-hidden-p (popup line)
  (let ((overlay (popup-line-overlay popup line)))
    (and (eq (overlay-get overlay 'display) nil)
         (eq (overlay-get overlay 'after-string) nil))))

345 346 347 348 349 350 351 352 353 354 355 356 357
(cl-defun popup-set-line-item (popup
                               line
                               &key
                               item
                               face
                               mouse-face
                               margin-left
                               margin-right
                               scroll-bar-char
                               symbol
                               summary
                               summary-face
                               keymap)
358
  (let* ((overlay (popup-line-overlay popup line))
359 360 361 362
         (content (popup-create-line-string popup (popup-x-to-string item)
                                            :margin-left margin-left
                                            :margin-right margin-right
                                            :symbol symbol
363 364
                                            :summary summary
                                            :summary-face summary-face))
365 366 367 368
         (start 0)
         (prefix (overlay-get overlay 'prefix))
         (postfix (overlay-get overlay 'postfix))
         end)
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
369 370
    (put-text-property 0 (length content) 'popup-item item content)
    (put-text-property 0 (length content) 'keymap keymap content)
371
    ;; Overlap face properties
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
372 373
    (when (get-text-property start 'face content)
      (setq start (next-single-property-change start 'face content)))
374 375 376
    (while (and start (setq end (next-single-property-change start 'face content)))
      (put-text-property start end 'face face content)
      (setq start (next-single-property-change end 'face content)))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
377 378 379 380
    (when start
      (put-text-property start (length content) 'face face content))
    (when mouse-face
      (put-text-property 0 (length content) 'mouse-face mouse-face content))
381 382 383 384 385 386 387 388 389
    (let ((prop (if (overlay-get overlay 'dangle)
                    'after-string
                  'display)))
      (overlay-put overlay
                   prop
                   (concat prefix
                           content
                           scroll-bar-char
                           postfix)))))
390

391 392 393 394 395 396 397 398
(cl-defun popup-create-line-string (popup
                                    string
                                    &key
                                    margin-left
                                    margin-right
                                    symbol
                                    summary
                                    summary-face)
399 400
  (let* ((popup-width (popup-width popup))
         (summary-width (string-width summary))
401 402 403 404 405 406
         (content-width (max
                         (min popup-width (string-width string))
                         (- popup-width
                            (if (> summary-width 0)
                                (+ summary-width 2)
                              0))))
407 408
         (string (car (popup-substring-by-width string content-width)))
         (string-width (string-width string))
409
         (spacing (max (- popup-width string-width summary-width)
410 411 412 413
                       (if (> popup-width string-width) 1 0)))
         (truncated-summary
          (car (popup-substring-by-width
                summary (max (- popup-width string-width spacing) 0)))))
414 415 416
    (when summary-face
      (put-text-property 0 (length truncated-summary)
                         'face summary-face truncated-summary))
417 418
    (concat margin-left
            string
419
            (make-string spacing ? )
420
            truncated-summary
421 422 423 424
            symbol
            margin-right)))

(defun popup-live-p (popup)
425
  "Return non-nil if POPUP is alive."
426 427 428
  (and popup (popup-overlays popup) t))

(defun popup-child-point (popup &optional offset)
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
  (overlay-end
   (popup-line-overlay
    popup
    (or offset
        (popup-selected-line popup)))))

(defun popup-calculate-direction (height row)
  "Return a proper direction when displaying a popup on this
window. HEIGHT is the a height of the popup, and ROW is a line
number at the point."
  (let* ((remaining-rows (- (max 1 (- (window-height)
                                      (if mode-line-format 1 0)
                                      (if header-line-format 1 0)))
                            (count-lines (window-start) (point))))
         (enough-space-above (> row height))
         (enough-space-below (<= height remaining-rows)))
    (if (and enough-space-above
             (not enough-space-below))
        -1
      1)))
449

450 451 452 453 454
(cl-defun popup-create (point
                        width
                        height
                        &key
                        min-height
455
                        max-width
456 457 458 459 460 461 462 463 464 465 466 467
                        around
                        (face 'popup-face)
                        mouse-face
                        (selection-face face)
                        (summary-face 'popup-summary-face)
                        scroll-bar
                        margin-left
                        margin-right
                        symbol
                        parent
                        parent-offset
                        keymap)
468 469 470 471 472
  "Create a popup instance at POINT with WIDTH and HEIGHT.

MIN-HEIGHT is a minimal height of the popup. The default value is
0.

473 474 475 476
MAX-WIDTH is the maximum width of the popup. The default value is
nil (no limit). If a floating point, the value refers to the ratio of
the window. If an integer, limit is in characters.

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
If AROUND is non-nil, the popup will be displayed around the
point but not at the point.

FACE is a background face of the popup. The default value is POPUP-FACE.

SELECTION-FACE is a foreground (selection) face of the popup The
default value is POPUP-FACE.

If SCROLL-BAR is non-nil, the popup will have a scroll bar at the
right.

If MARGIN-LEFT is non-nil, the popup will have a margin at the
left.

If MARGIN-RIGHT is non-nil, the popup will have a margin at the
right.

SYMBOL is a single character which indicates a kind of the item.

PARENT is a parent popup instance. If PARENT is omitted, the
popup will be a root instance.

Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
499 500 501
PARENT-OFFSET is a row offset from the parent popup.

KEYMAP is a keymap that will be put on the popup contents."
502 503 504 505 506
  (or margin-left (setq margin-left 0))
  (or margin-right (setq margin-right 0))
  (unless point
    (setq point
          (if parent (popup-child-point parent parent-offset) (point))))
507 508
  (when max-width
    (setq width (min width (popup-calculate-max-width max-width))))
509 510
  (save-excursion
    (goto-char point)
TAKAGI Kentaro's avatar
TAKAGI Kentaro committed
511 512 513
    (let* ((col-row (posn-col-row (posn-at-point)))
           (row (cdr col-row))
           (column (car col-row))
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
           (overlays (make-vector height nil))
           (popup-width (+ width
                           (if scroll-bar 1 0)
                           margin-left
                           margin-right
                           (if symbol 2 0)))
           margin-left-cancel
           (window (selected-window))
           (window-start (window-start))
           (window-hscroll (window-hscroll))
           (window-width (window-width))
           (right (+ column popup-width))
           (overflow (and (> right window-width)
                          (>= right popup-width)))
           (foldable (and (null parent)
                          (>= column popup-width)))
           (direction (or
                       ;; Currently the direction of cascade popup won't be changed
                       (and parent (popup-direction parent))

                       ;; Calculate direction
535
                       (popup-calculate-direction height row)))
536
           (depth (if parent (1+ (popup-depth parent)) 0))
537
           (newlines (max 0 (+ (- height (count-lines point (point-max))) (if around 1 0))))
TAKAGI Kentaro's avatar
TAKAGI Kentaro committed
538
           invis-overlays
539
           current-column)
540 541
      ;; Case: no newlines at the end of the buffer
      (when (> newlines 0)
542
        (popup-save-buffer-state
543 544
          (goto-char (point-max))
          (insert (make-string newlines ?\n))))
Syohei YOSHIDA's avatar
Syohei YOSHIDA committed
545

546
      ;; Case: the popup overflows
547 548 549
      (if overflow
          (if foldable
              (progn
550
                (cl-decf column (- popup-width margin-left margin-right))
551 552
                (unless around (move-to-column column)))
            (when (not truncate-lines)
553
              ;; Truncate.
554
              (let ((d (1+ (- popup-width (- window-width column)))))
555 556 557 558
                (cl-decf popup-width d)
                (cl-decf width d)))
            (cl-decf column margin-left))
        (cl-decf column margin-left))
559 560

      ;; Case: no space at the left
561 562
      (when (and (null parent)
                 (< column 0))
563
        ;; Cancel margin left
564
        (setq column 0)
565
        (cl-decf popup-width margin-left)
566
        (setq margin-left-cancel t))
Syohei YOSHIDA's avatar
Syohei YOSHIDA committed
567

568
      (dotimes (i height)
569
        (let (overlay begin w (dangle t) (prefix "") (postfix ""))
570
          (when around
571
            (popup-vertical-motion column direction))
TAKAGI Kentaro's avatar
TAKAGI Kentaro committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
          (cl-loop for ov in (overlays-in (save-excursion
                                            (beginning-of-visual-line)
                                            (point))
                                          (save-excursion
                                            (end-of-visual-line)
                                            (point)))
                   when (and (not (overlay-get ov 'popup))
                             (not (overlay-get ov 'popup-item))
                             (or (overlay-get ov 'invisible)
                                 (overlay-get ov 'display)))
                   do (progn
                        (push (list ov (overlay-get ov 'display)) invis-overlays)
                        (overlay-put ov 'display "")))
          (setq around t)
          (setq current-column (car (posn-col-row (posn-at-point))))
587 588 589

          (when (< current-column column)
            ;; Extend short buffer lines by popup prefix (line of spaces)
590
            (setq prefix (make-string
591
                          (+ (if (= current-column 0)
TAKAGI Kentaro's avatar
TAKAGI Kentaro committed
592
                                 (- window-hscroll current-column)
593 594 595
                               0)
                             (- column current-column))
                          ? )))
596 597 598 599 600

          (setq begin (point))
          (setq w (+ popup-width (length prefix)))
          (while (and (not (eolp)) (> w 0))
            (setq dangle nil)
601
            (cl-decf w (char-width (char-after)))
602 603 604 605 606
            (forward-char))
          (if (< w 0)
              (setq postfix (make-string (- w) ? )))

          (setq overlay (make-overlay begin (point)))
TAKAGI Kentaro's avatar
TAKAGI Kentaro committed
607
          (overlay-put overlay 'popup t)
608 609 610 611 612 613
          (overlay-put overlay 'window window)
          (overlay-put overlay 'dangle dangle)
          (overlay-put overlay 'prefix prefix)
          (overlay-put overlay 'postfix postfix)
          (overlay-put overlay 'width width)
          (aset overlays
Syohei YOSHIDA's avatar
Syohei YOSHIDA committed
614 615
                (if (> direction 0) i (- height i 1))
                overlay)))
616 617 618
      (cl-loop for p from (- 10000 (* depth 1000))
               for overlay in (nreverse (append overlays nil))
               do (overlay-put overlay 'priority p))
619 620 621 622 623 624 625 626 627 628
      (let ((it (make-popup :point point
                            :row row
                            :column column
                            :width width
                            :height height
                            :min-height min-height
                            :direction direction
                            :parent parent
                            :depth depth
                            :face face
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
629
                            :mouse-face mouse-face
630
                            :selection-face selection-face
631
                            :summary-face summary-face
632 633 634 635 636 637
                            :margin-left margin-left
                            :margin-right margin-right
                            :margin-left-cancel margin-left-cancel
                            :scroll-bar scroll-bar
                            :symbol symbol
                            :cursor 0
638
                            :offset 0
639 640 641
                            :scroll-top 0
                            :current-height 0
                            :list nil
642
                            :newlines newlines
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
643
                            :overlays overlays
TAKAGI Kentaro's avatar
TAKAGI Kentaro committed
644
                            :invis-overlays invis-overlays
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
645
                            :keymap keymap)))
646 647 648 649
        (push it popup-instances)
        it))))

(defun popup-delete (popup)
650
  "Delete POPUP instance."
651 652 653 654 655
  (when (popup-live-p popup)
    (popup-hide popup)
    (mapc 'delete-overlay (popup-overlays popup))
    (setf (popup-overlays popup) nil)
    (setq popup-instances (delq popup popup-instances))
656 657 658
    ;; Restore newlines state
    (let ((newlines (popup-newlines popup)))
      (when (> newlines 0)
659
        (popup-save-buffer-state
660 661
          (goto-char (point-max))
          (dotimes (i newlines)
662 663
            (if (and (char-before)
                     (= (char-before) ?\n))
664
                (delete-char -1)))))))
665 666 667
  nil)

(defun popup-draw (popup)
668
  "Draw POPUP."
TAKAGI Kentaro's avatar
TAKAGI Kentaro committed
669 670 671
  (cl-loop for (ov olddisplay) in (popup-invis-overlays popup)
           do (overlay-put ov 'display ""))

672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
  (cl-loop with height = (popup-height popup)
           with min-height = (popup-min-height popup)
           with popup-face = (popup-face popup)
           with mouse-face = (popup-mouse-face popup)
           with selection-face = (popup-selection-face popup)
           with summary-face-0 = (popup-summary-face popup)
           with list = (popup-list popup)
           with length = (length list)
           with thum-size = (max (/ (* height height) (max length 1)) 1)
           with page-size = (/ (+ 0.0 (max length 1)) height)
           with scroll-bar = (popup-scroll-bar popup)
           with margin-left = (make-string (if (popup-margin-left-cancel popup) 0 (popup-margin-left popup)) ? )
           with margin-right = (make-string (popup-margin-right popup) ? )
           with symbol = (popup-symbol popup)
           with cursor = (popup-cursor popup)
           with scroll-top = (popup-scroll-top popup)
           with offset = (popup-offset popup)
           with keymap = (popup-keymap popup)
           for o from offset
           for i from scroll-top
           while (< o height)
           for item in (nthcdr scroll-top list)
           for page-index = (* thum-size (/ o thum-size))
           for face = (if (= i cursor)
                          (or (popup-item-selection-face item) selection-face)
                        (or (popup-item-face item) popup-face))
           for summary-face = (unless (= i cursor) summary-face-0)
           for empty-char = (propertize " " 'face face)
           for scroll-bar-char = (if scroll-bar
                                     (cond
                                      ((and (not (eq scroll-bar :always))
                                            (<= page-size 1))
                                       empty-char)
                                      ((and (> page-size 1)
                                            (>= cursor (* page-index page-size))
                                            (< cursor (* (+ page-index thum-size) page-size)))
                                       popup-scroll-bar-foreground-char)
                                      (t
                                       popup-scroll-bar-background-char))
                                   "")
           for sym = (if symbol
                         (concat " " (or (popup-item-symbol item) " "))
                       "")
           for summary = (or (popup-item-summary item) "")

           do
           ;; Show line and set item to the line
           (popup-set-line-item popup o
                                :item item
                                :face face
                                :mouse-face mouse-face
                                :margin-left margin-left
                                :margin-right margin-right
                                :scroll-bar-char scroll-bar-char
                                :symbol sym
                                :summary summary
                                :summary-face summary-face
                                :keymap keymap)

           finally
           ;; Remember current height
           (setf (popup-current-height popup) (- o offset))

           ;; Hide remaining lines
           (let ((scroll-bar-char (if scroll-bar (propertize " " 'face popup-face) ""))
                 (symbol (if symbol " " "")))
             (if (> (popup-direction popup) 0)
                 (progn
                   (when min-height
                     (while (< o min-height)
                       (popup-set-line-item popup o
                                            :item ""
                                            :face popup-face
                                            :margin-left margin-left
                                            :margin-right margin-right
                                            :scroll-bar-char scroll-bar-char
                                            :symbol symbol
                                            :summary "")
750
                       (cl-incf o)))
751 752
                   (while (< o height)
                     (popup-hide-line popup o)
753
                     (cl-incf o)))
754 755 756 757 758 759 760 761 762 763 764 765 766
               (cl-loop with h = (if min-height (- height min-height) offset)
                        for o from 0 below offset
                        if (< o h)
                        do (popup-hide-line popup o)
                        if (>= o h)
                        do (popup-set-line-item popup o
                                                :item ""
                                                :face popup-face
                                                :margin-left margin-left
                                                :margin-right margin-right
                                                :scroll-bar-char scroll-bar-char
                                                :symbol symbol
                                                :summary ""))))))
767 768

(defun popup-hide (popup)
769
  "Hide POPUP."
TAKAGI Kentaro's avatar
TAKAGI Kentaro committed
770 771
  (cl-loop for (ov olddisplay) in (popup-invis-overlays popup)
           do (overlay-put ov 'display olddisplay))
772 773 774 775
  (dotimes (i (popup-height popup))
    (popup-hide-line popup i)))

(defun popup-hidden-p (popup)
776
  "Return non-nil if POPUP is hidden."
777 778 779 780 781 782 783
  (let ((hidden t))
    (when (popup-live-p popup)
      (dotimes (i (popup-height popup))
        (unless (popup-line-hidden-p popup i)
          (setq hidden nil))))
    hidden))

784 785 786 787 788 789 790 791 792 793
(defun popup-jump (popup cursor)
  "Jump to a position specified by CURSOR of POPUP and draw."
  (let ((scroll-top (popup-scroll-top popup)))
    ;; Do not change page as much as possible.
    (unless (and (<= scroll-top cursor)
                 (< cursor (+ scroll-top (popup-height popup))))
      (setf (popup-scroll-top popup) cursor))
    (setf (popup-cursor popup) cursor)
    (popup-draw popup)))

794
(defun popup-select (popup i)
795
  "Select the item at I of POPUP and draw."
796 797 798 799 800 801 802
  (setq i (+ i (popup-offset popup)))
  (when (and (<= 0 i) (< i (popup-height popup)))
    (setf (popup-cursor popup) i)
    (popup-draw popup)
    t))

(defun popup-next (popup)
803
  "Select the next item of POPUP and draw."
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
  (let ((height (popup-height popup))
        (cursor (1+ (popup-cursor popup)))
        (scroll-top (popup-scroll-top popup))
        (length (length (popup-list popup))))
    (cond
     ((>= cursor length)
      ;; Back to first page
      (setq cursor 0
            scroll-top 0))
     ((= cursor (+ scroll-top height))
      ;; Go to next page
      (setq scroll-top (min (1+ scroll-top) (max (- length height) 0)))))
    (setf (popup-cursor popup) cursor
          (popup-scroll-top popup) scroll-top)
    (popup-draw popup)))

(defun popup-previous (popup)
821
  "Select the previous item of POPUP and draw."
822 823 824 825 826 827 828 829 830 831 832
  (let ((height (popup-height popup))
        (cursor (1- (popup-cursor popup)))
        (scroll-top (popup-scroll-top popup))
        (length (length (popup-list popup))))
    (cond
     ((< cursor 0)
      ;; Go to last page
      (setq cursor (1- length)
            scroll-top (max (- length height) 0)))
     ((= cursor (1- scroll-top))
      ;; Go to previous page
833
      (cl-decf scroll-top)))
834 835 836 837
    (setf (popup-cursor popup) cursor
          (popup-scroll-top popup) scroll-top)
    (popup-draw popup)))

838 839 840
(defun popup-page-next (popup)
  "Select next item of POPUP per `popup-height' range.
Pages down through POPUP."
kostafey's avatar
kostafey committed
841 842
  (dotimes (counter (1- (popup-height popup)))
    (popup-next popup)))
843 844 845 846

(defun popup-page-previous (popup)
  "Select previous item of POPUP per `popup-height' range.
Pages up through POPUP."
kostafey's avatar
kostafey committed
847 848
  (dotimes (counter (1- (popup-height popup)))
    (popup-previous popup)))
849

850
(defun popup-scroll-down (popup &optional n)
851
  "Scroll down N of POPUP and draw."
852 853 854 855 856 857 858
  (let ((scroll-top (min (+ (popup-scroll-top popup) (or n 1))
                         (- (length (popup-list popup)) (popup-height popup)))))
    (setf (popup-cursor popup) scroll-top
          (popup-scroll-top popup) scroll-top)
    (popup-draw popup)))

(defun popup-scroll-up (popup &optional n)
859
  "Scroll up N of POPUP and draw."
860 861 862 863 864 865 866 867
  (let ((scroll-top (max (- (popup-scroll-top popup) (or n 1))
                         0)))
    (setf (popup-cursor popup) scroll-top
          (popup-scroll-top popup) scroll-top)
    (popup-draw popup)))



868
;;; Popup Incremental Search
869 870 871 872 873 874 875 876 877 878 879 880

(defface popup-isearch-match
  '((t (:background "sky blue")))
  "Popup isearch match face."
  :group 'popup)

(defvar popup-isearch-cursor-color "blue")

(defvar popup-isearch-keymap
  (let ((map (make-sparse-keymap)))
    ;(define-key map "\r"        'popup-isearch-done)
    (define-key map "\C-g"      'popup-isearch-cancel)
881 882
    (define-key map "\C-b"      'popup-isearch-close)
    (define-key map [left]      'popup-isearch-close)
883 884 885 886
    (define-key map "\C-h"      'popup-isearch-delete)
    (define-key map (kbd "DEL") 'popup-isearch-delete)
    map))

887 888 889
(defvar popup-menu-show-quick-help-function 'popup-menu-show-quick-help
  "Function used for showing quick help by `popup-menu*'.")

890 891 892 893 894 895
(defsubst popup-isearch-char-p (char)
  (and (integerp char)
       (<= 32 char)
       (<= char 126)))

(defun popup-isearch-filter-list (pattern list)
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
  (cl-loop with regexp = (regexp-quote pattern)
           for item in list
           do
           (unless (stringp item)
             (setq item (popup-item-propertize (popup-x-to-string item)
                                               'value item)))
           if (string-match regexp item)
           collect
           (let ((beg (match-beginning 0))
                 (end (match-end 0)))
             (alter-text-property 0 (length item) 'face
                                  (lambda (prop)
                                    (unless (eq prop 'popup-isearch-match)
                                      prop))
                                  item)
             (put-text-property beg end
                                'face 'popup-isearch-match
                                item)
             item)))
915 916 917 918 919 920

(defun popup-isearch-prompt (popup pattern)
  (format "Pattern: %s" (if (= (length (popup-list popup)) 0)
                            (propertize pattern 'face 'isearch-fail)
                          pattern)))

921
(defun popup-isearch-update (popup filter pattern &optional callback)
922 923 924
  (setf (popup-cursor popup) 0
        (popup-scroll-top popup) 0
        (popup-pattern popup) pattern)
925
  (let ((list (funcall filter pattern (popup-original-list popup))))
926 927 928 929 930
    (popup-set-filtered-list popup list)
    (if callback
        (funcall callback list)))
  (popup-draw popup))

931 932
(cl-defun popup-isearch (popup
                         &key
933
                         (filter 'popup-isearch-filter-list)
934 935 936 937
                         (cursor-color popup-isearch-cursor-color)
                         (keymap popup-isearch-keymap)
                         callback
                         help-delay)
938 939 940
  "Start isearch on POPUP. This function is synchronized, meaning
event loop waits for quiting of isearch.

941 942
FILTER is function with two argumenst to perform popup items filtering.

943 944 945 946 947 948 949 950 951 952 953
CURSOR-COLOR is a cursor color during isearch. The default value
is `popup-isearch-cursor-color'.

KEYMAP is a keymap which is used when processing events during
event loop. The default value is `popup-isearch-keymap'.

CALLBACK is a function taking one argument. `popup-isearch' calls
CALLBACK, if specified, after isearch finished or isearch
canceled. The arguments is whole filtered list of items.

HELP-DELAY is a delay of displaying helps."
954 955 956
  (let ((list (popup-original-list popup))
        (pattern (or (popup-pattern popup) ""))
        (old-cursor-color (frame-parameter (selected-frame) 'cursor-color))
957
        prompt key binding)
958
    (unwind-protect
959
        (cl-block nil
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
          (if cursor-color
              (set-cursor-color cursor-color))
          (while t
            (setq prompt (popup-isearch-prompt popup pattern))
            (setq key (popup-menu-read-key-sequence keymap prompt help-delay))
            (if (null key)
                (unless (funcall popup-menu-show-quick-help-function popup nil :prompt prompt)
                  (clear-this-command-keys)
                  (push (read-event prompt) unread-command-events))
              (setq binding (lookup-key keymap key))
              (cond
               ((and (stringp key)
                     (popup-isearch-char-p (aref key 0)))
                (setq pattern (concat pattern key)))
               ((eq binding 'popup-isearch-done)
975
                (cl-return nil))
976
               ((eq binding 'popup-isearch-cancel)
977
                (popup-isearch-update popup filter "" callback)
978
                (cl-return t))
979
               ((eq binding 'popup-isearch-close)
980
                (popup-isearch-update popup filter "" callback)
981 982 983
                (setq unread-command-events
                      (append (listify-key-sequence key) unread-command-events))
                (cl-return nil))
984 985 986 987 988 989
               ((eq binding 'popup-isearch-delete)
                (if (> (length pattern) 0)
                    (setq pattern (substring pattern 0 (1- (length pattern))))))
               (t
                (setq unread-command-events
                      (append (listify-key-sequence key) unread-command-events))
990
                (cl-return nil)))
991
              (popup-isearch-update popup filter pattern callback))))
992 993 994 995 996
      (if old-cursor-color
          (set-cursor-color old-cursor-color)))))



997
;;; Popup Tip
998 999 1000 1001 1002 1003 1004 1005

(defface popup-tip-face
  '((t (:background "khaki1" :foreground "black")))
  "Face for popup tip."
  :group 'popup)

(defvar popup-tip-max-width 80)

1006 1007 1008 1009 1010 1011 1012
(cl-defun popup-tip (string
                     &key
                     point
                     (around t)
                     width
                     (height 15)
                     min-height
1013
                     max-width
1014 1015 1016 1017 1018 1019 1020 1021
                     truncate
                     margin
                     margin-left
                     margin-right
                     scroll-bar
                     parent
                     parent-offset
                     nowait
1022
                     nostrip
1023 1024
                     prompt
                     &aux tip lines)
1025 1026 1027 1028 1029 1030 1031 1032 1033
  "Show a tooltip of STRING at POINT. This function is
synchronized unless NOWAIT specified. Almost arguments are same
as `popup-create' except for TRUNCATE, NOWAIT, and PROMPT.

If TRUNCATE is non-nil, the tooltip can be truncated.

If NOWAIT is non-nil, this function immediately returns the
tooltip instance without entering event loop.

1034 1035
If `NOSTRIP` is non-nil, `STRING` properties are not stripped.

1036
PROMPT is a prompt string when reading events during event loop."
1037 1038
  (if (bufferp string)
      (setq string (with-current-buffer string (buffer-string))))
1039 1040 1041 1042

  (unless nostrip
    ;; TODO strip text (mainly face) properties
    (setq string (substring-no-properties string)))
1043 1044 1045 1046

  (and (eq margin t) (setq margin 1))
  (or margin-left (setq margin-left margin))
  (or margin-right (setq margin-right margin))
Syohei YOSHIDA's avatar
Syohei YOSHIDA committed
1047

1048 1049 1050
  (let ((it (popup-fill-string string width popup-tip-max-width)))
    (setq width (car it)
          lines (cdr it)))
Syohei YOSHIDA's avatar
Syohei YOSHIDA committed
1051

1052 1053
  (setq tip (popup-create point width height
                          :min-height min-height
1054
                          :max-width max-width
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
                          :around around
                          :margin-left margin-left
                          :margin-right margin-right
                          :scroll-bar scroll-bar
                          :face 'popup-tip-face
                          :parent parent
                          :parent-offset parent-offset))

  (unwind-protect
      (when (> (popup-width tip) 0)                   ; not to be corrupted
        (when (and (not (eq width (popup-width tip))) ; truncated
                   (not truncate))
          ;; Refill once again to lines be fitted to popup width
          (setq width (popup-width tip))
          (setq lines (cdr (popup-fill-string string width width))))

        (popup-set-list tip lines)
        (popup-draw tip)
        (if nowait
            tip
          (clear-this-command-keys)
          (push (read-event prompt) unread-command-events)
          t))
    (unless nowait
      (popup-delete tip))))



1083
;;; Popup Menu
1084 1085

(defface popup-menu-face
1086
  '((t (:inherit popup-face)))
1087 1088 1089
  "Face for popup menu."
  :group 'popup)

Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1090 1091 1092 1093 1094
(defface popup-menu-mouse-face
  '((t (:background "blue" :foreground "white")))
  "Face for popup menu."
  :group 'popup)

1095 1096 1097 1098 1099
(defface popup-menu-selection-face
  '((t (:background "steelblue" :foreground "white")))
  "Face for popup menu selection."
  :group 'popup)

1100
(defface popup-menu-summary-face
1101
  '((t (:inherit popup-summary-face)))
1102 1103 1104
  "Face for popup summary."
  :group 'popup)

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
(defvar popup-menu-show-tip-function 'popup-tip
  "Function used for showing tooltip by `popup-menu-show-quick-help'.")

(defun popup-menu-show-help (menu &optional persist item)
  (popup-item-show-help (or item (popup-selected-item menu)) persist))

(defun popup-menu-documentation (menu &optional item)
  (popup-item-documentation (or item (popup-selected-item menu))))

(defun popup-menu-show-quick-help (menu &optional item &rest args)
  (let* ((point (plist-get args :point))
         (height (or (plist-get args :height) (popup-height menu)))
         (min-height (min height (popup-current-height menu)))
         (around nil)
         (parent-offset (popup-offset menu))
         (doc (popup-menu-documentation menu item)))
    (when (stringp doc)
      (if (popup-hidden-p menu)
          (setq around t
                menu nil
                parent-offset nil)
        (setq point nil))
      (let ((popup-use-optimized-column-computation nil)) ; To avoid wrong positioning
        (apply popup-menu-show-tip-function
               doc
               :point point
               :height height
               :min-height min-height
               :around around
               :parent menu
               :parent-offset parent-offset
               args)))))

Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1138 1139
(defun popup-menu-item-of-mouse-event (event)
  (when (and (consp event)
1140 1141
             (memq (cl-first event) '(mouse-1 mouse-2 mouse-3 mouse-4 mouse-5)))
    (let* ((position (cl-second event))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1142 1143 1144 1145
           (object (elt position 4)))
      (when (consp object)
        (get-text-property (cdr object) 'popup-item (car object))))))

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
(defun popup-menu-read-key-sequence (keymap &optional prompt timeout)
  (catch 'timeout
    (let ((timer (and timeout
                      (run-with-timer timeout nil
                                      (lambda ()
                                        (if (zerop (length (this-command-keys)))
                                            (throw 'timeout nil))))))
          (old-global-map (current-global-map))
          (temp-global-map (make-sparse-keymap))
          (overriding-terminal-local-map (make-sparse-keymap)))
      (substitute-key-definition 'keyboard-quit 'keyboard-quit
                                 temp-global-map old-global-map)
      (define-key temp-global-map [menu-bar] (lookup-key old-global-map [menu-bar]))
      (define-key temp-global-map [tool-bar] (lookup-key old-global-map [tool-bar]))
      (set-keymap-parent overriding-terminal-local-map keymap)
      (if (current-local-map)
          (define-key overriding-terminal-local-map [menu-bar]
            (lookup-key (current-local-map) [menu-bar])))
      (unwind-protect
          (progn
            (use-global-map temp-global-map)
            (clear-this-command-keys)
            (with-temp-message prompt
              (read-key-sequence nil)))
        (use-global-map old-global-map)
        (if timer (cancel-timer timer))))))

(defun popup-menu-fallback (event default))

1175 1176 1177 1178 1179 1180 1181
(cl-defun popup-menu-event-loop (menu
                                 keymap
                                 fallback
                                 &key
                                 prompt
                                 help-delay
                                 isearch
1182
                                 isearch-filter
1183 1184 1185 1186
                                 isearch-cursor-color
                                 isearch-keymap
                                 isearch-callback
                                 &aux key binding)
1187
  (cl-block nil
1188 1189 1190
    (while (popup-live-p menu)
      (and isearch
           (popup-isearch menu
1191
                          :filter isearch-filter
1192 1193 1194 1195 1196 1197
                          :cursor-color isearch-cursor-color
                          :keymap isearch-keymap
                          :callback isearch-callback
                          :help-delay help-delay)
           (keyboard-quit))
      (setq key (popup-menu-read-key-sequence keymap prompt help-delay))
1198
      (setq binding (and key (lookup-key keymap key)))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1199 1200 1201 1202 1203 1204 1205
      (cond
       ((or (null key) (zerop (length key)))
        (unless (funcall popup-menu-show-quick-help-function menu nil :prompt prompt)
          (clear-this-command-keys)
          (push (read-event prompt) unread-command-events)))
       ((eq (lookup-key (current-global-map) key) 'keyboard-quit)
        (keyboard-quit)
1206
        (cl-return))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1207 1208
       ((eq binding 'popup-close)
        (if (popup-parent menu)
1209
            (cl-return)))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1210 1211 1212
       ((memq binding '(popup-select popup-open))
        (let* ((item (or (popup-menu-item-of-mouse-event (elt key 0))
                         (popup-selected-item menu)))
1213
               (index (cl-position item (popup-list menu)))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1214
               (sublist (popup-item-sublist item)))
1215
          (unless index (cl-return))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1216
          (if sublist
1217 1218 1219 1220 1221 1222 1223
              (popup-aif (let (popup-use-optimized-column-computation)
                           (popup-cascade-menu sublist
                                               :around nil
                                               :margin-left (popup-margin-left menu)
                                               :margin-right (popup-margin-right menu)
                                               :scroll-bar (popup-scroll-bar menu)
                                               :parent menu
1224
                                               :parent-offset index
1225 1226
                                               :help-delay help-delay
                                               :isearch isearch
1227
                                               :isearch-filter isearch-filter
1228 1229 1230
                                               :isearch-cursor-color isearch-cursor-color
                                               :isearch-keymap isearch-keymap
                                               :isearch-callback isearch-callback))
1231
                  (and it (cl-return it)))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1232
            (if (eq binding 'popup-select)
1233
                (cl-return (popup-item-value-or-self item))))))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1234 1235 1236 1237
       ((eq binding 'popup-next)
        (popup-next menu))
       ((eq binding 'popup-previous)
        (popup-previous menu))
1238 1239 1240 1241
       ((eq binding 'popup-page-next)
        (popup-page-next menu))
       ((eq binding 'popup-page-previous)
        (popup-page-previous menu))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1242 1243 1244 1245
       ((eq binding 'popup-help)
        (popup-menu-show-help menu))
       ((eq binding 'popup-isearch)
        (popup-isearch menu
1246
                       :filter 'isearch-filter
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1247 1248 1249 1250 1251 1252 1253 1254
                       :cursor-color isearch-cursor-color
                       :keymap isearch-keymap
                       :callback isearch-callback
                       :help-delay help-delay))
       ((commandp binding)
        (call-interactively binding))
       (t
        (funcall fallback key (key-binding key)))))))
1255

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
(defun popup-preferred-width (list)
  "Return the preferred width to show LIST beautifully."
  (cl-loop with tab-width = 4
           for item in list
           for summary = (popup-item-summary item)
           maximize (string-width (popup-x-to-string item)) into width
           if (stringp summary)
           maximize (+ (string-width summary) 2) into summary-width
           finally return
           (let ((total (+ (or width 0) (or summary-width 0))))
             (* (ceiling (/ total 10.0)) 10))))

(defvar popup-menu-keymap
  (let ((map (make-sparse-keymap)))
    (define-key map "\r"        'popup-select)
    (define-key map "\C-f"      'popup-open)
    (define-key map [right]     'popup-open)
    (define-key map "\C-b"      'popup-close)
    (define-key map [left]      'popup-close)

    (define-key map "\C-n"      'popup-next)
    (define-key map [down]      'popup-next)
    (define-key map "\C-p"      'popup-previous)
    (define-key map [up]        'popup-previous)

    (define-key map [next]      'popup-page-next)
    (define-key map [prior]     'popup-page-previous)

    (define-key map [f1]        'popup-help)
    (define-key map (kbd "\C-?") 'popup-help)

    (define-key map "\C-s"      'popup-isearch)

    (define-key map [mouse-1]   'popup-select)
    (define-key map [mouse-4]   'popup-previous)
    (define-key map [mouse-5]   'popup-next)
    map))

1294 1295 1296 1297 1298 1299
(cl-defun popup-menu* (list
                       &key
                       point
                       (around t)
                       (width (popup-preferred-width list))
                       (height 15)
1300
                       max-width
1301 1302 1303 1304 1305 1306 1307
                       margin
                       margin-left
                       margin-right
                       scroll-bar
                       symbol
                       parent
                       parent-offset
1308
                       cursor
1309 1310 1311 1312 1313 1314
                       (keymap popup-menu-keymap)
                       (fallback 'popup-menu-fallback)
                       help-delay
                       nowait
                       prompt
                       isearch
1315
                       (isearch-filter 'popup-isearch-filter-list)
1316 1317 1318
                       (isearch-cursor-color popup-isearch-cursor-color)
                       (isearch-keymap popup-isearch-keymap)
                       isearch-callback
Syohei YOSHIDA's avatar
Syohei YOSHIDA committed
1319
                       initial-index
1320
                       &aux menu event)
1321
  "Show a popup menu of LIST at POINT. This function returns a
1322
value of the selected item. Almost arguments are same as
1323
`popup-create' except for KEYMAP, FALLBACK, HELP-DELAY, PROMPT,
1324
ISEARCH, ISEARCH-FILTER, ISEARCH-CURSOR-COLOR, ISEARCH-KEYMAP, and
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
ISEARCH-CALLBACK.

If KEYMAP is a keymap which is used when processing events during
event loop.

If FALLBACK is a function taking two arguments; a key and a
command. FALLBACK is called when no special operation is found on
the key. The default value is `popup-menu-fallback', which does
nothing.

HELP-DELAY is a delay of displaying helps.

If NOWAIT is non-nil, this function immediately returns the menu
instance without entering event loop.

PROMPT is a prompt string when reading events during event loop.

If ISEARCH is non-nil, do isearch as soon as displaying the popup
menu.

1345 1346 1347
ISEARCH-FILTER is a filtering function taking two arguments:
search pattern and list of items. Returns a list of matching items.

1348 1349 1350 1351 1352 1353 1354 1355
ISEARCH-CURSOR-COLOR is a cursor color during isearch. The
default value is `popup-isearch-cursor-color'.

ISEARCH-KEYMAP is a keymap which is used when processing events
during event loop. The default value is `popup-isearch-keymap'.

ISEARCH-CALLBACK is a function taking one argument.  `popup-menu'
calls ISEARCH-CALLBACK, if specified, after isearch finished or
1356 1357 1358 1359
isearch canceled. The arguments is whole filtered list of items.

If `INITIAL-INDEX' is non-nil, this is an initial index value for
`popup-select'. Only positive integer is valid."
1360 1361 1362 1363 1364 1365 1366
  (and (eq margin t) (setq margin 1))
  (or margin-left (setq margin-left margin))
  (or margin-right (setq margin-right margin))
  (if (and scroll-bar
           (integerp margin-right)
           (> margin-right 0))
      ;; Make scroll-bar space as margin-right
1367
      (cl-decf margin-right))
1368
  (setq menu (popup-create point width height
1369
                           :max-width max-width
1370 1371
                           :around around
                           :face 'popup-menu-face
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1372
                           :mouse-face 'popup-menu-mouse-face
1373
                           :selection-face 'popup-menu-selection-face
1374
                           :summary-face 'popup-menu-summary-face
1375 1376 1377 1378
                           :margin-left margin-left
                           :margin-right margin-right
                           :scroll-bar scroll-bar
                           :symbol symbol
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1379 1380
                           :parent parent
                           :parent-offset parent-offset))
1381 1382 1383
  (unwind-protect
      (progn
        (popup-set-list menu list)
1384 1385
        (if cursor
            (popup-jump menu cursor)
1386
          (popup-draw menu))
Syohei YOSHIDA's avatar
Syohei YOSHIDA committed
1387
        (when initial-index
Syohei YOSHIDA's avatar
Syohei YOSHIDA committed
1388 1389
          (dotimes (_i (min (- (length list) 1) initial-index))
            (popup-next menu)))
1390 1391 1392 1393 1394 1395
        (if nowait
            menu
          (popup-menu-event-loop menu keymap fallback
                                 :prompt prompt
                                 :help-delay help-delay
                                 :isearch isearch
1396
                                 :isearch-filter isearch-filter
1397 1398 1399 1400 1401
                                 :isearch-cursor-color isearch-cursor-color
                                 :isearch-keymap isearch-keymap
                                 :isearch-callback isearch-callback)))
    (unless nowait
      (popup-delete menu))))
1402 1403

(defun popup-cascade-menu (list &rest args)
1404 1405 1406 1407
  "Same as `popup-menu' except that an element of LIST can be
also a sub-menu if the element is a cons cell formed (ITEM
. SUBLIST) where ITEM is an usual item and SUBLIST is a list of
the sub menu."
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
  (apply 'popup-menu*
         (mapcar (lambda (item)
                   (if (consp item)
                       (popup-make-item (car item)
                                        :sublist (cdr item)
                                        :symbol ">")
                     item))
                 list)
         :symbol t
         args))

(provide 'popup)
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
1420
;;; popup.el ends here