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