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