Subject: bug#2419: 23.0.90; python-mode: Better Imenu

From: Milan Zamazal <[email-masked]>
Date: Sat, 21 Feb 2009 11:24:23 +0100

In GNU Emacs 23.0.90.1 (x86_64-pc-linux-gnu, GTK+ Version 2.12.11)
 of 2009-02-03 on blackbird, modified by Debian
 (emacs-snapshot package, version 1:20090202-1)

The Imenu support as currently implemented in python-mode is not very
useful:

1. It is easier to use I-search than clicking through the offered
   choices.

2. When I call `M-x imenu', it usually can't find the definition of the
   identifier at the current point.

FWIW, I use the following Imenu index building function which fixes both
the problems by using single-string items, with reverse order of the
identifiers within the string.  Perhaps something like this could be
useful for other people as well.

(defun my-python-imenu-create-index ()
  (let ((index '())
        (suffix '()))
    (save-excursion
      (goto-char (point-min))
      (while (re-search-forward "^\\([ \t]*\\)\\(def\\|class\\) \\([a-zA-Z_0-9]+\\)" nil t)
        (let ((indentation (length (match-string 1)))
              (name (match-string-no-properties 3)))
          (while (and suffix (<= indentation (caar suffix)))
            (setq suffix (cdr suffix)))
          (let* ((current-suffix (if suffix (cdar suffix) ""))
                 (name+suffix (concat name current-suffix)))
            (push (cons indentation (concat "." name+suffix)) suffix)
            (push (cons name+suffix (match-end 3)) index))))
      (goto-char (point-min))
      (while (re-search-forward "^\\([a-zA-Z_0-9]+\\) *=" nil t)
        (push (cons (match-string-no-properties 1) (match-end 1)) index)))
    (sort* index 'string< :key 'car)))

Regards,

Milan Zamazal