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