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