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