Navigating Markdown Headings


Neovim provides many ways to navigate within documents, and this tip creates a simple keymap that makes it quick and easy to jump between markdown headings, which can be a big speed boost in longer markdown documents.

Create a markdown directory under ftplugin if it doesn't already exist, then add a file containing the following keymaps:

vim.keymap.set("n", "<A-j>", "/^#\\+ <CR>")

vim.keymap.set("n", "<A-k>", "?^#\\+ <CR>")

These keymaps take advantage of the search operators / and ? to search forward and backward from the current cursor position, respectively. In each case, Neovim searches for the pattern ^#\\+, which matches any line that starts with one or more # characters followed by a space. While this is a fairly naive pattern that may produce some false matches, it is very simple to implement and works quite well for most markdown documents.

As a quick demo, let's take the following Markdown file. Starting from the top, in steps 1 and 2 we hit <A-j> to step forward through the headings, then finally in step 3 we use <A-k> to jump back up to the previous heading:

Before
#·Heading·1
 
Text
 
##·Heading·2
 
Text
 
###·Heading·3
NORMALTop1:1
 
Jump to Next Heading<A-j>
#·Heading·1
 
Text
 
##·Heading·2
 
Text
 
###·Heading·3
NORMAL50%5:1
 
Jump to Next Heading (Again)<A-j>
#·Heading·1
 
Text
 
##·Heading·2
 
Text
 
###·Heading·3
NORMAL90%9:1
 
Jump to Previous Heading<A-k>
#·Heading·1
 
Text
 
##·Heading·2
 
Text
 
###·Heading·3
NORMAL50%5:1
 

This keymap also supports counts, allowing you to navigate even faster by jumping multiple headings at a time.

If you would like to see another way to implement the same function but using Treesitter, take a look at this tip.