" Enable spelling except in Windows terminal vim.
if has('syntax') && (!has('win32') || has('gui_running'))
  setlocal spell
endif

setlocal foldmethod=expr
setlocal foldexpr=MarkdownFold(v:lnum)
setlocal conceallevel=2
setlocal concealcursor=n
setlocal commentstring=<!--%s-->

function! MarkdownFold(lnum)
  let l:line = getline(a:lnum)

  if match(l:line, '^######.*$') == 0
    return '>6'
  elseif match(l:line, '^#####.*$') == 0
    return '>5'
  elseif match(l:line, '^####.*$') == 0
    return '>4'
  elseif match(l:line, '^###.*$') == 0
    return '>3'
  elseif match(l:line, '^##.*$') == 0
    return '>2'
  elseif match(l:line, '^#.*$') == 0
    return '>1'
  endif

  return '='
endfunction

" Max 80 chars wide.
setlocal textwidth=80

" Custom surround for markdown link syntax.
" "ys{motion}l" makes link out of "word" -> "[word]()"
let b:surround_{char2nr("l")} = "[\r]()"
" "ys{motion}L" makes link out of "url" -> "[](url)"
let b:surround_{char2nr("L")} = "[](\r)"

finish " Experiment functionality (disabled). {{{

nnoremap yh :<C-U>set opfunc=<SID>yh<CR>g@
function! <SID>yh(type, ...)
  let save_reg_h = getreg('h')
  " Mark positions
  let begin = getpos("'[")[1:2]
  let end = getpos("']")[1:2]
  " Append after the end mark.
  call cursor(end)
  call setreg('h', ']()')
  normal "hp
  " Prepend before the begin mark.
  call cursor(begin)
  call setreg('h', '[')
  normal "hP
  " Place cursor at final )
  call cursor(end)
  normal f)
  call setreg('h', save_reg_h)
endfunction

" }}}