" Error message handling
set shortmess=s   " less messages
set cmdheight=2

" Jump to To:, Cc:, Subject:
nmap <M-t> 2GA
map! <M-t> <ESC>2GA
nmap <M-c> 3GA
map! <M-c> <ESC>3GA
nmap <M-s> 4GA
map! <M-s> <ESC>4GA

" Go to first empty line and start insert mode
execute "normal /^$/\n"
execute ":startinsert"

" add two empty lines after header (where we jumped to)
execute "call append(line('.')-1, '')"
execute "call append(line('.')-1, '')"

" Email auto completion for headers
let g:qcc_query_command='khard email --parsable --remove-first-line --search-in-source-files'
setlocal omnifunc=QueryCommandComplete

" Functions

" Set tw to 5000 if in the first 4 lines, else 72
au CursorMovedI * call ModifyTextWidth() " execute when cursor has moved, use for all files
function! ModifyTextWidth()
    let line=getline('.')  " get the current line number of the cursor
    if line('.') < 5  " if line number smaller than 5
        setlocal textwidth=5000   " use high tw setting
    else
        setlocal textwidth=72 " Otherwise use normal textwidth
    endif
endfunction

function! Mail_Erase_Sig()
  " search for the signature pattern (takes into account signature delimiters
  " from broken mailers that forget the space after the two dashes)
  let i = 0
  while ((i <= line('$')) && (getline(i) !~ '^> *-- \=$'))
    let i = i + 1
  endwhile

  " if found, then
  if (i != line('$') + 1)
    " first, look for our own signature, to avoid deleting it
    let j = i
    while (j < line('$') && (getline(j + 1) !~ '^-- $'))
      let j = j + 1
    endwhile

    " second, search for the last non empty (non sig) line
    while ((i > 0) && (getline(i - 1) =~ '^\(>\s*\)*$'))
      let i = i - 1
    endwhile

    " third, delete those lines plus the signature
    exe ':'.i.','.j.'d'
  endif
endfunction

function! Mail_Erase_Own_Sig()
  let i = 0
  while ((i <= line('$')) && (getline(i) !~ '^-- \=$'))
    let i = i + 1
  endwhile

  " if found, then
  if (i != line('$') + 1)
    " first, look for our own signature, to avoid deleting it
    let j = i
    while (j < line('$') && (getline(j + 1) !~ '^-- $'))
      let j = j + 1
    endwhile

    " second, search for the last non empty (non sig) line
    while ((i > 0) && (getline(i - 1) =~ '^\(>\s*\)*$'))
      let i = i - 1
    endwhile

    " third, delete those lines plus the signature
    exe ':'.i.','.j.'d'
  endif
endfunction

function! Mail_Beginning()
  exe "normal gg"
  if getline (line ('.')) =~ '^From: '
    " if we use edit_headers in Mutt, then go after the headers
    exe "normal /^$\<CR>"
  endif
endfunction

call Mail_Erase_Own_Sig()
call Mail_Erase_Sig()
call Mail_Beginning()
