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