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