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