]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
vim: fix citation/signature fold lengths
[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 " 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]*\) 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['filename'] = m[4]
874                                 endif
875
876                                 let in_message = 1
877                         endif
878                 endif
879
880                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
881                         call add(info['folds'], foldinfo[0:3])
882                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
883                 endif
884         endfor
885         return info
886 endfunction
887
888 function! s:NM_cmd_show_mkfolds()
889         let info = b:nm_raw_info
890
891         for afold in info['folds']
892                 exec printf('%d,%dfold', afold[1], afold[2])
893                 let state = 'open'
894                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
895                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
896                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
897                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
898                         let state = 'close'
899                 elseif afold[0] == 'msg'
900                         let idx = afold[3]
901                         let msg = info['msgs'][idx]
902                         if has_key(msg,'match') && msg['match'] == '0'
903                                 let state = 'close'
904                         endif
905                 endif
906                 exec printf('%dfold%s', afold[1], state)
907         endfor
908 endfunction
909
910 function! s:NM_cmd_show_mksyntax()
911         let info = b:nm_raw_info
912         let cnt = 0
913         for msg in info['msgs']
914                 let cnt = cnt + 1
915                 let start = msg['start']
916                 let hdr_start = msg['hdr_start']
917                 let body_start = msg['body_start']
918                 let end = msg['end']
919                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
920                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
921                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
922         endfor
923 endfunction
924
925 function! NM_cmd_show_foldtext()
926         let foldtext = b:nm_raw_info['foldtext']
927         return foldtext[v:foldstart]
928 endfunction
929
930
931 " --- implement compose screen {{{1
932
933 function! s:NM_cmd_compose(words, body_lines)
934         let lines = []
935         let start_on_line = 0
936
937         let hdrs = { }
938         for word in a:words
939                 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
940                 if !len(m)
941                         throw 'Eeek! bad parameter ''' . string(word) . ''''
942                 endif
943                 let key = substitute(m[1], '\<\w', '\U&', 'g')
944                 if !has_key(hdrs, key)
945                         let hdrs[key] = []
946                 endif
947                 if strlen(m[2])
948                         call add(hdrs[key], m[2])
949                 endif
950         endfor
951
952         if !has_key(hdrs, 'From') || !len(hdrs['From'])
953                 let me = <SID>NM_compose_get_user_email()
954                 let hdrs['From'] = [ me ]
955         endif
956
957         for key in g:notmuch_compose_headers
958                 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
959                 call add(lines, key . ': ' . text)
960                 if !start_on_line && !strlen(text)
961                         let start_on_line = len(lines)
962                 endif
963         endfor
964
965         for [key,val] in items(hdrs)
966                 if match(g:notmuch_compose_headers, key) == -1
967                         let line = key . ': ' . join(val, ', ')
968                         call add(lines, line)
969                 endif
970         endfor
971
972         call add(lines, '')
973         if !start_on_line
974                 let start_on_line = len(lines) + 1
975         endif
976
977         if len(a:body_lines)
978                 call extend(lines, a:body_lines)
979         else
980                 call extend(lines, [ '', '' ])
981         endif
982
983         call <SID>NM_newComposeBuffer(lines, start_on_line)
984 endfunction
985
986 function! s:NM_compose_send()
987         call <SID>NM_assert_buffer_type('compose')
988         let fname = expand('%')
989         let lnum = 1
990         let line = getline(lnum)
991         let lst_hdr = ''
992         while match(line, '^$') == -1
993                 if !exists("hdr_starts") && match(line, '^Notmuch-Help:') == -1
994                         let hdr_starts = lnum - 1
995                 endif
996                 let lnum = lnum + 1
997                 let line = getline(lnum)
998         endwhile
999         let body_starts = lnum - 1
1000
1001         call append(body_starts, 'Date: ' . strftime('%a, %d %b %Y %H:%M:%S %z'))
1002         exec printf(':0,%dd', hdr_starts)
1003         write
1004
1005         let line = getline(1)
1006         let m = matchlist(line, '^From:\s*\(.*\)\s*<\(.*\)>$')
1007         if (len(m) >= 2)
1008                 let from = m[2]
1009         else
1010                 let m = matchlist(line, '^From:\s*\(.*\)$')
1011                 let from = m[1]
1012         endif
1013
1014         let cmdtxt = g:notmuch_sendmail . ' -t -f ' . from . ' < ' . fname
1015         let out = system(cmdtxt)
1016         let err = v:shell_error
1017         if err
1018                 undo
1019                 write
1020                 call <SID>NM_newBuffer('new', 'error',
1021                             \ "While running...\n" .
1022                             \ '  ' . cmdtxt . "\n" .
1023                             \ "\n" .
1024                             \ "Failed with...\n" .
1025                             \ substitute(out, '^', '  ', 'g'))
1026                 echohl Error
1027                 echo 'Eeek! unable to send mail'
1028                 echohl None
1029                 return
1030         endif
1031
1032         if !exists('b:nm_prev_bufnr')
1033                 bdelete
1034         else
1035                 let prev_bufnr = b:nm_prev_bufnr
1036                 bdelete
1037                 if prev_bufnr == bufnr('%')
1038                         exec printf("buffer %d", prev_bufnr)
1039                 endif
1040         endif
1041         call delete(fname)
1042         echo 'Mail sent successfully.'
1043 endfunction
1044
1045 function! s:NM_compose_attach()
1046         echo 'not implemented'
1047 endfunction
1048
1049 function! s:NM_compose_next_entry_area()
1050         let lnum = line('.')
1051         let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1052         if lnum < hdr_end
1053                 let lnum = lnum + 1
1054                 let line = getline(lnum)
1055                 if match(line, '^\([^:]\+\):\s*$') == -1
1056                         call cursor(lnum, strlen(line) + 1)
1057                         return ''
1058                 endif
1059                 while match(getline(lnum+1), '^\s') != -1
1060                         let lnum = lnum + 1
1061                 endwhile
1062                 call cursor(lnum, strlen(getline(lnum)) + 1)
1063                 return ''
1064
1065         elseif lnum == hdr_end
1066                 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1067                 return ''
1068         endif
1069         if mode() == 'i'
1070                 if !getbufvar(bufnr('.'), '&et')
1071                         return "\t"
1072                 endif
1073                 let space = ''
1074                 let shiftwidth = a:shiftwidth
1075                 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1076                 " we assume no one has shiftwidth set to more than 40 :)
1077                 return '                                        '[0:shiftwidth]
1078         endif
1079 endfunction
1080
1081 " --- --- compose screen helper functions {{{2
1082
1083 function! s:NM_compose_get_user_email()
1084         " TODO: do this properly (still), i.e., allow for multiple email accounts
1085         let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1086         return email
1087 endfunction
1088
1089 function! s:NM_compose_find_line_match(start, pattern, failure)
1090         let lnum = a:start
1091         let lend = line('$')
1092         while lnum < lend
1093                 if match(getline(lnum), a:pattern) != -1
1094                         return lnum
1095                 endif
1096                 let lnum = lnum + 1
1097         endwhile
1098         return a:failure
1099 endfunction
1100
1101
1102 " --- notmuch helper functions {{{1
1103
1104 function! s:NM_newBuffer(how, type, content)
1105         if strlen(a:how)
1106                 exec a:how
1107         else
1108                 enew
1109         endif
1110         setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1111         silent put=a:content
1112         keepjumps 0d
1113         setlocal nomodifiable
1114         execute printf('set filetype=notmuch-%s', a:type)
1115         execute printf('set syntax=notmuch-%s', a:type)
1116         let b:nm_type = a:type
1117 endfunction
1118
1119 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1120         let fdir = expand(a:fdir)
1121         if !isdirectory(fdir)
1122                 call mkdir(fdir, 'p')
1123         endif
1124         let file_name = <SID>NM_mktemp(fdir, a:fname)
1125         if writefile(a:lines, file_name)
1126                 throw 'Eeek! couldn''t write to temporary file ' . file_name
1127         endif
1128         exec printf('edit %s', file_name)
1129         setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1130         execute printf('set filetype=notmuch-%s', a:type)
1131         execute printf('set syntax=notmuch-%s', a:type)
1132         let b:nm_type = a:type
1133 endfunction
1134
1135 function! s:NM_newComposeBuffer(lines, start_on_line)
1136         let lines = a:lines
1137         let start_on_line = a:start_on_line
1138         let real_hdr_start = 1
1139         if g:notmuch_compose_header_help
1140                 let help_lines = [
1141                   \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1142                   \ 'Notmuch-Help:   ,a    - attach a file',
1143                   \ 'Notmuch-Help:   ,s    - send the message (Notmuch-Help lines will be removed)',
1144                   \ 'Notmuch-Help:   ,q    - abort the message',
1145                   \ 'Notmuch-Help:   <Tab> - skip through header lines',
1146                   \ ]
1147                 call extend(lines, help_lines, 0)
1148                 let real_hdr_start = len(help_lines)
1149                 if start_on_line > 0
1150                         let start_on_line = start_on_line + len(help_lines)
1151                 endif
1152         endif
1153         call extend(lines, g:notmuch_signature)
1154
1155
1156         let prev_bufnr = bufnr('%')
1157         setlocal bufhidden=hide
1158         call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1159                                   \ 'compose', lines)
1160         setlocal bufhidden=hide
1161         let b:nm_prev_bufnr = prev_bufnr
1162
1163         call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1164         call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1165
1166         if start_on_line > 0 && start_on_line <= len(lines)
1167                 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1168         else
1169                 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1170                 call <SID>NM_compose_next_entry_area()
1171         endif
1172
1173         if g:notmuch_compose_insert_mode_start
1174                 startinsert!
1175         endif
1176         echo 'Type your message, use <TAB> to jump to next header and then body.'
1177 endfunction
1178
1179 function! s:NM_assert_buffer_type(type)
1180         if !exists('b:nm_type') || b:nm_type != a:type
1181                 throw printf('Eeek! expected type %s, but got %s.', a:type,
1182                             \ exists(b:nm_type) ? b:nm_type : 'something else')
1183         endif
1184 endfunction
1185
1186 function! s:NM_mktemp(dir, name)
1187         let time_stamp = strftime('%Y%m%d-%H%M%S')
1188         let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1189         " TODO: check if it exists, try again
1190         return file_name
1191 endfunction
1192
1193 function! s:NM_shell_escape(word)
1194         " TODO: use shellescape()
1195         let word = substitute(a:word, '''', '\\''', 'g')
1196         return '''' . word . ''''
1197 endfunction
1198
1199 " this function was taken from git.vim, then fixed up
1200 " http://github.com/motemen/git-vim
1201 function! s:NM_shell_split(cmd)
1202         let l:split_cmd = []
1203         let cmd = a:cmd
1204         let iStart = 0
1205         while 1
1206                 let t = match(cmd, '\S', iStart)
1207                 if t < iStart
1208                         break
1209                 endif
1210                 let iStart = t
1211
1212                 let iSpace = match(cmd, '\v(\s|$)', iStart)
1213                 if iSpace < iStart
1214                         break
1215                 endif
1216
1217                 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1218                 if iQuote1 > iSpace || iQuote1 < iStart
1219                         let iEnd = iSpace - 1
1220                         let l:split_cmd += [ cmd[iStart : iEnd] ]
1221                 else
1222                         let q = cmd[iQuote1]
1223                         let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1224                         if iQuote2 < iQuote1
1225                                 throw 'No matching ' . q . ' quote'
1226                         endif
1227                         let iEnd = iQuote2
1228                         let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1229                 endif
1230
1231
1232                 let iStart = iEnd + 1
1233         endwhile
1234
1235         return l:split_cmd
1236 endfunction
1237
1238
1239 function! s:NM_run(args)
1240         let words = a:args
1241         call map(words, 's:NM_shell_escape(v:val)')
1242         let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1243
1244         if exists('g:notmuch_debug') && g:notmuch_debug
1245                 let start = reltime()
1246                 let out = system(cmd)
1247                 let err = v:shell_error
1248                 let delta = reltime(start)
1249
1250                 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1251         else
1252                 let out = system(cmd)
1253                 let err = v:shell_error
1254         endif
1255
1256         if err
1257                 echohl Error
1258                 echo substitute(out, '\n*$', '', '')
1259                 echohl None
1260                 return ''
1261         else
1262                 return out
1263         endif
1264 endfunction
1265
1266 " --- external mail handling helpers {{{1
1267
1268 function! s:NM_new_mail()
1269         call <SID>NM_cmd_compose([], [])
1270 endfunction
1271
1272 " --- tag manipulation helpers {{{1
1273
1274 " used to combine an array of words with prefixes and separators
1275 " example:
1276 "     NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1277 "  -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1278 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1279         let res = []
1280         for word in a:words
1281                 if len(res) && strlen(a:separator)
1282                         call add(res, a:separator)
1283                 endif
1284                 call add(res, a:word_prefix . word)
1285         endfor
1286         if len(res) > 1 && strlen(a:brackets)
1287                 if strlen(a:brackets) != 2
1288                         throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1289                 endif
1290                 call insert(res, a:brackets[0])
1291                 call add(res, a:brackets[1])
1292         endif
1293         return res
1294 endfunction
1295
1296 " --- other helpers {{{1
1297
1298 function! s:NM_get_search_words()
1299         if !exists('b:nm_search_words')
1300                 throw 'Eeek! no b:nm_search_words'
1301         endif
1302         return b:nm_search_words
1303 endfunction
1304
1305 function! s:NM_kill_this_buffer()
1306         if exists('b:nm_prev_bufnr')
1307                 let prev_bufnr = b:nm_prev_bufnr
1308                 bdelete!
1309                 exec printf("buffer %d", prev_bufnr)
1310         else
1311                 echo "This is the last buffer; use :q<CR> to quit."
1312         endif
1313 endfunction
1314
1315 function! s:NM_search_expand(arg)
1316         let word = expand(a:arg)
1317         let prev_bufnr = bufnr('%')
1318         setlocal bufhidden=hide
1319         call <SID>NM_cmd_search([word])
1320         setlocal bufhidden=delete
1321         let b:nm_prev_bufnr = prev_bufnr
1322 endfunction
1323
1324 function! s:NM_tag(filter, tags)
1325         let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1326         if !len(filter)
1327                 throw 'Eeek! I couldn''t find the thread id!'
1328         endif
1329         let args = ['tag']
1330         call extend(args, a:tags)
1331         call add(args, '--')
1332         call extend(args, filter)
1333         " TODO: handle errors
1334         call <SID>NM_run(args)
1335 endfunction
1336
1337 " --- process and set the defaults {{{1
1338
1339 function! NM_set_defaults(force)
1340         for [key, dflt] in items(s:notmuch_defaults)
1341                 let cmd = ''
1342                 if !a:force && exists(key) && type(dflt) == type(eval(key))
1343                         continue
1344                 elseif type(dflt) == type(0)
1345                         let cmd = printf('let %s = %d', key, dflt)
1346                 elseif type(dflt) == type('')
1347                         let cmd = printf('let %s = ''%s''', key, dflt)
1348                 " FIXME: not sure why this didn't work when dflt is an array
1349                 "elseif type(dflt) == type([])
1350                 "        let cmd = printf('let %s = %s', key, string(dflt))
1351                 else
1352                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1353                                                 \ a:force, key, string(dflt))
1354                         continue
1355                 endif
1356                 exec cmd
1357         endfor
1358 endfunction
1359 call NM_set_defaults(0)
1360
1361 " for some reason NM_set_defaults() didn't work for arrays...
1362 if !exists('g:notmuch_show_headers')
1363         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1364 endif
1365 if !exists('g:notmuch_initial_search_words')
1366         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1367 endif
1368 if !exists('g:notmuch_folders')
1369         let g:notmuch_folders = s:notmuch_folders_defaults
1370 endif
1371
1372 if !exists('g:notmuch_signature')
1373         let g:notmuch_signature = s:notmuch_signature_defaults
1374 endif
1375 if !exists('g:notmuch_compose_headers')
1376         let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1377 endif
1378
1379 " --- assign keymaps {{{1
1380
1381 function! s:NM_set_map(type, maps)
1382         nmapclear
1383         for [key, code] in items(a:maps)
1384                 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1385         endfor
1386         " --- this is a hack for development :)
1387         nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1388 endfunction
1389
1390 " --- command handler {{{1
1391
1392 function! NotMuch(args)
1393         let args = a:args
1394         if !strlen(args)
1395                 let args = 'folders'
1396         endif
1397
1398         let words = <SID>NM_shell_split(args)
1399         if words[0] == 'folders' || words[0] == 'f'
1400                 let words = words[1:]
1401                 call <SID>NM_cmd_folders(words)
1402
1403         elseif words[0] == 'search' || words[0] == 's'
1404                 if len(words) > 1
1405                         let words = words[1:]
1406                 elseif exists('b:nm_search_words')
1407                         let words = b:nm_search_words
1408                 else
1409                         let words = g:notmuch_initial_search_words
1410                 endif
1411                 call <SID>NM_cmd_search(words)
1412
1413         elseif words[0] == 'show'
1414                 echoe 'show is not yet implemented.'
1415
1416         elseif words[0] == 'new' || words[0] == 'compose'
1417                 let words = words[1:]
1418                 call <SID>NM_cmd_compose(words, [])
1419         endif
1420 endfunction
1421 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1422         return []
1423 endfunction
1424
1425
1426 " --- glue {{{1
1427
1428 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1429 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1430
1431 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :