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