aboutsummaryrefslogtreecommitdiff
path: root/vim/autoload/mail/header.vim
blob: 7a360a2ca29a235e3d8ca376618ecbbf2fafe505 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
" Parse a mail header into a list of dictionaries with 'name' and 'body' keys;
" preserve case of the name and whitespace in body, including leading space
"
function! mail#header#Read() abort
  let fields = []
  for lnum in range(1, line('$'))
    let line = getline(lnum)
    let matchlist = matchlist(
          \ line,
          \ '^\([a-zA-Z0-9-]\+\):\s*\(\_.*\)',
          \)
    if !empty(matchlist)
      let field = {
            \ 'name': matchlist[1],
            \ 'body': matchlist[2],
            \}
      call add(fields, field)
    elseif line =~ '^\s' && exists('field')
      let field['body'] .= "\n" . line
    elseif line ==# ''
      break
    else
      throw 'Parse error'
    endif
  endfor
  let header = {
        \'fields': fields,
        \}
  return header
endfunction

" Flatten a header data structure into a string
function! mail#header#String(header) abort
  let fields = copy(a:header['fields'])
  return join(
        \ map(
          \ copy(a:header['fields']),
          \ 'v:val[''name''] . '': '' . v:val[''body''] . "\n"'),
        \ '',
        \)
endfunction

" Replace existing mail header with the provided one
function! mail#header#Write(header) abort
  let start = 1
  for lnum in range(1, line('$'))
    if getline(lnum) ==# ''
      break
    endif
    let end = lnum
  endfor
  let curpos = getpos('.')
  if exists('end')
    let range = join([start, end], ',')
    execute join(['silent', range, 'delete'])
  endif
  silent 0 put =mail#header#String(a:header)
  call setpos('.', curpos)
endfunction