Vim Markdown Folding?

I had the same question, and played around with Jander's nice solution. The only problem is that by defining folding using syntax, you lose any Markdown syntax highlighting.

Given that you might be interested in alternate markups, I would suggest using reStructuredText, and the amazing Vst vim extension. It does folding very nicely. Rst is much more powerful than Markdown.


When I use markdown I only use the hash-style headings with space separating hashes and text. This makes the folding task a lot simpler.

I'm pretty new to Vim, so use the following at your own risk. I added the following code to my vimrc and it folds headings based on number of hashes, and it retains the syntax colouring.

function! MarkdownLevel()
    if getline(v:lnum) =~ '^# .*$'
        return ">1"
    endif
    if getline(v:lnum) =~ '^## .*$'
        return ">2"
    endif
    if getline(v:lnum) =~ '^### .*$'
        return ">3"
    endif
    if getline(v:lnum) =~ '^#### .*$'
        return ">4"
    endif
    if getline(v:lnum) =~ '^##### .*$'
        return ">5"
    endif
    if getline(v:lnum) =~ '^###### .*$'
        return ">6"
    endif
    return "=" 
endfunction
au BufEnter *.md setlocal foldexpr=MarkdownLevel()  
au BufEnter *.md setlocal foldmethod=expr     

Here is a try at a recursive header folding rule. It doesn't include the underline style of Markdown header, but I'm guessing those would be awkward for your purposes anyway.

Put the following code into your .vimrc:

au FileType markdown syn region myMkdHeaderFold
        \ start="\v^\s*\z(\#{1,6})"
        \ skip="\v(\n\s*\z1\#)\@="
        \ end="\v\n(\s*\#)\@="ms=s-1,me=s-1
        \ fold contains=myMkdHeaderFold

au FileType markdown syn sync fromstart
au FileType markdown set foldmethod=syntax

let g:markdown_folding = 1

You can enable markdown folding feature by adding this in your .vimrc if you are using the latest version of Vim - no need to be the latest, but I don't know the exact version.

For some reason it's not documented in the README but you can find the related code in the repository.

FYI, if you don't want the sections closed when you open a file, refer to this SO thread. I think adding this would be the best way but you may have a different preference.

set nofoldenable

Update

Unfortunately, I stopped using markdown_folding since it makes things slow (Github issue).

Tags:

Vim

Markdown