Insert Fold Marker

1 Point

Alex Alex

5 years ago

Insert foldmarker with current foldlevel. Works 'ok' most of the time, except when it's works incorrectly...

function! InsertFoldMarker(...) abort
	let l:cur_line   = getline('.')
	let l:markers    = split(&l:fmr, ',')
	let l:marker     = (a:0) && len(l:markers)>1 ? l:markers[1] : l:markers[0]
	let l:level      = foldlevel('.')
	let l:level      = l:level == 0 ? '1' : l:level
	let l:cms        = split(&l:cms, '%s')
	" TODO: handle paired comment markers
	let l:cms        = (a:0) && len(l:cms)>1 ? l:cms[1] : l:cms[0]
	if has('nvim')
		let l:marker_cnt = 0
		for c in split(l:cur_line, '\zs')
			if c == l:cms
				let l:marker_cnt += 1
			endif
		endfor
	else
		let l:marker_cnt = count(l:cur_line, l:cms)
	endif
	let l:cms        = (l:marker_cnt % 2 == 0) && (l:cur_line[0] != l:cms) ? l:cms.' ' : ''
	let l:space      = l:cur_line[-1:]  =~ '\s' || len(l:cur_line)<2 ? '' : ' '
	exe "norm! m1A".l:space.l:cms.l:marker.l:level."\<Esc>`1"
	return ''
endfunction

nnoremap <leader><Tab>  :call InsertFoldMarker()<CR>
nnoremap <leader>1<Tab> :call InsertFoldMarker(1)<CR>
inoremap <localleader><Tab>  <C-r>=InsertFoldMarker()<CR>
inoremap <localleader>1<Tab> <C-r>=InsertFoldMarker(1)<CR>