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