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