" Language:    Texte Convivial Technique (TCT)
" License:     GNU General Public License, version 3 or later (at your option)
" Maintainer:  Julien Moutinho <julm+hdoc@autogeree.net>
" URL:         git://git.autogeree.net/hdoc
" Version:     v2018-02-16
" Installation:
"  Copy this file to ~/.vim/ftplugin/tct.vim
"  then add this line to ~/.vimrc :
"  autocmd BufNewFile,BufRead *.tct set filetype=tct
if exists("b:did_ftplugin")
  finish
endif

let s:vim_tct_folding_indent = get(g:, "vim_tct_folding_indent", 0)
  " NOTE: off by default, because quite slow

"setlocal comments=fb:*,fb:-,fb:+,n:> commentstring=>\ %s
setlocal formatoptions+=tcqln formatoptions-=ro
setlocal formatlistpat=^\\s*\\d\\+\\.\\s\\+\\\|^[-*+]\\s\\+\\\|^\\[^\\ze[^\\]]\\+\\]:

if exists('b:undo_ftplugin')
  let b:undo_ftplugin .= "|setl cms< com< fo< flp<"
else
  let b:undo_ftplugin = "setl cms< com< fo< flp<"
endif

function! s:sectionLevel(lnum)
  let l = a:lnum
  while l > 0
    let l:lineCurr = getline(l)
    let l:depth = match(l:lineCurr, '\(^#\+\)\@<=\( .*$\)\@=')
    if l:depth > 0
      return l:depth
    endif
    let l = l-1
  endwhile
  return 0
endfunction

function! TctFold()
  let l:lineCurr = getline(v:lnum)

  " Fold wrt. section level
  let l:depth = match(l:lineCurr, '\(^#\+\)\@<=\( .*$\)\@=')
  if l:depth > 0
    return ">" . l:depth
  endif

  " Fold wrt. indent level
  if s:vim_tct_folding_indent == 1
   let spacesCurr = matchend(l:lineCurr,"^ *")
   return s:sectionLevel(v:lnum) + spacesCurr
  endif

  " Keep previous fold level
  return "="
endfunction

if has("folding")
  setlocal foldexpr=TctFold()
  setlocal foldmethod=expr
  let b:undo_ftplugin .= " foldexpr< foldmethod<"
endif

" vim:set sw=2: