aff492667b3d1db6773bbfebe79456b0d3fb277f
[notmuch] / vim / plugin / notmuch.vim
1 " notmuch.vim plugin --- run notmuch within vim
2 "
3 " Copyright © Carl Worth
4 "
5 " This file is part of Notmuch.
6 "
7 " Notmuch is free software: you can redistribute it and/or modify it
8 " under the terms of the GNU General Public License as published by
9 " the Free Software Foundation, either version 3 of the License, or
10 " (at your option) any later version.
11 "
12 " Notmuch is distributed in the hope that it will be useful, but
13 " WITHOUT ANY WARRANTY; without even the implied warranty of
14 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 " General Public License for more details.
16 "
17 " You should have received a copy of the GNU General Public License
18 " along with Notmuch.  If not, see <http://www.gnu.org/licenses/>.
19 "
20 " Authors: Bart Trojanowski <bart@jukie.net>
21
22 " --- configuration defaults {{{1
23
24 let s:notmuch_defaults = {
25         \ 'g:notmuch_cmd':                           'notmuch'                    ,
26         \
27         \ 'g:notmuch_search_newest_first':           1                            ,
28         \ 'g:notmuch_search_from_column_width':      20                           ,
29         \
30         \ 'g:notmuch_show_fold_signatures':          1                            ,
31         \ 'g:notmuch_show_fold_citations':           1                            ,
32         \ 'g:notmuch_show_fold_bodies':              0                            ,
33         \ 'g:notmuch_show_fold_headers':             1                            ,
34         \
35         \ 'g:notmuch_show_message_begin_regexp':     '^\fmessage{'                ,
36         \ 'g:notmuch_show_message_end_regexp':       '^\fmessage}'                ,
37         \ 'g:notmuch_show_header_begin_regexp':      '^\fheader{'                 ,
38         \ 'g:notmuch_show_header_end_regexp':        '^\fheader}'                 ,
39         \ 'g:notmuch_show_body_begin_regexp':        '^\fbody{'                   ,
40         \ 'g:notmuch_show_body_end_regexp':          '^\fbody}'                   ,
41         \ 'g:notmuch_show_attachment_begin_regexp':  '^\fattachment{'             ,
42         \ 'g:notmuch_show_attachment_end_regexp':    '^\fattachment}'             ,
43         \ 'g:notmuch_show_part_begin_regexp':        '^\fpart{'                   ,
44         \ 'g:notmuch_show_part_end_regexp':          '^\fpart}'                   ,
45         \ 'g:notmuch_show_marker_regexp':            '^\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
46         \
47         \ 'g:notmuch_show_message_parse_regexp':     '\(id:[^ ]*\) depth:\([0-9]*\) filename:\(.*\)$',
48         \ 'g:notmuch_show_tags_regexp':              '(\([^)]*\))$'               ,
49         \
50         \ 'g:notmuch_show_signature_regexp':         '^\(-- \?\|_\+\)$'           ,
51         \ 'g:notmuch_show_signature_lines_max':      12                           ,
52         \
53         \ 'g:notmuch_show_citation_regexp':          '^\s*>'                      ,
54         \ }
55
56 " defaults for g:notmuch_initial_search_words
57 " override with: let g:notmuch_initial_search_words = [ ... ]
58 let s:notmuch_initial_search_words_defaults = [
59         \ 'tag:inbox and tag:unread',
60         \ ]
61
62 " defaults for g:notmuch_show_headers
63 " override with: let g:notmuch_show_headers = [ ... ]
64 let s:notmuch_show_headers_defaults = [
65         \ 'Subject',
66         \ 'To',
67         \ 'Cc',
68         \ 'Bcc',
69         \ 'Date',
70         \ ]
71
72 " defaults for g:notmuch_folders
73 " override with: let g:notmuch_folders = [ ... ]
74 let s:notmuch_folders_defaults = [
75         \ [ 'new',    'tag:inbox and tag:unread' ],
76         \ [ 'inbox',  'tag:inbox'                ],
77         \ [ 'unread', 'tag:unread'               ],
78         \ ]
79
80 " --- keyboard mapping definitions {{{1
81
82 " --- --- bindings for folders mode {{{2
83
84 let g:notmuch_folders_maps = {
85         \ 's':          ':call <SID>NM_search_prompt()<CR>',
86         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
87         \ '=':          ':call <SID>NM_folders_refresh_view()<CR>',
88         \ '<Enter>':    ':call <SID>NM_folders_show_search()<CR>',
89         \ }
90
91 " --- --- bindings for search screen {{{2
92 let g:notmuch_search_maps = {
93         \ '<Enter>':    ':call <SID>NM_search_show_thread()<CR>',
94         \ '<C-]>':      ':call <SID>NM_search_expand(''<cword>'')<CR>',
95         \ 'a':          ':call <SID>NM_search_archive_thread()<CR>',
96         \ 'f':          ':call <SID>NM_search_filter()<CR>',
97         \ 'm':          ':call <SID>NM_new_mail()<CR>',
98         \ 'o':          ':call <SID>NM_search_toggle_order()<CR>',
99         \ 'r':          ':call <SID>NM_search_reply_to_thread()<CR>',
100         \ 's':          ':call <SID>NM_search_prompt()<CR>',
101         \ ',s':         ':call <SID>NM_search_edit()<CR>',
102         \ 't':          ':call <SID>NM_search_filter_by_tag()<CR>',
103         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
104         \ '+':          ':call <SID>NM_search_add_tags([])<CR>',
105         \ '-':          ':call <SID>NM_search_remove_tags([])<CR>',
106         \ '=':          ':call <SID>NM_search_refresh_view()<CR>',
107         \ '?':          ':echo <SID>NM_search_thread_id()<CR>',
108         \ }
109
110 " --- --- bindings for show screen {{{2
111 let g:notmuch_show_maps = {
112         \ '<C-P>':      ':call <SID>NM_show_previous(1)<CR>',
113         \ '<C-N>':      ':call <SID>NM_show_next(1)<CR>',
114         \ '<C-]>':      ':call <SID>NM_search_expand(''<cword>'')<CR>',
115         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
116         \
117         \ 'b':          ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
118         \ 'c':          ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
119         \ 'h':          ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
120         \ 's':          ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
121         \
122         \ 'a':          ':call <SID>NM_show_archive_thread()<CR>',
123         \ 'A':          ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
124         \ 'N':          ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
125         \ 'v':          ':call <SID>NM_show_view_all_mime_parts()<CR>',
126         \ '+':          ':call <SID>NM_show_add_tag()<CR>',
127         \ '-':          ':call <SID>NM_show_remove_tag()<CR>',
128         \ '<Space>':    ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
129         \ '\|':         ':call <SID>NM_show_pipe_message()<CR>',
130         \
131         \ 'r':          ':call <SID>NM_show_reply()<CR>',
132         \ 'm':          ':call <SID>NM_new_mail()<CR>',
133         \ '?':          ':echo <SID>NM_show_message_id() . ''  @ '' . join(<SID>NM_show_search_words())<CR>',
134         \ }
135
136
137 " --- implement folders screen {{{1
138
139 function! s:NM_cmd_folders(words)
140         if len(a:words)
141                 echoe 'Not exapecting any arguments for folders command.'
142         endif
143         let cmd = ['count']
144         let disp = []
145         let searches = []
146         for entry in g:notmuch_folders
147                 let [ name, search ] = entry
148                 let data = s:NM_run(cmd + [search])
149                 let cnt = matchlist(data, '\(\d\+\)')[1]
150                 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
151                 call add(searches, search)
152         endfor
153
154         call <SID>NM_newBuffer('folders', join(disp, "\n"))
155         let b:nm_searches = searches
156         let b:nm_timestamp = reltime()
157
158         call <SID>NM_cmd_folders_mksyntax()
159         call <SID>NM_set_map(g:notmuch_folders_maps)
160         setlocal cursorline
161         setlocal nowrap
162 endfunction
163
164 function! s:NM_cmd_folders_mksyntax()
165 endfunction
166
167 " --- --- folders screen action functions {{{2
168
169 function! s:NM_folders_refresh_view()
170         let lno = line('.')
171         setlocal bufhidden=delete
172         call s:NM_cmd_folders([])
173         exec printf('norm %dG', lno)
174 endfunction
175
176 function! s:NM_folders_show_search()
177         let line = line('.')
178         let search = b:nm_searches[line-1]
179
180         let prev_bufnr = bufnr('%')
181         setlocal bufhidden=hide
182         call <SID>NM_cmd_search([search])
183         setlocal bufhidden=delete
184         let b:nm_prev_bufnr = prev_bufnr
185 endfunction
186
187
188 " --- implement search screen {{{1
189
190 function! s:NM_cmd_search(words)
191         let cmd = ['search']
192         if g:notmuch_search_newest_first
193                 let cmd = cmd + ['--sort=newest-first']
194         else
195                 let cmd = cmd + ['--sort=oldest-first']
196         endif
197         let data = s:NM_run(cmd + a:words)
198         let lines = split(data, "\n")
199         let disp = copy(lines)
200         call map(disp, 's:NM_cmd_search_fmtline(v:val)')
201
202         call <SID>NM_newBuffer('search', join(disp, "\n"))
203         let b:nm_raw_lines = lines
204         let b:nm_search_words = a:words
205
206         call <SID>NM_cmd_search_mksyntax()
207         call <SID>NM_set_map(g:notmuch_search_maps)
208         setlocal cursorline
209         setlocal nowrap
210 endfunction
211 function! s:NM_cmd_search_fmtline(line)
212         let m = matchlist(a:line, '^\(thread:\S\+\)\s\([^]]\+\]\) \([^;]\+\); \(.*\) (\([^(]*\))$')
213         if !len(m)
214                 return 'ERROR PARSING: ' . a:line
215         endif
216         let max = g:notmuch_search_from_column_width
217         let from = m[3]
218         if strlen(from) >= max
219                 let from = substitute(m[3][0:max-4], '[^A-Za-z1-9_]*$', '', '') . '...'
220         endif
221         return printf('%-20s %-20s | %s (%s)', m[2], from, m[4], m[5])
222 endfunction
223 function! s:NM_cmd_search_mksyntax()
224         syntax clear nmSearchFrom
225         exec printf('syntax match nmSearchFrom /\(\] \)\@<=.\{%d\}/ oneline contained', g:notmuch_search_from_column_width)
226 endfunction
227
228 " --- --- search screen action functions {{{2
229
230 function! s:NM_search_show_thread()
231         let id = <SID>NM_search_thread_id()
232         if id != ''
233                 let words = [id]
234                 if exists('b:nm_search_words')
235                         let words = ['('] + b:nm_search_words + [')', 'and', id]
236                 endif
237                 if len(words)
238                         call <SID>NM_cmd_show(words)
239                 endif
240         endif
241 endfunction
242
243 function! s:NM_search_prompt()
244         " TODO: input() can support completion
245         let text = input('NotMuch Search: ')
246         if strlen(text)
247                 let tags = split(text)
248         else
249                 let tags = s:notmuch_initial_search_words_defaults
250         endif
251         let prev_bufnr = bufnr('%')
252         if b:nm_type == 'search'
253                 " TODO: we intend to replace the current buffer,
254                 "       ... maybe we could just clear it
255                 let prev_bufnr = b:nm_prev_bufnr
256                 setlocal bufhidden=delete
257         else
258                 setlocal bufhidden=hide
259         endif
260         call <SID>NM_cmd_search(tags)
261         setlocal bufhidden=delete
262         let b:nm_prev_bufnr = prev_bufnr
263 endfunction
264
265 function! s:NM_search_edit()
266         " TODO: input() can support completion
267         let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
268         if strlen(text)
269                 call <SID>NM_cmd_search(split(text))
270         endif
271 endfunction
272
273 function! s:NM_search_archive_thread()
274         call <SID>NM_add_remove_tags_on_screen('-', ['inbox'])
275         call <SID>NM_add_remove_tags('-', ['inbox'])
276         norm j
277 endfunction
278
279 function! s:NM_search_filter()
280         call <SID>NM_search_filter_helper('Filter: ', '', '')
281 endfunction
282
283 function! s:NM_search_filter_by_tag()
284         call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
285 endfunction
286
287 function! s:NM_search_filter_helper(prompt, prefix, joiner)
288         " TODO: input() can support completion
289         let text = input(a:prompt)
290         if !strlen(text)
291                 return
292         endif
293
294         let tags = split(text)
295         if strlen(a:prefix)
296                 call map(tags, 'a:prefix . v:val')
297         endif
298         if strlen(a:joiner)
299                 let idx = len(tags) - 1
300                 while idx > 0
301                         call insert(tags, a:joiner, idx)
302                         let idx = idx - 1
303                 endwhile
304         endif
305         let tags = b:nm_search_words + ['and', '('] + tags + [')']
306
307         let prev_bufnr = bufnr('%')
308         setlocal bufhidden=hide
309         call <SID>NM_cmd_search(tags)
310         setlocal bufhidden=delete
311         let b:nm_prev_bufnr = prev_bufnr
312 endfunction
313
314 function! s:NM_search_toggle_order()
315         let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
316         " FIXME: maybe this would be better done w/o reading re-reading the lines
317         "         reversing the b:nm_raw_lines and the buffer lines would be better
318         call <SID>NM_search_refresh_view()
319 endfunction
320
321 function! s:NM_search_reply_to_thread()
322         echo 'not implemented'
323 endfunction
324
325 function! s:NM_search_add_tags(tags)
326         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
327 endfunction
328
329 function! s:NM_search_remove_tags(tags)
330         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
331 endfunction
332
333 function! s:NM_search_refresh_view()
334         let lno = line('.')
335         let prev_bufnr = b:nm_prev_bufnr
336         setlocal bufhidden=delete
337         call <SID>NM_cmd_search(b:nm_search_words)
338         let b:nm_prev_bufnr = prev_bufnr
339         " FIXME: should find the line of the thread we were on if possible
340         exec printf('norm %dG', lno)
341 endfunction
342
343 " --- --- search screen helper functions {{{2
344
345 function! s:NM_search_thread_id()
346         if !exists('b:nm_raw_lines')
347                 echoe 'no b:nm_raw_lines'
348                 return ''
349         else
350                 let line = line('.')
351                 let info = b:nm_raw_lines[line-1]
352                 let what = split(info, '\s\+')[0]
353                 return what
354         endif
355 endfunction
356
357 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
358         if type(a:intags) != type([]) || len(a:intags) == 0
359                 " TODO: input() can support completion
360                 let text = input(a:prompt)
361                 if !strlen(text)
362                         return
363                 endif
364                 let tags = split(text, ' ')
365         else
366                 let tags = a:intags
367         endif
368         call <SID>NM_add_remove_tags(a:prefix, tags)
369         call <SID>NM_add_remove_tags_on_screen(a:prefix, tags)
370 endfunction
371
372 " --- implement show screen {{{1
373
374 function! s:NM_cmd_show(words)
375         let prev_bufnr = bufnr('%')
376         let data = s:NM_run(['show'] + a:words)
377         let lines = split(data, "\n")
378
379         let info = s:NM_cmd_show_parse(lines)
380
381         setlocal bufhidden=hide
382         call <SID>NM_newBuffer('show', join(info['disp'], "\n"))
383         setlocal bufhidden=delete
384         let b:nm_words = a:words
385         let b:nm_raw_info = info
386         let b:nm_prev_bufnr = prev_bufnr
387
388         call <SID>NM_cmd_show_mkfolds()
389         call <SID>NM_cmd_show_mksyntax()
390         call <SID>NM_set_map(g:notmuch_show_maps)
391         setlocal foldtext=NM_cmd_show_foldtext()
392         setlocal fillchars=
393         setlocal foldcolumn=6
394
395 endfunction
396
397 function! s:NM_show_previous(can_change_thread)
398         let info = b:nm_raw_info
399         let lnum = line('.')
400         for msg in reverse(copy(info['msgs']))
401                 if lnum <= msg['start']
402                         continue
403                 endif
404
405                 exec printf('norm %dG', msg['start'])
406                 " TODO: try to fit the message on screen
407                 norm zz
408                 return
409         endfor
410         if !a:can_change_thread
411                 return
412         endif
413         call <SID>NM_kill_this_buffer()
414         if line('.') != line('0')
415                 norm k
416                 call <SID>NM_search_show_thread()
417                 norm G
418                 call <SID>NM_show_previous(0)
419         else
420                 echo 'No more messages.'
421         endif
422 endfunction
423
424 function! s:NM_show_next(can_change_thread)
425         let info = b:nm_raw_info
426         let lnum = line('.')
427         for msg in info['msgs']
428                 if lnum >= msg['start']
429                         continue
430                 endif
431
432                 exec printf('norm %dG', msg['start'])
433                 " TODO: try to fit the message on screen
434                 norm zz
435                 return
436         endfor
437         if !a:can_change_thread
438                 return
439         endif
440         call <SID>NM_kill_this_buffer()
441         if line('.') != line('$')
442                 norm j
443                 call <SID>NM_search_show_thread()
444         else
445                 echo 'No more messages.'
446         endif
447 endfunction
448
449 function! s:NM_show_archive_thread()
450         echo 'not implemented'
451 endfunction
452
453 function! s:NM_show_mark_read_then_archive_thread()
454         echo 'not implemented'
455 endfunction
456
457 function! s:NM_show_next_message()
458         echo 'not implemented'
459 endfunction
460
461 function! s:NM_show_mark_read_then_next_open_message()
462         echo 'not implemented'
463 endfunction
464
465 function! s:NM_show_previous_message()
466         echo 'not implemented'
467 endfunction
468
469 function! s:NM_show_reply()
470         echo 'not implemented'
471 endfunction
472
473 function! s:NM_show_view_all_mime_parts()
474         echo 'not implemented'
475 endfunction
476
477 function! s:NM_show_view_raw_message()
478         echo 'not implemented'
479 endfunction
480
481 function! s:NM_show_add_tag()
482         echo 'not implemented'
483 endfunction
484
485 function! s:NM_show_remove_tag()
486         echo 'not implemented'
487 endfunction
488
489 function! s:NM_show_advance_marking_read_and_archiving()
490         echo 'not implemented'
491 endfunction
492
493 function! s:NM_show_pipe_message()
494         echo 'not implemented'
495 endfunction
496
497 " --- --- show screen helper functions {{{2
498
499 function! s:NM_show_thread_id()
500         if !exists('b:nm_words')
501                 echoe 'no b:nm_words'
502                 return ''
503         endif
504         return b:nm_words[0]
505 endfunction
506
507 function! s:NM_show_message_id()
508         if !exists('b:nm_raw_info')
509                 echoe 'no b:nm_raw_info'
510                 return ''
511         endif
512         let info = b:nm_raw_info
513         let lnum = line('.')
514         for msg in info['msgs']
515                 if lnum > msg['end']
516                         continue
517                 endif
518
519                 return msg['id']
520         endfor
521         return ''
522 endfunction
523
524 function! s:NM_show_search_words()
525         if !exists('b:nm_words')
526                 echoe 'no b:nm_words'
527                 return []
528         endif
529         return b:nm_words
530 endfunction
531
532 function! s:NM_show_fold_toggle(key, type, fold)
533         let info = b:nm_raw_info
534         let act = 'open'
535         if a:fold
536                 let act = 'close'
537         endif
538         for fld in info['folds']
539                 if fld[0] == a:type
540                         exec printf('%dfold%s', fld[1], act)
541                 endif
542         endfor
543         exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
544 endfunction
545
546
547 " s:NM_cmd_show_parse returns the following dictionary:
548 "    'disp':     lines to display
549 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
550 "    'folds':    fold info arrays [ type, start, end ]
551 "    'foldtext': fold text indexed by start line
552 function! s:NM_cmd_show_parse(inlines)
553         let info = { 'disp': [],       
554                    \ 'msgs': [],       
555                    \ 'folds': [],      
556                    \ 'foldtext': {} }  
557         let msg = {}
558         let hdr = {}
559
560         let in_message = 0
561         let in_header = 0
562         let in_body = 0
563         let in_part = ''
564
565         let body_start = -1
566         let part_start = -1
567
568         let mode_type = ''
569         let mode_start = -1
570
571         let inlnum = 0
572         for line in a:inlines
573                 let inlnum = inlnum + 1
574                 let foldinfo = []
575
576                 if strlen(in_part)
577                         let part_end = 0
578
579                         if match(line, g:notmuch_show_part_end_regexp) != -1
580                                 let part_end = len(info['disp'])
581                         else
582                                 call add(info['disp'], line)
583                         endif
584
585                         if in_part == 'text/plain'
586                                 if !part_end && mode_type == ''
587                                         if match(line, g:notmuch_show_signature_regexp) != -1
588                                                 let mode_type = 'sig'
589                                                 let mode_start = len(info['disp'])
590                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
591                                                 let mode_type = 'cit'
592                                                 let mode_start = len(info['disp'])
593                                         endif
594                                 elseif mode_type == 'cit'
595                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
596                                                 let outlnum = len(info['disp'])
597                                                 let foldinfo = [ mode_type, mode_start, outlnum-1,
598                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
599                                                 let mode_type = ''
600                                         endif
601                                 elseif mode_type == 'sig'
602                                         let outlnum = len(info['disp'])
603                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
604                                                 let mode_type = ''
605                                         elseif part_end
606                                                 let foldinfo = [ mode_type, mode_start, outlnum-1,
607                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
608                                                 let mode_type = ''
609                                         endif
610                                 endif
611                         endif
612
613                         if part_end
614                                 " FIXME: this is a hack for handling two folds being added for one line
615                                 "         we should handle addinga fold in a function
616                                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
617                                         call add(info['folds'], foldinfo[0:2])
618                                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
619                                 endif
620
621                                 let foldinfo = [ 'text', part_start, part_end,
622                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
623                                 let in_part = ''
624                                 call add(info['disp'], '')
625                         endif
626
627                 elseif in_body
628                         if !has_key(msg,'body_start')
629                                 let msg['body_start'] = len(info['disp']) + 1
630                         endif
631                         if match(line, g:notmuch_show_body_end_regexp) != -1
632                                 let body_end = len(info['disp'])
633                                 let foldinfo = [ 'bdy', body_start, body_end,
634                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
635
636                                 let in_body = 0
637
638                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
639                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
640                                 let in_part = 'unknown'
641                                 if len(m)
642                                         let in_part = m[2]
643                                 endif
644                                 call add(info['disp'],
645                                          \ printf('--- %s ---', in_part))
646                                 let part_start = len(info['disp']) + 1
647                         endif
648
649                 elseif in_header
650                         if in_header == 1
651                                 let msg['descr'] = line
652                                 call add(info['disp'], line)
653                                 let in_header = 2
654                                 let msg['hdr_start'] = len(info['disp']) + 1
655
656                         else
657                                 if match(line, g:notmuch_show_header_end_regexp) != -1
658                                         let hdr_start = msg['hdr_start']+1
659                                         let hdr_end = len(info['disp'])
660                                         let foldinfo = [ 'hdr', hdr_start, hdr_end,
661                                                \ printf('[ %d-line headers.  Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
662                                         let msg['header'] = hdr
663                                         let in_header = 0
664                                         let hdr = {}
665                                 else
666                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
667                                         if len(m)
668                                                 let hdr[m[1]] = m[2]
669                                                 if match(g:notmuch_show_headers, m[1]) != -1
670                                                         call add(info['disp'], line)
671                                                 endif
672                                         endif
673                                 endif
674                         endif
675
676                 elseif in_message
677                         if match(line, g:notmuch_show_message_end_regexp) != -1
678                                 let msg['end'] = len(info['disp'])
679                                 call add(info['disp'], '')
680
681                                 let foldinfo = [ 'msg', msg['start'], msg['end'],
682                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
683
684                                 call add(info['msgs'], msg)
685                                 let msg = {}
686                                 let in_message = 0
687                                 let in_header = 0
688                                 let in_body = 0
689                                 let in_part = ''
690
691                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
692                                 let in_header = 1
693                                 continue
694
695                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
696                                 let body_start = len(info['disp']) + 1
697                                 let in_body = 1
698                                 continue
699                         endif
700
701                 else
702                         if match(line, g:notmuch_show_message_begin_regexp) != -1
703                                 let msg['start'] = len(info['disp']) + 1
704
705                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
706                                 if len(m)
707                                         let msg['id'] = m[1]
708                                         let msg['depth'] = m[2]
709                                         let msg['filename'] = m[3]
710                                 endif
711
712                                 let in_message = 1
713                         endif
714                 endif
715
716                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
717                         call add(info['folds'], foldinfo[0:2])
718                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
719                 endif
720         endfor
721         return info
722 endfunction
723
724 function! s:NM_cmd_show_mkfolds()
725         let info = b:nm_raw_info
726
727         for afold in info['folds']
728                 exec printf('%d,%dfold', afold[1], afold[2])
729                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
730                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
731                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
732                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
733                         exec printf('%dfoldclose', afold[1])
734                 else
735                         exec printf('%dfoldopen', afold[1])
736                 endif
737         endfor
738 endfunction
739
740 function! s:NM_cmd_show_mksyntax()
741         let info = b:nm_raw_info
742         let cnt = 0
743         for msg in info['msgs']
744                 let cnt = cnt + 1
745                 let start = msg['start']
746                 let hdr_start = msg['hdr_start']
747                 let body_start = msg['body_start']
748                 let end = msg['end']
749                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
750                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
751                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
752         endfor
753 endfunction
754
755 function! NM_cmd_show_foldtext()
756         let foldtext = b:nm_raw_info['foldtext']
757         return foldtext[v:foldstart]
758 endfunction
759
760
761 " --- notmuch helper functions {{{1
762
763 function! s:NM_newBuffer(type, content)
764         enew
765         setlocal buftype=nofile readonly modifiable
766         silent put=a:content
767         keepjumps 0d
768         setlocal nomodifiable
769         execute printf('set filetype=notmuch-%s', a:type)
770         execute printf('set syntax=notmuch-%s', a:type)
771         let b:nm_type = a:type
772 endfunction
773
774 function! s:NM_shell_escape(word)
775         let word = substitute(a:word, '''', '\\''', 'g')
776         return '''' . word . ''''
777 endfunction
778
779 function! s:NM_run(args)
780         let words = a:args
781         call map(words, 's:NM_shell_escape(v:val)')
782         let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
783
784         let start = reltime()
785         let out = system(cmd)
786         let err = v:shell_error
787         let delta = reltime(start)
788
789         echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
790
791         if err
792                 echohl Error
793                 echo substitute(out, '\n*$', '', '')
794                 echohl None
795                 return ''
796         else
797                 return out
798         endif
799 endfunction
800
801 " --- external mail handling helpers {{{1
802
803 function! s:NM_new_mail()
804         echo 'not implemented'
805 endfunction
806
807 " --- other helpers {{{1
808
809 function! s:NM_kill_this_buffer()
810         if exists('b:nm_prev_bufnr')
811                 setlocal bufhidden=delete
812                 exec printf(":buffer %d", b:nm_prev_bufnr)
813         else
814                 echo "This is the last buffer; use :q<CR> to quit."
815         endif
816 endfunction
817
818 function! s:NM_search_expand(arg)
819         let word = expand(a:arg)
820         let prev_bufnr = bufnr('%')
821         setlocal bufhidden=hide
822         call <SID>NM_cmd_search([word])
823         setlocal bufhidden=delete
824         let b:nm_prev_bufnr = prev_bufnr
825 endfunction
826
827 function! s:NM_add_remove_tags(prefix, tags)
828         let id = <SID>NM_search_thread_id()
829         if id == ''
830                 echoe 'Eeek! I couldn''t find the thead id!'
831         endif
832         call map(a:tags, 'a:prefix . v:val')
833         " TODO: handle errors
834         call <SID>NM_run(['tag'] + a:tags + ['--', id])
835 endfunction
836
837 function! s:NM_add_remove_tags_on_screen(prefix, tags)
838         let online = ''
839         setlocal modifiable
840         if a:prefix == '-'
841                 for tagname in a:tags
842                         exec printf('silent %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', online, tagname)
843                 endfor
844         else
845                 for tagname in a:tags
846                         exec printf('silent %ss/(\([^)]*\)\([^)]*\))$/(\1 %s)/', online, tagname)
847                 endfor
848         endif
849         setlocal nomodifiable
850 endfunction
851
852 " --- process and set the defaults {{{1
853
854 function! NM_set_defaults(force)
855         for [key, dflt] in items(s:notmuch_defaults)
856                 let cmd = ''
857                 if !a:force && exists(key) && type(dflt) == type(eval(key))
858                         continue
859                 elseif type(dflt) == type(0)
860                         let cmd = printf('let %s = %d', key, dflt)
861                 elseif type(dflt) == type('')
862                         let cmd = printf('let %s = ''%s''', key, dflt)
863                 " FIXME: not sure why this didn't work when dflt is an array
864                 "elseif type(dflt) == type([])
865                 "        let cmd = printf('let %s = %s', key, string(dflt))
866                 else
867                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
868                                                 \ a:force, key, string(dflt))
869                         continue
870                 endif
871                 exec cmd
872         endfor
873 endfunction
874 call NM_set_defaults(0)
875
876 " for some reason NM_set_defaults() didn't work for arrays...
877 if !exists('g:notmuch_show_headers')
878         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
879 endif
880 if !exists('g:notmuch_initial_search_words')
881         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
882 endif
883 if !exists('g:notmuch_folders')
884         let g:notmuch_folders = s:notmuch_folders_defaults
885 endif
886
887
888 " --- assign keymaps {{{1
889
890 function! s:NM_set_map(maps)
891         nmapclear
892         for [key, code] in items(a:maps)
893                 exec printf('nnoremap <buffer> %s %s', key, code)
894         endfor
895         " --- this is a hack for development :)
896         nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
897 endfunction
898
899 " --- command handler {{{1
900
901 function! NotMuch(args)
902         let args = a:args
903         if !strlen(args)
904                 let args = 'folders'
905         endif
906
907         let words = split(args)
908         if words[0] == 'folders'
909                 let words = words[1:]
910                 call <SID>NM_cmd_folders(words)
911         elseif words[0] == 'search'
912                 if len(words) > 1
913                         let words = words[1:]
914                 elseif exists('b:nm_search_words')
915                         let words = b:nm_search_words
916                 else
917                         let words = g:notmuch_initial_search_words
918                 endif
919                 call <SID>NM_cmd_search(words)
920
921         elseif words[0] == 'show'
922                 echoe 'show is not yet implemented.'
923         endif
924 endfunction
925 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
926         return []
927 endfunction
928
929
930 " --- glue {{{1
931
932 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
933 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
934
935 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :