April 12, 2023

A vim script to mark folds on Markdown headers by default

You can write a script for vim to mark folds on Markdown headers automatically, by default, so you don’t have to manually set markers.

To do so add the following script1 to your .vimrc file:

" Mark folds on Markdown headers
function! MarkdownFolds()
    let thisline = getline(v:lnum)
    if match(thisline, '^##') >= 0
        return ">2"
    elseif match(thisline, '^#') >= 0
        return ">1"
    else
        return "="
    endif
endfunction
setlocal foldmethod=expr
setlocal foldexpr=MarkdownFolds()

Save your .vimrc file.

You should find the .vimrc file under the path ~/.vimrc.

Reload your buffer: :e, short for :edit.

Now folds should be marked. You can use zc, zm and other fold commands without having to add markers manually.

Run :h fold in vim to see all the fold commands.


  1. 1↩︎


vim markdown personal computing

No affiliate links, no analytics, no tracking, no cookies. © 2016-2023 yctct.com. Content is licensed under CC BY-NC-SA 4.0 .