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