vimyamlfolding

Define custom folding for YAML files in VIM


I have a YAML formatted text file, and would like to define custom folding for VIM, but I'm not sure how to go about it (despite reading the VIM documentation for folding). The file consists of YAML "documents", like so:

---
title: My Title
attr1: value1
attr2: value2
---
title: Next Item
attr1: value3
---
title: One More Item
...

I would like the resulting folded text to look something like this:

+---- 2 lines: My Title ----
+---- ? lines: Next Item ---

Any suggestions are appreciated! Thanks!


Solution

  • Do

    %s/---\(.*\)\(\_.\{-}title: \)\(.*\)/---\1 #{{{1 \3\2\3/g
    set foldmethod=marker
    

    or

    %s/\(---\_.\{-}title: \)\(.*\)/#{{{1 \2\r\1\2/g
    set foldmethod=marker
    

    That will add comment with title to the beginning of every YAML document and leave document still valid. foldmarker option must be left untouched.

    Result:

    1.

    --- #{{{1 My Title
    title: My Title
    attr1: value1
    attr2: value2
    --- #{{{1 Next Item
    title: Next Item
    attr1: value3
    --- #{{{1 One More Item
    title: One More Item
    ...
    

    Folded:

    +--  4 строк: --- My Title-----------------------------
    +--  3 строк: --- Next Item----------------------------
    +--  3 строк: --- One More Item------------------------
    

    2.

    #{{{1 My Title
    ---
    title: My Title
    attr1: value1
    attr2: value2
    #{{{1 Next Item
    ---
    title: Next Item
    attr1: value3
    #{{{1 One More Item
    ---
    title: One More Item
    ...
    

    Folded:

    +--  5 строк: My Title--------------------------------
    +--  4 строк: Next Item-------------------------------
    +--  4 строк: One More Item---------------------------