]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
vim: have ? show details of what's under cursor in search/show views
[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_thread_id() . '' '' . <SID>NM_show_message_id()<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('%s %-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                 call <SID>NM_cmd_show([id])
234         endif
235 endfunction
236
237 function! s:NM_search_prompt()
238         " TODO: input() can support completion
239         let text = input('NotMuch Search: ')
240         if strlen(text)
241                 let tags = split(text)
242         else
243                 let tags = s:notmuch_initial_search_words_defaults
244         endif
245         if b:nm_type == 'search'
246                 " TODO: we intend to replace the current buffer,
247                 "       ... maybe we could just clear it
248                 let prev_bufnr = b:nm_prev_bufnr
249                 setlocal bufhidden=delete
250         else
251                 let prev_bufnr = bufnr('%')
252                 setlocal bufhidden=hide
253         endif
254         call <SID>NM_cmd_search(tags)
255         setlocal bufhidden=delete
256         let b:nm_prev_bufnr = prev_bufnr
257 endfunction
258
259 function! s:NM_search_edit()
260         " TODO: input() can support completion
261         let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
262         if strlen(text)
263                 call <SID>NM_cmd_search(split(text))
264         endif
265 endfunction
266
267 function! s:NM_search_archive_thread()
268         call <SID>NM_add_remove_tags_on_screen('-', ['inbox'])
269         call <SID>NM_add_remove_tags('-', ['inbox'])
270         norm j
271 endfunction
272
273 function! s:NM_search_filter()
274         call <SID>NM_search_filter_helper('Filter: ', '')
275 endfunction
276
277 function! s:NM_search_filter_by_tag()
278         call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:')
279 endfunction
280
281 function! s:NM_search_filter_helper(prompt, prefix)
282         " TODO: input() can support completion
283         let text = input(a:prompt)
284         if !strlen(text)
285                 return
286         endif
287
288         let tags = split(text)
289         map(tags, 'and a:prefix . v:val')
290         let tags = b:nm_search_words + tags
291         echo tags
292
293         let prev_bufnr = bufnr('%')
294         setlocal bufhidden=hide
295         call <SID>NM_cmd_search(tags)
296         setlocal bufhidden=delete
297         let b:nm_prev_bufnr = prev_bufnr
298 endfunction
299
300 function! s:NM_search_toggle_order()
301         let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
302         " FIXME: maybe this would be better done w/o reading re-reading the lines
303         "         reversing the b:nm_raw_lines and the buffer lines would be better
304         call <SID>NM_search_refresh_view()
305 endfunction
306
307 function! s:NM_search_reply_to_thread()
308         echo 'not implemented'
309 endfunction
310
311 function! s:NM_search_add_tags(tags)
312         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
313 endfunction
314
315 function! s:NM_search_remove_tags(tags)
316         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
317 endfunction
318
319 function! s:NM_search_refresh_view()
320         let lno = line('.')
321         setlocal bufhidden=delete
322         call <SID>NM_cmd_search(b:nm_search_words)
323         " FIXME: should find the line of the thread we were on if possible
324         exec printf('norm %dG', lno)
325 endfunction
326
327 " --- --- search screen helper functions {{{2
328
329 function! s:NM_search_thread_id()
330         if !exists('b:nm_raw_lines')
331                 echoe 'no b:nm_raw_lines'
332                 return ''
333         else
334                 let line = line('.')
335                 let info = b:nm_raw_lines[line-1]
336                 let what = split(info, '\s\+')[0]
337                 return what
338         endif
339 endfunction
340
341 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
342         if type(a:intags) != type([]) || len(a:intags) == 0
343                 " TODO: input() can support completion
344                 let text = input(a:prompt)
345                 if !strlen(text)
346                         return
347                 endif
348                 let tags = split(text, ' ')
349         else
350                 let tags = a:intags
351         endif
352         call <SID>NM_add_remove_tags(a:prefix, tags)
353         call <SID>NM_add_remove_tags_on_screen(a:prefix, tags)
354 endfunction
355
356 " --- implement show screen {{{1
357
358 function! s:NM_cmd_show(words)
359         let prev_bufnr = bufnr('%')
360         let data = s:NM_run(['show'] + a:words)
361         let lines = split(data, "\n")
362
363         let info = s:NM_cmd_show_parse(lines)
364
365         setlocal bufhidden=hide
366         call <SID>NM_newBuffer('show', join(info['disp'], "\n"))
367         setlocal bufhidden=delete
368         let b:nm_words = a:words
369         let b:nm_raw_info = info
370         let b:nm_prev_bufnr = prev_bufnr
371
372         call <SID>NM_cmd_show_mkfolds()
373         call <SID>NM_cmd_show_mksyntax()
374         call <SID>NM_set_map(g:notmuch_show_maps)
375         setlocal foldtext=NM_cmd_show_foldtext()
376         setlocal fillchars=
377         setlocal foldcolumn=6
378
379 endfunction
380
381 function! s:NM_show_previous(can_change_thread)
382         let info = b:nm_raw_info
383         let lnum = line('.')
384         for msg in reverse(copy(info['msgs']))
385                 if lnum <= msg['start']
386                         continue
387                 endif
388
389                 exec printf('norm %dG', msg['start'])
390                 " TODO: try to fit the message on screen
391                 norm zz
392                 return
393         endfor
394         if !a:can_change_thread
395                 return
396         endif
397         call <SID>NM_kill_this_buffer()
398         if line('.') != line('0')
399                 norm k
400                 call <SID>NM_search_show_thread()
401                 norm G
402                 call <SID>NM_show_previous(0)
403         else
404                 echo 'No more messages.'
405         endif
406 endfunction
407
408 function! s:NM_show_next(can_change_thread)
409         let info = b:nm_raw_info
410         let lnum = line('.')
411         for msg in info['msgs']
412                 if lnum >= msg['start']
413                         continue
414                 endif
415
416                 exec printf('norm %dG', msg['start'])
417                 " TODO: try to fit the message on screen
418                 norm zz
419                 return
420         endfor
421         if !a:can_change_thread
422                 return
423         endif
424         call <SID>NM_kill_this_buffer()
425         if line('.') != line('$')
426                 norm j
427                 call <SID>NM_search_show_thread()
428         else
429                 echo 'No more messages.'
430         endif
431 endfunction
432
433 function! s:NM_show_archive_thread()
434         echo 'not implemented'
435 endfunction
436
437 function! s:NM_show_mark_read_then_archive_thread()
438         echo 'not implemented'
439 endfunction
440
441 function! s:NM_show_next_message()
442         echo 'not implemented'
443 endfunction
444
445 function! s:NM_show_mark_read_then_next_open_message()
446         echo 'not implemented'
447 endfunction
448
449 function! s:NM_show_previous_message()
450         echo 'not implemented'
451 endfunction
452
453 function! s:NM_show_reply()
454         echo 'not implemented'
455 endfunction
456
457 function! s:NM_show_view_all_mime_parts()
458         echo 'not implemented'
459 endfunction
460
461 function! s:NM_show_view_raw_message()
462         echo 'not implemented'
463 endfunction
464
465 function! s:NM_show_add_tag()
466         echo 'not implemented'
467 endfunction
468
469 function! s:NM_show_remove_tag()
470         echo 'not implemented'
471 endfunction
472
473 function! s:NM_show_advance_marking_read_and_archiving()
474         echo 'not implemented'
475 endfunction
476
477 function! s:NM_show_pipe_message()
478         echo 'not implemented'
479 endfunction
480
481 " --- --- show screen helper functions {{{2
482
483 function! s:NM_show_thread_id()
484         if !exists('b:nm_words')
485                 echoe 'no b:nm_words'
486                 return ''
487         endif
488         return b:nm_words[0]
489 endfunction
490
491 function! s:NM_show_message_id()
492         if !exists('b:nm_raw_info')
493                 echoe 'no b:nm_raw_info'
494                 return ''
495         endif
496         let info = b:nm_raw_info
497         let lnum = line('.')
498         for msg in info['msgs']
499                 if lnum < msg['start']
500                         continue
501                 endif
502
503                 return msg['id']
504         endfor
505         return ''
506 endfunction
507
508 function! s:NM_show_fold_toggle(key, type, fold)
509         let info = b:nm_raw_info
510         let act = 'open'
511         if a:fold
512                 let act = 'close'
513         endif
514         for fld in info['folds']
515                 if fld[0] == a:type
516                         exec printf('%dfold%s', fld[1], act)
517                 endif
518         endfor
519         exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
520 endfunction
521
522
523 " s:NM_cmd_show_parse returns the following dictionary:
524 "    'disp':     lines to display
525 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
526 "    'folds':    fold info arrays [ type, start, end ]
527 "    'foldtext': fold text indexed by start line
528 function! s:NM_cmd_show_parse(inlines)
529         let info = { 'disp': [],       
530                    \ 'msgs': [],       
531                    \ 'folds': [],      
532                    \ 'foldtext': {} }  
533         let msg = {}
534         let hdr = {}
535
536         let in_message = 0
537         let in_header = 0
538         let in_body = 0
539         let in_part = ''
540
541         let body_start = -1
542         let part_start = -1
543
544         let mode_type = ''
545         let mode_start = -1
546
547         let inlnum = 0
548         for line in a:inlines
549                 let inlnum = inlnum + 1
550                 let foldinfo = []
551
552                 if strlen(in_part)
553                         let part_end = 0
554
555                         if match(line, g:notmuch_show_part_end_regexp) != -1
556                                 let part_end = len(info['disp'])
557                         else
558                                 call add(info['disp'], line)
559                         endif
560
561                         if in_part == 'text/plain'
562                                 if !part_end && mode_type == ''
563                                         if match(line, g:notmuch_show_signature_regexp) != -1
564                                                 let mode_type = 'sig'
565                                                 let mode_start = len(info['disp'])
566                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
567                                                 let mode_type = 'cit'
568                                                 let mode_start = len(info['disp'])
569                                         endif
570                                 elseif mode_type == 'cit'
571                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
572                                                 let outlnum = len(info['disp'])
573                                                 let foldinfo = [ mode_type, mode_start, outlnum-1,
574                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
575                                                 let mode_type = ''
576                                         endif
577                                 elseif mode_type == 'sig'
578                                         let outlnum = len(info['disp'])
579                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
580                                                 let mode_type = ''
581                                         elseif part_end
582                                                 let foldinfo = [ mode_type, mode_start, outlnum-1,
583                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
584                                                 let mode_type = ''
585                                         endif
586                                 endif
587                         endif
588
589                         if part_end
590                                 " FIXME: this is a hack for handling two folds being added for one line
591                                 "         we should handle addinga fold in a function
592                                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
593                                         call add(info['folds'], foldinfo[0:2])
594                                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
595                                 endif
596
597                                 let foldinfo = [ 'text', part_start, part_end,
598                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
599                                 let in_part = ''
600                                 call add(info['disp'], '')
601                         endif
602
603                 elseif in_body
604                         if !has_key(msg,'body_start')
605                                 let msg['body_start'] = len(info['disp']) + 1
606                         endif
607                         if match(line, g:notmuch_show_body_end_regexp) != -1
608                                 let body_end = len(info['disp'])
609                                 let foldinfo = [ 'bdy', body_start, body_end,
610                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
611
612                                 let in_body = 0
613
614                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
615                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
616                                 let in_part = 'unknown'
617                                 if len(m)
618                                         let in_part = m[2]
619                                 endif
620                                 call add(info['disp'],
621                                          \ printf('--- %s ---', in_part))
622                                 let part_start = len(info['disp']) + 1
623                         endif
624
625                 elseif in_header
626                         if in_header == 1
627                                 let msg['descr'] = line
628                                 call add(info['disp'], line)
629                                 let in_header = 2
630                                 let msg['hdr_start'] = len(info['disp']) + 1
631
632                         else
633                                 if match(line, g:notmuch_show_header_end_regexp) != -1
634                                         let hdr_start = msg['hdr_start']+1
635                                         let hdr_end = len(info['disp'])
636                                         let foldinfo = [ 'hdr', hdr_start, hdr_end,
637                                                \ printf('[ %d-line headers.  Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
638                                         let msg['header'] = hdr
639                                         let in_header = 0
640                                         let hdr = {}
641                                 else
642                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
643                                         if len(m)
644                                                 let hdr[m[1]] = m[2]
645                                                 if match(g:notmuch_show_headers, m[1]) != -1
646                                                         call add(info['disp'], line)
647                                                 endif
648                                         endif
649                                 endif
650                         endif
651
652                 elseif in_message
653                         if match(line, g:notmuch_show_message_end_regexp) != -1
654                                 let msg['end'] = len(info['disp'])
655                                 call add(info['disp'], '')
656
657                                 let foldinfo = [ 'msg', msg['start'], msg['end'],
658                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
659
660                                 call add(info['msgs'], msg)
661                                 let msg = {}
662                                 let in_message = 0
663                                 let in_header = 0
664                                 let in_body = 0
665                                 let in_part = ''
666
667                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
668                                 let in_header = 1
669                                 continue
670
671                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
672                                 let body_start = len(info['disp']) + 1
673                                 let in_body = 1
674                                 continue
675                         endif
676
677                 else
678                         if match(line, g:notmuch_show_message_begin_regexp) != -1
679                                 let msg['start'] = len(info['disp']) + 1
680
681                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
682                                 if len(m)
683                                         let msg['id'] = m[1]
684                                         let msg['depth'] = m[2]
685                                         let msg['filename'] = m[3]
686                                 endif
687
688                                 let in_message = 1
689                         endif
690                 endif
691
692                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
693                         call add(info['folds'], foldinfo[0:2])
694                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
695                 endif
696         endfor
697         return info
698 endfunction
699
700 function! s:NM_cmd_show_mkfolds()
701         let info = b:nm_raw_info
702
703         for afold in info['folds']
704                 exec printf('%d,%dfold', afold[1], afold[2])
705                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
706                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
707                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
708                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
709                         exec printf('%dfoldclose', afold[1])
710                 else
711                         exec printf('%dfoldopen', afold[1])
712                 endif
713         endfor
714 endfunction
715
716 function! s:NM_cmd_show_mksyntax()
717         let info = b:nm_raw_info
718         let cnt = 0
719         for msg in info['msgs']
720                 let cnt = cnt + 1
721                 let start = msg['start']
722                 let hdr_start = msg['hdr_start']
723                 let body_start = msg['body_start']
724                 let end = msg['end']
725                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
726                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
727                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
728         endfor
729 endfunction
730
731 function! NM_cmd_show_foldtext()
732         let foldtext = b:nm_raw_info['foldtext']
733         return foldtext[v:foldstart]
734 endfunction
735
736
737 " --- notmuch helper functions {{{1
738
739 function! s:NM_newBuffer(type, content)
740         enew
741         setlocal buftype=nofile readonly modifiable
742         silent put=a:content
743         keepjumps 0d
744         setlocal nomodifiable
745         execute printf('set filetype=notmuch-%s', a:type)
746         execute printf('set syntax=notmuch-%s', a:type)
747         let b:nm_type = a:type
748 endfunction
749
750 function! s:NM_run(args)
751         let cmd = g:notmuch_cmd . ' ' . join(a:args) . '< /dev/null'
752
753         let start = reltime()
754         let out = system(cmd)
755         let err = v:shell_error
756         let delta = reltime(start)
757
758         echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
759
760         if err
761                 echohl Error
762                 echo substitute(out, '\n*$', '', '')
763                 echohl None
764                 return ''
765         else
766                 return out
767         endif
768 endfunction
769
770 " --- external mail handling helpers {{{1
771
772 function! s:NM_new_mail()
773         echo 'not implemented'
774 endfunction
775
776 " --- other helpers {{{1
777
778 function! s:NM_kill_this_buffer()
779         if exists('b:nm_prev_bufnr')
780                 setlocal bufhidden=delete
781                 exec printf(":buffer %d", b:nm_prev_bufnr)
782         else
783                 echo "Nothing to kill."
784         endif
785 endfunction
786
787 function! s:NM_search_expand(arg)
788         let word = expand(a:arg)
789         let prev_bufnr = bufnr('%')
790         setlocal bufhidden=hide
791         call <SID>NM_cmd_search([word])
792         setlocal bufhidden=delete
793         let b:nm_prev_bufnr = prev_bufnr
794 endfunction
795
796 function! s:NM_add_remove_tags(prefix, tags)
797         let id = <SID>NM_search_thread_id()
798         if id == ''
799                 echoe 'Eeek! I couldn''t find the thead id!'
800         endif
801         call map(a:tags, 'a:prefix . v:val')
802         " TODO: handle errors
803         call <SID>NM_run(['tag'] + a:tags + ['--', id])
804 endfunction
805
806 function! s:NM_add_remove_tags_on_screen(prefix, tags)
807         let online = ''
808         setlocal modifiable
809         if a:prefix == '-'
810                 for tagname in a:tags
811                         exec printf('silent %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', online, tagname)
812                 endfor
813         else
814                 for tagname in a:tags
815                         exec printf('silent %ss/(\([^)]*\)\([^)]*\))$/(\1 %s)/', online, tagname)
816                 endfor
817         endif
818         setlocal nomodifiable
819 endfunction
820
821 " --- process and set the defaults {{{1
822
823 function! NM_set_defaults(force)
824         for [key, dflt] in items(s:notmuch_defaults)
825                 let cmd = ''
826                 if !a:force && exists(key) && type(dflt) == type(eval(key))
827                         continue
828                 elseif type(dflt) == type(0)
829                         let cmd = printf('let %s = %d', key, dflt)
830                 elseif type(dflt) == type('')
831                         let cmd = printf('let %s = ''%s''', key, dflt)
832                 " FIXME: not sure why this didn't work when dflt is an array
833                 "elseif type(dflt) == type([])
834                 "        let cmd = printf('let %s = %s', key, string(dflt))
835                 else
836                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
837                                                 \ a:force, key, string(dflt))
838                         continue
839                 endif
840                 exec cmd
841         endfor
842 endfunction
843 call NM_set_defaults(0)
844
845 " for some reason NM_set_defaults() didn't work for arrays...
846 if !exists('g:notmuch_show_headers')
847         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
848 endif
849 if !exists('g:notmuch_initial_search_words')
850         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
851 endif
852 if !exists('g:notmuch_folders')
853         let g:notmuch_folders = s:notmuch_folders_defaults
854 endif
855
856
857 " --- assign keymaps {{{1
858
859 function! s:NM_set_map(maps)
860         nmapclear
861         for [key, code] in items(a:maps)
862                 exec printf('nnoremap <buffer> %s %s', key, code)
863         endfor
864         " --- this is a hack for development :)
865         nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
866 endfunction
867
868 " --- command handler {{{1
869
870 function! NotMuch(args)
871         let args = a:args
872         if !strlen(args)
873                 let args = 'folders'
874         endif
875
876         let words = split(args)
877         if words[0] == 'folders'
878                 let words = words[1:]
879                 call <SID>NM_cmd_folders(words)
880         elseif words[0] == 'search'
881                 if len(words) > 1
882                         let words = words[1:]
883                 elseif exists('b:nm_search_words')
884                         let words = b:nm_search_words
885                 else
886                         let words = g:notmuch_initial_search_words
887                 endif
888                 call <SID>NM_cmd_search(words)
889
890         elseif words[0] == 'show'
891                 echoe 'show is not yet implemented.'
892         endif
893 endfunction
894 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
895         return []
896 endfunction
897
898
899 " --- glue {{{1
900
901 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
902 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
903
904 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :