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