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