;; This buffer is for text that is not saved, and for Lisp evaluation.
;; To create a file, visit it with ‘C-x C-f’ and enter text in its buffer.

(define-derived-mode imenu-selection-mode fundamental-mode "imenu"
  "Major mode for imenu selection."
  (suppress-keymap imenu-selection-mode-map)
  (define-key imenu-selection-mode-map "j" 'next-line)
  (define-key imenu-selection-mode-map "k" 'previous-line)
  (define-key imenu-selection-mode-map "l" 'imenu-selection-select)
  (define-key imenu-selection-mode-map "\C-m" 'imenu-selection-select)
  (define-key imenu-selection-mode-map "h" 'kill-this-buffer)
  )
(defvar imenu--selection-buffer " *imenu-select*")
(defvar imenu--target-buffer nil)
(defun imenu-make-selection-buffer (&optional index-alist)
  (interactive)
  (require 'which-func)
  (setq index-alist (if index-alist index-alist (imenu--make-index-alist)))
  (let ((cur (which-function)))
    (when (listp cur)
      (setq cur (car cur)))
    (setq imenu--target-buffer (current-buffer))
    (switch-to-buffer imenu--selection-buffer)
    (buffer-disable-undo)
    (erase-buffer)
    (dolist (x index-alist)
      (insert (car x) "\n"))
    (if cur (search-backward (concat cur "\n") nil t))
    (imenu-selection-mode)))

(defun imenu-selection-select ()
  (interactive)
  (let ((sel (substring (thing-at-point 'line) 0 -1)))
    (bury-buffer)
    (switch-to-buffer imenu--target-buffer)
    (imenu sel)))
