Clicky

Markdown Mode and Imenu

August 10, 2017

Markdown Mode for Emacs includes support for imenu, an interface for quickly navigating to different sections within a buffer. To try imenu with Markdown Mode, simply run M-x imenu-add-menubar-index. An “Index” menu will appear in the menubar. Clicking a heading moves the point to that heading. Alternatively, when invoking M-x imenu using the keyboard Emacs will present you with a list of headings in the minibuffer.

imenu Index in Markdown Mode
imenu Index in Markdown Mode

Markdown Mode adds a “.” to the top of each sub-menu. Clicking this dot takes you to the parent section. Otherwise, there is no way to jump directly to headings that are not “leaf nodes.”

To automatically load imenu when markdown-mode is loaded, you can add the following to your .emacs or init.el file:

(add-hook 'markdown-mode-hook 'imenu-add-menubar-index)
(setq imenu-auto-rescan t)

The first line asks Emacs to run the imenu-add-menubar-index function each time markdown-mode is loaded. The second line asks imenu to keep the index up to date when files are modified, as sections may be added or removed.

Another useful imenu-based tool is imenu-list, a third-party package which shows the current buffer’s imenu entries in a popup buffer. You can install it from MELPA. I use use-package for loading packages in my init file, so I configure it like this:

(use-package imenu-list
  :ensure t
  :bind (("C-'" . imenu-list-smart-toggle))
  :config
  (setq imenu-list-focus-after-activation t
        imenu-list-auto-resize nil))

Then, when pressing C-‘, a window appears on the right side showing the heading hierarchy in the *Ilist* buffer. Pressing C-’ again hides the window.

imenu-list with Markdown Mode
imenu-list with Markdown Mode

Of course, there are several keybindings in the *Ilist* buffer for navigating between sections:

Unlike the imenu Index menu, the *Ilist* buffer is updated automatically when Emacs is idle.