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