]> git.notmuchmail.org Git - notmuch/blob - contrib/notmuch-vim/plugin/notmuch.vim
lib: update cached mtime in notmuch_directory_set_mtime
[notmuch] / contrib / 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 <https://www.gnu.org/licenses/>.
19 "
20 " Authors: Bart Trojanowski <bart@jukie.net>
21 " Contributors: Felipe Contreras <felipe.contreras@gmail.com>,
22 "   Peter Hartman <peterjohnhartman@gmail.com>
23 "
24 " --- configuration defaults {{{1
25
26 let s:notmuch_defaults = {
27         \ 'g:notmuch_cmd':                           'notmuch'                    ,
28         \ 'g:notmuch_sendmail':                      '/usr/sbin/sendmail'         ,
29         \ 'g:notmuch_debug':                         0                            ,
30         \
31         \ 'g:notmuch_search_newest_first':           1                            ,
32         \ 'g:notmuch_search_from_column_width':      20                           ,
33         \
34         \ 'g:notmuch_show_fold_signatures':          1                            ,
35         \ 'g:notmuch_show_fold_citations':           1                            ,
36         \ 'g:notmuch_show_fold_bodies':              0                            ,
37         \ 'g:notmuch_show_fold_headers':             1                            ,
38         \
39         \ 'g:notmuch_show_message_begin_regexp':     '\fmessage{'                ,
40         \ 'g:notmuch_show_message_end_regexp':       '\fmessage}'                ,
41         \ 'g:notmuch_show_header_begin_regexp':      '\fheader{'                 ,
42         \ 'g:notmuch_show_header_end_regexp':        '\fheader}'                 ,
43         \ 'g:notmuch_show_body_begin_regexp':        '\fbody{'                   ,
44         \ 'g:notmuch_show_body_end_regexp':          '\fbody}'                   ,
45         \ 'g:notmuch_show_attachment_begin_regexp':  '\fattachment{'             ,
46         \ 'g:notmuch_show_attachment_end_regexp':    '\fattachment}'             ,
47         \ 'g:notmuch_show_part_begin_regexp':        '\fpart{'                   ,
48         \ 'g:notmuch_show_part_end_regexp':          '\fpart}'                   ,
49         \ 'g:notmuch_show_marker_regexp':            '\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
50         \
51         \ 'g:notmuch_show_message_parse_regexp':     '\(id:[^ ]*\) depth:\([0-9]*\) match:\([0-9]*\) excluded:\([0-9]*\) filename:\(.*\)$',
52         \ 'g:notmuch_show_tags_regexp':              '(\([^)]*\))$'               ,
53         \
54         \ 'g:notmuch_show_signature_regexp':         '^\(-- \?\|_\+\)$'           ,
55         \ 'g:notmuch_show_signature_lines_max':      12                           ,
56         \
57         \ 'g:notmuch_show_citation_regexp':          '^\s*>'                      ,
58         \
59         \ 'g:notmuch_compose_insert_mode_start':     1                            ,
60         \ 'g:notmuch_compose_header_help':           1                            ,
61         \ 'g:notmuch_compose_temp_file_dir':         '~/.notmuch/compose'         ,
62         \ }
63
64 " defaults for g:notmuch_initial_search_words
65 " override with: let g:notmuch_initial_search_words = [ ... ]
66 let s:notmuch_initial_search_words_defaults = [
67         \ 'tag:inbox and tag:unread',
68         \ ]
69
70 " defaults for g:notmuch_show_headers
71 " override with: let g:notmuch_show_headers = [ ... ]
72 let s:notmuch_show_headers_defaults = [
73         \ 'Subject',
74         \ 'To',
75         \ 'Cc',
76         \ 'Bcc',
77         \ 'Date',
78         \ ]
79
80 " defaults for g:notmuch_folders
81 " override with: let g:notmuch_folders = [ ... ]
82 let s:notmuch_folders_defaults = [
83         \ [ 'new',    'tag:inbox and tag:unread' ],
84         \ [ 'inbox',  'tag:inbox'                ],
85         \ [ 'unread', 'tag:unread'               ],
86         \ ]
87
88 " defaults for g:notmuch_signature
89 " override with: let g:notmuch_signature = [ ... ]
90 let s:notmuch_signature_defaults = [
91         \ '',
92         \ '-- ',
93         \ 'email sent from notmuch.vim plugin'
94         \ ]
95
96 " defaults for g:notmuch_compose_headers
97 " override with: let g:notmuch_compose_headers = [ ... ]
98 let s:notmuch_compose_headers_defaults = [
99         \ 'From',
100         \ 'To',
101         \ 'Cc',
102         \ 'Bcc',
103         \ 'Subject'
104         \ ]
105
106 " --- keyboard mapping definitions {{{1
107
108 " --- --- bindings for folders mode {{{2
109
110 let g:notmuch_folders_maps = {
111         \ 'm':          ':call <SID>NM_new_mail()<CR>',
112         \ 's':          ':call <SID>NM_search_prompt()<CR>',
113         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
114         \ '=':          ':call <SID>NM_folders_refresh_view()<CR>',
115         \ '<Enter>':    ':call <SID>NM_folders_show_search()<CR>',
116         \ }
117
118 " --- --- bindings for search screen {{{2
119 let g:notmuch_search_maps = {
120         \ '<Space>':    ':call <SID>NM_search_show_thread(0)<CR>',
121         \ '<Enter>':    ':call <SID>NM_search_show_thread(1)<CR>',
122         \ '<C-]>':      ':call <SID>NM_search_expand(''<cword>'')<CR>',
123         \ 'I':          ':call <SID>NM_search_mark_read_thread()<CR>',
124         \ 'a':          ':call <SID>NM_search_archive_thread()<CR>',
125         \ 'A':          ':call <SID>NM_search_mark_read_then_archive_thread()<CR>',
126         \ 'D':          ':call <SID>NM_search_delete_thread()<CR>',
127         \ 'f':          ':call <SID>NM_search_filter()<CR>',
128         \ 'm':          ':call <SID>NM_new_mail()<CR>',
129         \ 'o':          ':call <SID>NM_search_toggle_order()<CR>',
130         \ 'r':          ':call <SID>NM_search_reply_to_thread()<CR>',
131         \ 's':          ':call <SID>NM_search_prompt()<CR>',
132         \ ',s':         ':call <SID>NM_search_edit()<CR>',
133         \ 't':          ':call <SID>NM_search_filter_by_tag()<CR>',
134         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
135         \ '+':          ':call <SID>NM_search_add_tags([])<CR>',
136         \ '-':          ':call <SID>NM_search_remove_tags([])<CR>',
137         \ '=':          ':call <SID>NM_search_refresh_view()<CR>',
138         \ '?':          ':echo <SID>NM_search_thread_id() . ''  @ '' . join(<SID>NM_get_search_words())<CR>',
139         \ }
140
141 " --- --- bindings for show screen {{{2
142 let g:notmuch_show_maps = {
143         \ '<C-P>':      ':call <SID>NM_show_previous(1, 0)<CR>',
144         \ '<C-N>':      ':call <SID>NM_show_next(1, 0)<CR>',
145         \ '<C-]>':      ':call <SID>NM_search_expand(''<cword>'')<CR>',
146         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
147         \ 's':          ':call <SID>NM_search_prompt()<CR>',
148         \
149         \ 'b':          ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
150         \ 'c':          ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
151         \ 'h':          ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
152         \ 'i':          ':call <SID>NM_show_fold_toggle(''i'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
153         \
154         \ 'I':          ':call <SID>NM_show_mark_read_thread()<CR>',
155         \ 'a':          ':call <SID>NM_show_archive_thread()<CR>',
156         \ 'A':          ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
157         \ 'D':          ':call <SID>NM_show_delete_thread()<CR>',
158         \ 'd':          ':call <SID>NM_show_delete_message()<CR>',
159         \ 'N':          ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
160         \ 'v':          ':call <SID>NM_show_view_all_mime_parts()<CR>',
161         \ '+':          ':call <SID>NM_show_add_tag()<CR>',
162         \ '-':          ':call <SID>NM_show_remove_tag()<CR>',
163         \ '<Space>':    ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
164         \ '\|':         ':call <SID>NM_show_pipe_message()<CR>',
165         \
166         \ '<S-Tab>':    ':call <SID>NM_show_previous_fold()<CR>',
167         \ '<Tab>':      ':call <SID>NM_show_next_fold()<CR>',
168         \ '<Enter>':    ':call <SID>NM_show_toggle_fold()<CR>',
169         \
170         \ 'r':          ':call <SID>NM_show_reply()<CR>',
171         \ 'm':          ':call <SID>NM_new_mail()<CR>',
172         \ '?':          ':echo <SID>NM_show_message_id() . ''  @ '' . join(<SID>NM_get_search_words())<CR>',
173         \ }
174
175 " --- --- bindings for compose screen {{{2
176 let g:notmuch_compose_nmaps = {
177         \ ',s':         ':call <SID>NM_compose_send()<CR>',
178         \ ',a':         ':call <SID>NM_compose_attach()<CR>',
179         \ ',q':         ':call <SID>NM_kill_this_buffer()<CR>',
180         \ '<Tab>':      ':call <SID>NM_compose_next_entry_area()<CR>',
181         \ }
182 let g:notmuch_compose_imaps = {
183         \ '<Tab>':      '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
184         \ }
185
186 " --- implement folders screen {{{1
187
188 function! s:NM_cmd_folders(words)
189         if len(a:words)
190                 throw 'Not expecting any arguments for folders command.'
191         endif
192         let cmd = ['count']
193         let disp = []
194         let searches = []
195         for entry in g:notmuch_folders
196                 let [ name, search ] = entry
197                 let data = s:NM_run(cmd + [search])
198                 let cnt = matchlist(data, '\(\d\+\)')[1]
199                 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
200                 call add(searches, search)
201         endfor
202
203         call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
204         let b:nm_searches = searches
205         let b:nm_timestamp = reltime()
206
207         call <SID>NM_cmd_folders_mksyntax()
208         call <SID>NM_set_map('n', g:notmuch_folders_maps)
209         setlocal cursorline
210         setlocal nowrap
211 endfunction
212
213 function! s:NM_cmd_folders_mksyntax()
214 endfunction
215
216 " --- --- folders screen action functions {{{2
217
218 function! s:NM_folders_refresh_view()
219         let lno = line('.')
220         setlocal bufhidden=delete
221         call s:NM_cmd_folders([])
222         exec printf('norm %dG', lno)
223 endfunction
224
225 function! s:NM_folders_show_search()
226         let line = line('.')
227         let search = b:nm_searches[line-1]
228
229         let prev_bufnr = bufnr('%')
230         setlocal bufhidden=hide
231         call <SID>NM_cmd_search([search])
232         setlocal bufhidden=delete
233         let b:nm_prev_bufnr = prev_bufnr
234 endfunction
235
236
237 " --- implement search screen {{{1
238
239 function! s:NM_cmd_search(words)
240         let cmd = ['search']
241         if g:notmuch_search_newest_first
242                 let cmd = cmd + ['--sort=newest-first']
243         else
244                 let cmd = cmd + ['--sort=oldest-first']
245         endif
246         let data = s:NM_run(cmd + a:words)
247         let lines = split(data, "\n")
248         let disp = copy(lines)
249         call map(disp, 's:NM_cmd_search_fmtline(v:val)')
250
251         call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
252         let b:nm_raw_lines = lines
253         let b:nm_search_words = a:words
254
255         call <SID>NM_set_map('n', g:notmuch_search_maps)
256         setlocal cursorline
257         setlocal nowrap
258 endfunction
259 function! s:NM_cmd_search_fmtline(line)
260         let m = matchlist(a:line, '^\(thread:\S\+\)\s\(.\{12\}\) \[\(\d\+\)/\d\+\] \([^;]\+\); \%(\[[^\[]\+\] \)*\(.*\) (\([^(]*\))$')
261         if !len(m)
262                 return 'ERROR PARSING: ' . a:line
263         endif
264         let max = g:notmuch_search_from_column_width
265         let flist = {}
266         for at in split(m[4], '[|,] ')
267                 let p = split(at, '[@.]')
268                 let flist[p[0]] = 1
269         endfor
270         let from = join(keys(flist), ", ")
271         return printf("%-12s %3s %-20.20s | %s (%s)", m[2], m[3], from, m[5], m[6])
272 endfunction
273
274 " --- --- search screen action functions {{{2
275
276 function! s:NM_search_show_thread(everything)
277         let words = [ <SID>NM_search_thread_id() ]
278         if !a:everything && exists('b:nm_search_words')
279                 call extend(words, ['AND', '('])
280                 call extend(words, b:nm_search_words)
281                 call add(words, ')')
282         endif
283         call <SID>NM_cmd_show(words)
284         let b:nm_show_everything = a:everything
285 endfunction
286
287 function! s:NM_search_prompt()
288         " TODO: input() can support completion
289         let text = input('NotMuch Search: ')
290         if strlen(text)
291                 let tags = split(text)
292         else
293                 let tags = s:notmuch_initial_search_words_defaults
294         endif
295         let prev_bufnr = bufnr('%')
296         if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
297                 " TODO: we intend to replace the current buffer,
298                 "       ... maybe we could just clear it
299                 let prev_bufnr = b:nm_prev_bufnr
300                 setlocal bufhidden=delete
301         else
302                 setlocal bufhidden=hide
303         endif
304         call <SID>NM_cmd_search(tags)
305         setlocal bufhidden=delete
306         let b:nm_prev_bufnr = prev_bufnr
307 endfunction
308
309 function! s:NM_search_edit()
310         " TODO: input() can support completion
311         let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
312         if strlen(text)
313                 call <SID>NM_cmd_search(split(text))
314         endif
315 endfunction
316
317 function! s:NM_search_mark_read_thread()
318         call <SID>NM_tag([], ['-unread'])
319         norm j
320 endfunction
321
322 function! s:NM_search_archive_thread()
323         call <SID>NM_tag([], ['-inbox'])
324         norm j
325 endfunction
326
327 function! s:NM_search_mark_read_then_archive_thread()
328         call <SID>NM_tag([], ['-unread', '-inbox'])
329         norm j
330 endfunction
331
332 function! s:NM_search_delete_thread()
333         call <SID>NM_tag([], ['+delete','-inbox','-unread'])
334         norm j
335 endfunction
336
337 function! s:NM_search_filter()
338         call <SID>NM_search_filter_helper('Filter: ', '', '')
339 endfunction
340
341 function! s:NM_search_filter_by_tag()
342         call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
343 endfunction
344
345 function! s:NM_search_filter_helper(prompt, prefix, joiner)
346         " TODO: input() can support completion
347         let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
348         if !strlen(text)
349                 return
350         endif
351
352         let tags = b:nm_search_words + ['AND']
353                  \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
354
355         let prev_bufnr = bufnr('%')
356         setlocal bufhidden=hide
357         call <SID>NM_cmd_search(tags)
358         setlocal bufhidden=delete
359         let b:nm_prev_bufnr = prev_bufnr
360 endfunction
361
362 function! s:NM_search_toggle_order()
363         let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
364         " FIXME: maybe this would be better done w/o reading re-reading the lines
365         "         reversing the b:nm_raw_lines and the buffer lines would be better
366         call <SID>NM_search_refresh_view()
367 endfunction
368
369 function! s:NM_search_reply_to_thread()
370         let cmd = ['reply']
371         call add(cmd, <SID>NM_search_thread_id())
372         call add(cmd, 'AND')
373         call extend(cmd, <SID>NM_get_search_words())
374
375         let data = <SID>NM_run(cmd)
376         let lines = split(data, "\n")
377         call <SID>NM_newComposeBuffer(lines, 0)
378 endfunction
379
380 function! s:NM_search_add_tags(tags)
381         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
382 endfunction
383
384 function! s:NM_search_remove_tags(tags)
385         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
386 endfunction
387
388 function! s:NM_search_refresh_view()
389         let lno = line('.')
390         let prev_bufnr = b:nm_prev_bufnr
391         setlocal bufhidden=delete
392         call <SID>NM_cmd_search(b:nm_search_words)
393         let b:nm_prev_bufnr = prev_bufnr
394         " FIXME: should find the line of the thread we were on if possible
395         exec printf('norm %dG', lno)
396 endfunction
397
398 " --- --- search screen helper functions {{{2
399
400 function! s:NM_search_thread_id()
401         if !exists('b:nm_raw_lines')
402                 throw 'Eeek! no b:nm_raw_lines'
403         endif
404         let mnum = line('.') - 1
405         if len(b:nm_raw_lines) <= mnum
406                 return ''
407         endif
408         let info = b:nm_raw_lines[mnum]
409         let what = split(info, '\s\+')[0]
410         return what
411 endfunction
412
413 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
414         if type(a:intags) != type([]) || len(a:intags) == 0
415                 " TODO: input() can support completion
416                 let text = input(a:prompt)
417                 if !strlen(text)
418                         return
419                 endif
420                 let tags = split(text, ' ')
421         else
422                 let tags = a:intags
423         endif
424         call map(tags, 'a:prefix . v:val')
425         call <SID>NM_tag([], tags)
426 endfunction
427
428 " --- implement show screen {{{1
429
430 function! s:NM_cmd_show(words)
431         let prev_bufnr = bufnr('%')
432         let data = s:NM_run(['show', '--entire-thread'] + a:words)
433         let lines = split(data, "\n")
434
435         let info = s:NM_cmd_show_parse(lines)
436
437         setlocal bufhidden=hide
438         call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
439         setlocal bufhidden=delete
440         let b:nm_search_words = a:words
441         let b:nm_raw_info = info
442         let b:nm_prev_bufnr = prev_bufnr
443
444         call <SID>NM_cmd_show_mkfolds()
445         call <SID>NM_cmd_show_mksyntax()
446         call <SID>NM_set_map('n', g:notmuch_show_maps)
447         setlocal foldtext=NM_cmd_show_foldtext()
448         setlocal fillchars=
449         setlocal foldcolumn=6
450
451 endfunction
452
453 function! s:NM_show_previous(can_change_thread, find_matching)
454         let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
455         let info = b:nm_raw_info
456         let lnum = line('.')
457         for msg in reverse(copy(info['msgs']))
458                 if a:find_matching && msg['match'] == '0'
459                         continue
460                 endif
461                 if lnum <= msg['start']
462                         continue
463                 endif
464
465                 exec printf('norm %dGzt', msg['start'])
466                 " TODO: try to fit the message on screen
467                 return
468         endfor
469         if !a:can_change_thread
470                 return
471         endif
472         call <SID>NM_kill_this_buffer()
473         if line('.') > 1
474                 norm k
475                 call <SID>NM_search_show_thread(everything)
476                 norm G
477                 call <SID>NM_show_previous(0, a:find_matching)
478         else
479                 echo 'No more messages.'
480         endif
481 endfunction
482
483 function! s:NM_show_next(can_change_thread, find_matching)
484         let info = b:nm_raw_info
485         let lnum = line('.')
486         for msg in info['msgs']
487                 if a:find_matching && msg['match'] == '0'
488                         continue
489                 endif
490                 if lnum >= msg['start']
491                         continue
492                 endif
493
494                 exec printf('norm %dGzt', msg['start'])
495                 " TODO: try to fit the message on screen
496                 return
497         endfor
498         if a:can_change_thread
499                 call <SID>NM_show_next_thread()
500         endif
501 endfunction
502
503 function! s:NM_show_next_thread()
504         let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
505         call <SID>NM_kill_this_buffer()
506         if line('.') != line('$')
507                 norm j
508                 call <SID>NM_search_show_thread(everything)
509         else
510                 echo 'No more messages.'
511         endif
512 endfunction
513
514 function! s:NM_show_mark_read_thread()
515         call <SID>NM_tag(b:nm_search_words, ['-unread'])
516         call <SID>NM_show_next_thread()
517 endfunction
518
519 function! s:NM_show_archive_thread()
520         call <SID>NM_tag(b:nm_search_words, ['-inbox'])
521         call <SID>NM_show_next_thread()
522 endfunction
523
524 function! s:NM_show_mark_read_then_archive_thread()
525         call <SID>NM_tag(b:nm_search_words, ['-unread', '-inbox'])
526         call <SID>NM_show_next_thread()
527 endfunction
528
529 function! s:NM_show_delete_thread()
530         call <SID>NM_tag(b:nm_search_words, ['+delete', '-inbox', '-unread'])
531         call <SID>NM_show_next_thread()
532 endfunction
533
534 function! s:NM_show_delete_message()
535         let msg = <SID>NM_show_get_message_for_line(line('.'))
536         call <SID>NM_tag([msg['id']], ['+delete', '-inbox', '-unread'])
537 endfunction
538
539 function! s:NM_show_mark_read_then_next_open_message()
540         echo 'not implemented'
541 endfunction
542
543 function! s:NM_show_previous_message()
544         echo 'not implemented'
545 endfunction
546
547 function! s:NM_show_reply()
548         let cmd = ['reply']
549         call add(cmd, <SID>NM_show_message_id())
550         call add(cmd, 'AND')
551         call extend(cmd, <SID>NM_get_search_words())
552
553         let data = <SID>NM_run(cmd)
554         let lines = split(data, "\n")
555         call <SID>NM_newComposeBuffer(lines, 0)
556 endfunction
557
558 function! s:NM_show_view_all_mime_parts()
559         echo 'not implemented'
560 endfunction
561
562 function! s:NM_show_view_raw_message()
563         echo 'not implemented'
564 endfunction
565
566 function! s:NM_show_add_tag()
567         echo 'not implemented'
568 endfunction
569
570 function! s:NM_show_remove_tag()
571         echo 'not implemented'
572 endfunction
573
574 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
575 " otherwise go to next message
576 " any message that is viewed entirely has inbox and unread tags removed
577 function! s:NM_show_advance_marking_read_and_archiving()
578         let advance_tags = ['unread', 'inbox']
579
580         let vis_top = line('w0')
581         let vis_bot = line('w$')
582
583         let msg_top = <SID>NM_show_get_message_for_line(vis_top)
584         if !has_key(msg_top,'id')
585                 throw "No top visible message."
586         endif
587
588         " if the top message is the last message, just expunge the entire thread and move on
589         if msg_top['end'] == line('$')
590                 let ids = []
591                 for msg in b:nm_raw_info['msgs']
592                         if has_key(msg,'match') && msg['match'] != '0'
593                                 call add(ids, msg['id'])
594                         endif
595                 endfor
596                 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
597                          \ + ['AND']
598                          \ + <SID>NM_combine_tags('', ids, 'OR', '()')
599                 call map(advance_tags, '"-" . v:val')
600                 call <SID>NM_tag(filter, advance_tags)
601                 call <SID>NM_show_next(1, 1)
602                 return
603         endif
604
605         let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
606         if !has_key(msg_bot,'id')
607                 throw "No bottom visible message."
608         endif
609
610         " if entire message fits on the screen, read/archive it, move to the next one
611         if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
612                 exec printf('norm %dG', vis_top)
613                 call <SID>NM_show_next(0, 1)
614                 if has_key(msg_top,'match') && msg_top['match'] != '0'
615                         redraw
616                         " do this last to hide the latency
617                         let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
618                                  \ + ['AND', msg_top['id']]
619                         call map(advance_tags, '"-" . v:val')
620                         call <SID>NM_tag(filter, advance_tags)
621                 endif
622                 return
623         endif
624
625         " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
626         let jmp = winheight(winnr()) / 2
627         let max = msg_bot['end'] - vis_bot
628         if jmp > max
629                 let jmp = max
630         endif
631         exec printf('norm %dGzt', vis_top + jmp)
632         return
633 endfunction
634
635 function! s:NM_show_pipe_message()
636         echo 'not implemented'
637 endfunction
638
639 function! s:NM_show_previous_fold()
640         echo 'not implemented'
641 endfunction
642
643 function! s:NM_show_next_fold()
644         echo 'not implemented'
645 endfunction
646
647 function! s:NM_show_toggle_fold()
648         echo 'not implemented'
649 endfunction
650
651
652 " --- --- show screen helper functions {{{2
653
654 function! s:NM_show_get_message_for_line(line)
655         for msg in b:nm_raw_info['msgs']
656                 if a:line > msg['end']
657                         continue
658                 endif
659                 return msg
660         endfor
661         return {}
662 endfunction
663
664 function! s:NM_show_message_id()
665         if !exists('b:nm_raw_info')
666                 throw 'Eeek! no b:nm_raw_info'
667         endif
668         let msg = <SID>NM_show_get_message_for_line(line('.'))
669         if has_key(msg,'id')
670                 return msg['id']
671         endif
672         return ''
673 endfunction
674
675 function! s:NM_show_fold_toggle(key, type, fold)
676         let info = b:nm_raw_info
677         let act = 'open'
678         if a:fold
679                 let act = 'close'
680         endif
681         for fld in info['folds']
682                 if fld[0] != a:type
683                         continue
684                 endif
685                 "let idx = fld[3]
686                 "let msg = info['msgs'][idx]
687                 "if has_key(msg,'match') && msg['match'] == '0'
688                 "        continue
689                 "endif
690                 let cls = foldclosed(fld[1])
691                 if cls != -1 && cls != fld[1]
692                         continue
693                 endif
694                 exec printf('%dfold%s', fld[1], act)
695         endfor
696         exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
697 endfunction
698
699
700 " s:NM_cmd_show_parse returns the following dictionary:
701 "    'disp':     lines to display
702 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
703 "    'folds':    fold info arrays [ type, start, end ]
704 "    'foldtext': fold text indexed by start line
705 function! s:NM_cmd_show_parse(inlines)
706         let info = { 'disp': [],       
707                    \ 'msgs': [],       
708                    \ 'folds': [],      
709                    \ 'foldtext': {} }  
710         let msg = {}
711         let hdr = {}
712
713         let in_message = 0
714         let in_header = 0
715         let in_body = 0
716         let in_part = ''
717
718         let body_start = -1
719         let part_start = -1
720
721         let mode_type = ''
722         let mode_start = -1
723
724         let inlnum = 0
725         for line in a:inlines
726                 let inlnum = inlnum + 1
727                 let foldinfo = []
728
729                 if strlen(in_part)
730                         let part_end = 0
731
732                         if match(line, g:notmuch_show_part_end_regexp) != -1
733                                 let part_end = len(info['disp'])
734                         else
735                                 call add(info['disp'], line)
736                         endif
737
738                         if in_part == 'text/plain'
739                                 if !part_end && mode_type == ''
740                                         if match(line, g:notmuch_show_signature_regexp) != -1
741                                                 let mode_type = 'sig'
742                                                 let mode_start = len(info['disp'])
743                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
744                                                 let mode_type = 'cit'
745                                                 let mode_start = len(info['disp'])
746                                         endif
747                                 elseif mode_type == 'cit'
748                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
749                                                 let outlnum = len(info['disp'])
750                                                 if !part_end
751                                                         let outlnum = outlnum - 1
752                                                 endif
753                                                 let foldinfo = [ mode_type, mode_start, outlnum, len(info['msgs']),
754                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', 1 + outlnum - mode_start) ]
755                                                 let mode_type = ''
756                                         endif
757                                 elseif mode_type == 'sig'
758                                         let outlnum = len(info['disp'])
759                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
760                                                 let mode_type = ''
761                                         elseif part_end
762                                                 let foldinfo = [ mode_type, mode_start, outlnum, len(info['msgs']),
763                                                                \ printf('[ %d-line signature.  Press "i" to show. ]', 1 + outlnum - mode_start) ]
764                                                 let mode_type = ''
765                                         endif
766                                 endif
767                         endif
768
769                         if part_end
770                                 " FIXME: this is a hack for handling two folds being added for one line
771                                 "         we should handle adding a fold in a function
772                                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
773                                         call add(info['folds'], foldinfo[0:3])
774                                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
775                                 endif
776
777                                 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
778                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
779                                 let in_part = ''
780                                 call add(info['disp'], '')
781                         endif
782
783                 elseif in_body
784                         if !has_key(msg,'body_start')
785                                 let msg['body_start'] = len(info['disp']) + 1
786                         endif
787                         if match(line, g:notmuch_show_body_end_regexp) != -1
788                                 let body_end = len(info['disp'])
789                                 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
790                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
791
792                                 let in_body = 0
793
794                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
795                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
796                                 let in_part = 'unknown'
797                                 if len(m)
798                                         let in_part = m[2]
799                                 endif
800                                 call add(info['disp'],
801                                          \ printf('--- %s ---', in_part))
802                                 " We don't yet handle nested parts, so pop
803                                 " multipart/* immediately so text/plain
804                                 " sub-parts are parsed properly
805                                 if match(in_part, '^multipart/') != -1
806                                         let in_part = ''
807                                 else
808                                         let part_start = len(info['disp']) + 1
809                                 endif
810                         endif
811
812                 elseif in_header
813                         if in_header == 1
814                                 let msg['descr'] = line
815                                 call add(info['disp'], line)
816                                 let in_header = 2
817                                 let msg['hdr_start'] = len(info['disp']) + 1
818
819                         else
820                                 if match(line, g:notmuch_show_header_end_regexp) != -1
821                                         let hdr_start = msg['hdr_start']+1
822                                         let hdr_end = len(info['disp'])
823                                         let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
824                                                \ printf('[ %d-line headers.  Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
825                                         let msg['header'] = hdr
826                                         let in_header = 0
827                                         let hdr = {}
828                                 else
829                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
830                                         if len(m)
831                                                 let hdr[m[1]] = m[2]
832                                                 if match(g:notmuch_show_headers, m[1]) != -1
833                                                         call add(info['disp'], line)
834                                                 endif
835                                         endif
836                                 endif
837                         endif
838
839                 elseif in_message
840                         if match(line, g:notmuch_show_message_end_regexp) != -1
841                                 let msg['end'] = len(info['disp'])
842                                 call add(info['disp'], '')
843
844                                 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
845                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
846
847                                 call add(info['msgs'], msg)
848                                 let msg = {}
849                                 let in_message = 0
850                                 let in_header = 0
851                                 let in_body = 0
852                                 let in_part = ''
853
854                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
855                                 let in_header = 1
856                                 continue
857
858                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
859                                 let body_start = len(info['disp']) + 1
860                                 let in_body = 1
861                                 continue
862                         endif
863
864                 else
865                         if match(line, g:notmuch_show_message_begin_regexp) != -1
866                                 let msg['start'] = len(info['disp']) + 1
867
868                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
869                                 if len(m)
870                                         let msg['id'] = m[1]
871                                         let msg['depth'] = m[2]
872                                         let msg['match'] = m[3]
873                                         let msg['excluded'] = m[4]
874                                         let msg['filename'] = m[5]
875                                 endif
876
877                                 let in_message = 1
878                         endif
879                 endif
880
881                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
882                         call add(info['folds'], foldinfo[0:3])
883                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
884                 endif
885         endfor
886         return info
887 endfunction
888
889 function! s:NM_cmd_show_mkfolds()
890         let info = b:nm_raw_info
891
892         for afold in info['folds']
893                 exec printf('%d,%dfold', afold[1], afold[2])
894                 let state = 'open'
895                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
896                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
897                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
898                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
899                         let state = 'close'
900                 elseif afold[0] == 'msg'
901                         let idx = afold[3]
902                         let msg = info['msgs'][idx]
903                         if has_key(msg,'match') && msg['match'] == '0'
904                                 let state = 'close'
905                         endif
906                 endif
907                 exec printf('%dfold%s', afold[1], state)
908         endfor
909 endfunction
910
911 function! s:NM_cmd_show_mksyntax()
912         let info = b:nm_raw_info
913         let cnt = 0
914         for msg in info['msgs']
915                 let cnt = cnt + 1
916                 let start = msg['start']
917                 let hdr_start = msg['hdr_start']
918                 let body_start = msg['body_start']
919                 let end = msg['end']
920                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
921                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
922                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
923         endfor
924 endfunction
925
926 function! NM_cmd_show_foldtext()
927         let foldtext = b:nm_raw_info['foldtext']
928         return foldtext[v:foldstart]
929 endfunction
930
931
932 " --- implement compose screen {{{1
933
934 function! s:NM_cmd_compose(words, body_lines)
935         let lines = []
936         let start_on_line = 0
937
938         let hdrs = { }
939         for word in a:words
940                 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
941                 if !len(m)
942                         throw 'Eeek! bad parameter ''' . string(word) . ''''
943                 endif
944                 let key = substitute(m[1], '\<\w', '\U&', 'g')
945                 if !has_key(hdrs, key)
946                         let hdrs[key] = []
947                 endif
948                 if strlen(m[2])
949                         call add(hdrs[key], m[2])
950                 endif
951         endfor
952
953         if !has_key(hdrs, 'From') || !len(hdrs['From'])
954                 let me = <SID>NM_compose_get_user_email()
955                 let hdrs['From'] = [ me ]
956         endif
957
958         for key in g:notmuch_compose_headers
959                 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
960                 call add(lines, key . ': ' . text)
961                 if !start_on_line && !strlen(text)
962                         let start_on_line = len(lines)
963                 endif
964         endfor
965
966         for [key,val] in items(hdrs)
967                 if match(g:notmuch_compose_headers, key) == -1
968                         let line = key . ': ' . join(val, ', ')
969                         call add(lines, line)
970                 endif
971         endfor
972
973         call add(lines, '')
974         if !start_on_line
975                 let start_on_line = len(lines) + 1
976         endif
977
978         if len(a:body_lines)
979                 call extend(lines, a:body_lines)
980         else
981                 call extend(lines, [ '', '' ])
982         endif
983
984         call <SID>NM_newComposeBuffer(lines, start_on_line)
985 endfunction
986
987 function! s:NM_compose_send()
988         call <SID>NM_assert_buffer_type('compose')
989         let fname = expand('%')
990         let lnum = 1
991         let line = getline(lnum)
992         let lst_hdr = ''
993         while match(line, '^$') == -1
994                 if !exists("hdr_starts") && match(line, '^Notmuch-Help:') == -1
995                         let hdr_starts = lnum - 1
996                 endif
997                 let lnum = lnum + 1
998                 let line = getline(lnum)
999         endwhile
1000         let body_starts = lnum - 1
1001
1002         call append(body_starts, 'Date: ' . strftime('%a, %d %b %Y %H:%M:%S %z'))
1003         exec printf(':0,%dd', hdr_starts)
1004         write
1005
1006         let line = getline(1)
1007         let m = matchlist(line, '^From:\s*\(.*\)\s*<\(.*\)>$')
1008         if (len(m) >= 2)
1009                 let from = m[2]
1010         else
1011                 let m = matchlist(line, '^From:\s*\(.*\)$')
1012                 let from = m[1]
1013         endif
1014
1015         let cmdtxt = g:notmuch_sendmail . ' -t -f ' . from . ' < ' . fname
1016         let out = system(cmdtxt)
1017         let err = v:shell_error
1018         if err
1019                 undo
1020                 write
1021                 call <SID>NM_newBuffer('new', 'error',
1022                             \ "While running...\n" .
1023                             \ '  ' . cmdtxt . "\n" .
1024                             \ "\n" .
1025                             \ "Failed with...\n" .
1026                             \ substitute(out, '^', '  ', 'g'))
1027                 echohl Error
1028                 echo 'Eeek! unable to send mail'
1029                 echohl None
1030                 return
1031         endif
1032
1033         if !exists('b:nm_prev_bufnr')
1034                 bdelete
1035         else
1036                 let prev_bufnr = b:nm_prev_bufnr
1037                 bdelete
1038                 if prev_bufnr == bufnr('%')
1039                         exec printf("buffer %d", prev_bufnr)
1040                 endif
1041         endif
1042         call delete(fname)
1043         echo 'Mail sent successfully.'
1044 endfunction
1045
1046 function! s:NM_compose_attach()
1047         echo 'not implemented'
1048 endfunction
1049
1050 function! s:NM_compose_next_entry_area()
1051         let lnum = line('.')
1052         let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1053         if lnum < hdr_end
1054                 let lnum = lnum + 1
1055                 let line = getline(lnum)
1056                 if match(line, '^\([^:]\+\):\s*$') == -1
1057                         call cursor(lnum, strlen(line) + 1)
1058                         return ''
1059                 endif
1060                 while match(getline(lnum+1), '^\s') != -1
1061                         let lnum = lnum + 1
1062                 endwhile
1063                 call cursor(lnum, strlen(getline(lnum)) + 1)
1064                 return ''
1065
1066         elseif lnum == hdr_end
1067                 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1068                 return ''
1069         endif
1070         if mode() == 'i'
1071                 if !getbufvar(bufnr('.'), '&et')
1072                         return "\t"
1073                 endif
1074                 let space = ''
1075                 let shiftwidth = a:shiftwidth
1076                 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1077                 " we assume no one has shiftwidth set to more than 40 :)
1078                 return '                                        '[0:shiftwidth]
1079         endif
1080 endfunction
1081
1082 " --- --- compose screen helper functions {{{2
1083
1084 function! s:NM_compose_get_user_email()
1085         " TODO: do this properly (still), i.e., allow for multiple email accounts
1086         let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1087         return email
1088 endfunction
1089
1090 function! s:NM_compose_find_line_match(start, pattern, failure)
1091         let lnum = a:start
1092         let lend = line('$')
1093         while lnum < lend
1094                 if match(getline(lnum), a:pattern) != -1
1095                         return lnum
1096                 endif
1097                 let lnum = lnum + 1
1098         endwhile
1099         return a:failure
1100 endfunction
1101
1102
1103 " --- notmuch helper functions {{{1
1104
1105 function! s:NM_newBuffer(how, type, content)
1106         if strlen(a:how)
1107                 exec a:how
1108         else
1109                 enew
1110         endif
1111         setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1112         silent put=a:content
1113         keepjumps 0d
1114         setlocal nomodifiable
1115         execute printf('set filetype=notmuch-%s', a:type)
1116         execute printf('set syntax=notmuch-%s', a:type)
1117         let b:nm_type = a:type
1118 endfunction
1119
1120 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1121         let fdir = expand(a:fdir)
1122         if !isdirectory(fdir)
1123                 call mkdir(fdir, 'p')
1124         endif
1125         let file_name = <SID>NM_mktemp(fdir, a:fname)
1126         if writefile(a:lines, file_name)
1127                 throw 'Eeek! couldn''t write to temporary file ' . file_name
1128         endif
1129         exec printf('edit %s', file_name)
1130         setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1131         execute printf('set filetype=notmuch-%s', a:type)
1132         execute printf('set syntax=notmuch-%s', a:type)
1133         let b:nm_type = a:type
1134 endfunction
1135
1136 function! s:NM_newComposeBuffer(lines, start_on_line)
1137         let lines = a:lines
1138         let start_on_line = a:start_on_line
1139         let real_hdr_start = 1
1140         if g:notmuch_compose_header_help
1141                 let help_lines = [
1142                   \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1143                   \ 'Notmuch-Help:   ,a    - attach a file',
1144                   \ 'Notmuch-Help:   ,s    - send the message (Notmuch-Help lines will be removed)',
1145                   \ 'Notmuch-Help:   ,q    - abort the message',
1146                   \ 'Notmuch-Help:   <Tab> - skip through header lines',
1147                   \ ]
1148                 call extend(lines, help_lines, 0)
1149                 let real_hdr_start = len(help_lines)
1150                 if start_on_line > 0
1151                         let start_on_line = start_on_line + len(help_lines)
1152                 endif
1153         endif
1154         call extend(lines, g:notmuch_signature)
1155
1156
1157         let prev_bufnr = bufnr('%')
1158         setlocal bufhidden=hide
1159         call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1160                                   \ 'compose', lines)
1161         setlocal bufhidden=hide
1162         let b:nm_prev_bufnr = prev_bufnr
1163
1164         call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1165         call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1166
1167         if start_on_line > 0 && start_on_line <= len(lines)
1168                 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1169         else
1170                 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1171                 call <SID>NM_compose_next_entry_area()
1172         endif
1173
1174         if g:notmuch_compose_insert_mode_start
1175                 startinsert!
1176         endif
1177         echo 'Type your message, use <TAB> to jump to next header and then body.'
1178 endfunction
1179
1180 function! s:NM_assert_buffer_type(type)
1181         if !exists('b:nm_type') || b:nm_type != a:type
1182                 throw printf('Eeek! expected type %s, but got %s.', a:type,
1183                             \ exists(b:nm_type) ? b:nm_type : 'something else')
1184         endif
1185 endfunction
1186
1187 function! s:NM_mktemp(dir, name)
1188         let time_stamp = strftime('%Y%m%d-%H%M%S')
1189         let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1190         " TODO: check if it exists, try again
1191         return file_name
1192 endfunction
1193
1194 function! s:NM_shell_escape(word)
1195         " TODO: use shellescape()
1196         let word = substitute(a:word, '''', '\\''', 'g')
1197         return '''' . word . ''''
1198 endfunction
1199
1200 " this function was taken from git.vim, then fixed up
1201 " https://github.com/motemen/git-vim
1202 function! s:NM_shell_split(cmd)
1203         let l:split_cmd = []
1204         let cmd = a:cmd
1205         let iStart = 0
1206         while 1
1207                 let t = match(cmd, '\S', iStart)
1208                 if t < iStart
1209                         break
1210                 endif
1211                 let iStart = t
1212
1213                 let iSpace = match(cmd, '\v(\s|$)', iStart)
1214                 if iSpace < iStart
1215                         break
1216                 endif
1217
1218                 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1219                 if iQuote1 > iSpace || iQuote1 < iStart
1220                         let iEnd = iSpace - 1
1221                         let l:split_cmd += [ cmd[iStart : iEnd] ]
1222                 else
1223                         let q = cmd[iQuote1]
1224                         let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1225                         if iQuote2 < iQuote1
1226                                 throw 'No matching ' . q . ' quote'
1227                         endif
1228                         let iEnd = iQuote2
1229                         let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1230                 endif
1231
1232
1233                 let iStart = iEnd + 1
1234         endwhile
1235
1236         return l:split_cmd
1237 endfunction
1238
1239
1240 function! s:NM_run(args)
1241         let words = a:args
1242         call map(words, 's:NM_shell_escape(v:val)')
1243         let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1244
1245         if exists('g:notmuch_debug') && g:notmuch_debug
1246                 let start = reltime()
1247                 let out = system(cmd)
1248                 let err = v:shell_error
1249                 let delta = reltime(start)
1250
1251                 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1252         else
1253                 let out = system(cmd)
1254                 let err = v:shell_error
1255         endif
1256
1257         if err
1258                 echohl Error
1259                 echo substitute(out, '\n*$', '', '')
1260                 echohl None
1261                 return ''
1262         else
1263                 return out
1264         endif
1265 endfunction
1266
1267 " --- external mail handling helpers {{{1
1268
1269 function! s:NM_new_mail()
1270         call <SID>NM_cmd_compose([], [])
1271 endfunction
1272
1273 " --- tag manipulation helpers {{{1
1274
1275 " used to combine an array of words with prefixes and separators
1276 " example:
1277 "     NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1278 "  -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1279 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1280         let res = []
1281         for word in a:words
1282                 if len(res) && strlen(a:separator)
1283                         call add(res, a:separator)
1284                 endif
1285                 call add(res, a:word_prefix . word)
1286         endfor
1287         if len(res) > 1 && strlen(a:brackets)
1288                 if strlen(a:brackets) != 2
1289                         throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1290                 endif
1291                 call insert(res, a:brackets[0])
1292                 call add(res, a:brackets[1])
1293         endif
1294         return res
1295 endfunction
1296
1297 " --- other helpers {{{1
1298
1299 function! s:NM_get_search_words()
1300         if !exists('b:nm_search_words')
1301                 throw 'Eeek! no b:nm_search_words'
1302         endif
1303         return b:nm_search_words
1304 endfunction
1305
1306 function! s:NM_kill_this_buffer()
1307         if exists('b:nm_prev_bufnr')
1308                 let prev_bufnr = b:nm_prev_bufnr
1309                 bdelete!
1310                 exec printf("buffer %d", prev_bufnr)
1311         else
1312                 echo "This is the last buffer; use :q<CR> to quit."
1313         endif
1314 endfunction
1315
1316 function! s:NM_search_expand(arg)
1317         let word = expand(a:arg)
1318         let prev_bufnr = bufnr('%')
1319         setlocal bufhidden=hide
1320         call <SID>NM_cmd_search([word])
1321         setlocal bufhidden=delete
1322         let b:nm_prev_bufnr = prev_bufnr
1323 endfunction
1324
1325 function! s:NM_tag(filter, tags)
1326         let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1327         if !len(filter)
1328                 throw 'Eeek! I couldn''t find the thread id!'
1329         endif
1330         let args = ['tag']
1331         call extend(args, a:tags)
1332         call add(args, '--')
1333         call extend(args, filter)
1334         " TODO: handle errors
1335         call <SID>NM_run(args)
1336 endfunction
1337
1338 " --- process and set the defaults {{{1
1339
1340 function! NM_set_defaults(force)
1341         for [key, dflt] in items(s:notmuch_defaults)
1342                 let cmd = ''
1343                 if !a:force && exists(key) && type(dflt) == type(eval(key))
1344                         continue
1345                 elseif type(dflt) == type(0)
1346                         let cmd = printf('let %s = %d', key, dflt)
1347                 elseif type(dflt) == type('')
1348                         let cmd = printf('let %s = ''%s''', key, dflt)
1349                 " FIXME: not sure why this didn't work when dflt is an array
1350                 "elseif type(dflt) == type([])
1351                 "        let cmd = printf('let %s = %s', key, string(dflt))
1352                 else
1353                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1354                                                 \ a:force, key, string(dflt))
1355                         continue
1356                 endif
1357                 exec cmd
1358         endfor
1359 endfunction
1360 call NM_set_defaults(0)
1361
1362 " for some reason NM_set_defaults() didn't work for arrays...
1363 if !exists('g:notmuch_show_headers')
1364         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1365 endif
1366 if !exists('g:notmuch_initial_search_words')
1367         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1368 endif
1369 if !exists('g:notmuch_folders')
1370         let g:notmuch_folders = s:notmuch_folders_defaults
1371 endif
1372
1373 if !exists('g:notmuch_signature')
1374         let g:notmuch_signature = s:notmuch_signature_defaults
1375 endif
1376 if !exists('g:notmuch_compose_headers')
1377         let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1378 endif
1379
1380 " --- assign keymaps {{{1
1381
1382 function! s:NM_set_map(type, maps)
1383         nmapclear
1384         for [key, code] in items(a:maps)
1385                 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1386         endfor
1387         " --- this is a hack for development :)
1388         nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1389 endfunction
1390
1391 " --- command handler {{{1
1392
1393 function! NotMuch(args)
1394         let args = a:args
1395         if !strlen(args)
1396                 let args = 'folders'
1397         endif
1398
1399         let words = <SID>NM_shell_split(args)
1400         if words[0] == 'folders' || words[0] == 'f'
1401                 let words = words[1:]
1402                 call <SID>NM_cmd_folders(words)
1403
1404         elseif words[0] == 'search' || words[0] == 's'
1405                 if len(words) > 1
1406                         let words = words[1:]
1407                 elseif exists('b:nm_search_words')
1408                         let words = b:nm_search_words
1409                 else
1410                         let words = g:notmuch_initial_search_words
1411                 endif
1412                 call <SID>NM_cmd_search(words)
1413
1414         elseif words[0] == 'show'
1415                 echoe 'show is not yet implemented.'
1416
1417         elseif words[0] == 'new' || words[0] == 'compose'
1418                 let words = words[1:]
1419                 call <SID>NM_cmd_compose(words, [])
1420         endif
1421 endfunction
1422 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1423         return []
1424 endfunction
1425
1426
1427 " --- glue {{{1
1428
1429 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1430 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1431
1432 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :