Johnny Utahh
Johnny Utahh

Reputation: 2478

vim folds for asciidoc: include the line _previous_ to the section-title line

Summary. How (and if?) can I get vim folds to automatically associate the asciidoc [id=''] lines found immediately prior to a section-title line with the fold created for said section?

Details. asciidoc content enables section-title identification (that, among other things, maps to rendered-HTML-anchor-tag names and also enables intra-document cross-reference), otherwise known (I think?) as a block identifier. However, the [id=''] line blurb must be place prior to the section header line, even though it's part of the section. eg:

[id='under_construction', reftext='Under Construction']
## DISCLAIMER: This Document is Under Construction

This makes vim-folding of an asciidoc file much harder to manage, as folded-section moves "lose" the previous line (and all the section id's get shuffled), because in the eyes of the vim fold, the previous line belongs to the previous section.

Upvotes: 1

Views: 404

Answers (1)

mfedoten
mfedoten

Reputation: 123

I'm not sure how vim foldings asciidoc, but I assume that new section starts with ## (or ==, judging from a brief look at the link you provided), and [id=...] provides additional information on the section. So you could have a look at Steve Losh's markdown folding and :h fold-expr. So here is the modified code for markdown folding:

function! Fold_askiidoc(lnum)
  let l1 = getline(a:lnum)

  if l1 =~ '^\s*$'
      " assume sections are separated by blank lines
      return '0' 
  endif

  " check next line 
  let l2 = getline(a:lnum+1)

  if  l2 =~ '^#'
      " next line starts with hashes (or '=', or any symbol)
      " number of hashes specifies indent level
      return '>'.matchend(l2, '^#\+')
  else
      " otherwise keep previous foldlevel
      return '=' 
  endif
endfunction

setlocal foldexpr=Fold_test(v:lnum)
setlocal foldmethod=expr

It checks each line, if it's blank, suppose it's the end of a section. If the next line starts with #, it means the fold starts on the current line. The amount of #'s specify folding level. It folds any non-blank line before a section title, if you want it only for specific lines, like id=[''], you would have to add additional string comparison.

You can save it to $HOME/.vim/after/ftplugin/asciidoc.vim. I'm not sure about file type, if it exists or you have to create it separately. From there it should be loaded automatically each time you open specific file. Or you can just put function in your vimrc and specify setlocal foldexpr=Fold_test(v:lnum) setlocal foldmethod=expr as auto-comand for this file type.

Upvotes: 2

Related Questions