]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
vim: generalize compose buffer function further
[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 = []
860         let start_on_line = 0
861
862         let hdrs = { }
863         for word in a:words
864                 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
865                 if !len(m)
866                         throw 'Eeek! bad parameter ''' . string(word) . ''''
867                 endif
868                 let key = substitute(m[1], '\<\w', '\U&', 'g')
869                 if !has_key(hdrs, key)
870                         let hdrs[key] = []
871                 endif
872                 if strlen(m[2])
873                         call add(hdrs[key], m[2])
874                 endif
875         endfor
876
877         if !has_key(hdrs, 'From') || !len(hdrs['From'])
878                 let me = <SID>NM_compose_get_user_email()
879                 let hdrs['From'] = [ me ]
880         endif
881
882         for key in g:notmuch_compose_headers
883                 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
884                 call add(lines, key . ': ' . text)
885                 if !start_on_line && !strlen(text)
886                         let start_on_line = len(lines)
887                 endif
888         endfor
889
890         for [key,val] in items(hdrs)
891                 if match(g:notmuch_compose_headers, key) == -1
892                         let line = key . ': ' . join(val, ', ')
893                         call add(lines, line)
894                 endif
895         endfor
896
897         call add(lines, '')
898         if !start_on_line
899                 let start_on_line = len(lines) + 1
900         endif
901
902         if len(a:body_lines)
903                 call extend(lines, a:body_lines)
904         else
905                 call extend(lines, [ '', '' ])
906         endif
907
908         call <SID>NM_newComposeBuffer(lines, start_on_line)
909 endfunction
910
911 function! s:NM_compose_send()
912         call <SID>NM_assert_buffer_type('compose')
913         let fname = expand('%')
914         let lnum = 1
915         let line = getline(lnum)
916         let hdrs = {}
917         let lst_hdr = ''
918         while match(line, '^$') == -1
919                 if match(line, '^Notmuch-Help:') != -1
920                         " skip it
921                 elseif strlen(lst_hdr) && match(line, '^\s') != -1
922                         let hdrs[lst_hdr][-1] = hdrs[lst_hdr][-1] . substitute(line, '^\s*', ' ', '')
923                 else
924                         let m = matchlist(line, '^\(\w[^:]*\):\s*\(.*\)\s*$')
925                         if !len(m)
926                                 cursor(lnum, 0)
927                                 throw printf('Eeek! invalid header on line %d', lnum)
928                         endif
929                         let key = substitute(m[1], '\<\w', '\U&', 'g')
930                         if strlen(m[2])
931                                 if !has_key(hdrs, key)
932                                         let hdrs[key] = []
933                                 endif
934                                 call add(hdrs[key], m[2])
935                         endif
936                         let lst_hdr = key
937                 endif
938                 let lnum = lnum + 1
939                 let line = getline(lnum)
940         endwhile
941         let body_starts = lnum + 1
942         exec printf('0,%dd', body_starts)
943         write
944
945         "[-a header] [-b bcc-addr] [-c cc-addr] [-s subject] to-addr
946         let cmd = ['mail']
947         let tos = []
948         for [key, vals] in items(hdrs)
949                 if key == 'To'
950                         call extend(tos, vals)
951                 elseif key == 'Bcc'
952                         for adr in vals
953                                 call add(cmd, '-b')
954                                 call add(cmd, adr)
955                         endfor
956                 elseif key == 'Cc'
957                         for adr in vals
958                                 call add(cmd, '-c')
959                                 call add(cmd, adr)
960                         endfor
961                 elseif key == 'Subject'
962                         for txt in vals
963                                 call add(cmd, '-s')
964                                 call add(cmd, txt)
965                         endfor
966                 else
967                         for val in vals
968                                 call add(cmd, '-a')
969                                 call add(cmd, key . ': ' . val)
970                         endfor
971                 endif
972         endfor
973         call extend(cmd, tos)
974
975         call map(cmd, 's:NM_shell_escape(v:val)')
976         let cmdtxt = join(cmd) . '< ' . fname
977         let out = system(cmdtxt)
978         let err = v:shell_error
979         if err
980                 undo
981                 write
982                 call <SID>NM_newBuffer('new', 'error',
983                             \ "While running...\n" .
984                             \ '  ' . cmdtxt . "\n" .
985                             \ "\n" .
986                             \ "Failed with...\n" .
987                             \ substitute(out, '^', '  ', 'g'))
988                 echohl Error
989                 echo 'Eeek! unable to send mail'
990                 echohl None
991                 return
992         endif
993
994         if !exists('b:nm_prev_bufnr')
995                 bdelete
996         else
997                 let prev_bufnr = b:nm_prev_bufnr
998                 bdelete
999                 if prev_bufnr == bufnr('%')
1000                         exec printf("buffer %d", prev_bufnr)
1001                 endif
1002         endif
1003         call delete(fname)
1004         echo 'Mail sent successfully.'
1005 endfunction
1006
1007 function! s:NM_compose_attach()
1008         echo 'not implemented'
1009 endfunction
1010
1011 function! s:NM_compose_next_entry_area()
1012         let lnum = line('.')
1013         let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1014         if lnum < hdr_end
1015                 let lnum = lnum + 1
1016                 let line = getline(lnum)
1017                 if match(line, '^\([^:]\+\):\s*$') == -1
1018                         call cursor(lnum, strlen(line) + 1)
1019                         return ''
1020                 endif
1021                 while match(getline(lnum+1), '^\s') != -1
1022                         let lnum = lnum + 1
1023                 endwhile
1024                 call cursor(lnum, strlen(getline(lnum)) + 1)
1025                 return ''
1026
1027         elseif lnum == hdr_end
1028                 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1029                 return ''
1030         endif
1031         if mode() == 'i'
1032                 if !getbufvar(bufnr('.'), '&et')
1033                         return "\t"
1034                 endif
1035                 let space = ''
1036                 let shiftwidth = a:shiftwidth
1037                 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1038                 " we assume no one has shiftwidth set to more than 40 :)
1039                 return '                                        '[0:shiftwidth]
1040         endif
1041 endfunction
1042
1043 " --- --- compose screen helper functions {{{2
1044
1045 function! s:NM_compose_get_user_email()
1046         let name = substitute(system('id -u -n'), '\v(^\s*|\s*$|\n)', '', 'g')
1047         let fqdn = substitute(system('hostname -f'), '\v(^\s*|\s*$|\n)', '', 'g')
1048
1049         " TODO: do this properly
1050         return name . '@' . fqdn
1051 endfunction
1052
1053 function! s:NM_compose_find_line_match(start, pattern, failure)
1054         let lnum = a:start
1055         let lend = line('$')
1056         while lnum < lend
1057                 if match(getline(lnum), a:pattern) != -1
1058                         return lnum
1059                 endif
1060                 let lnum = lnum + 1
1061         endwhile
1062         return a:failure
1063 endfunction
1064
1065
1066 " --- notmuch helper functions {{{1
1067
1068 function! s:NM_newBuffer(how, type, content)
1069         if strlen(a:how)
1070                 exec a:how
1071         else
1072                 enew
1073         endif
1074         setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1075         silent put=a:content
1076         keepjumps 0d
1077         setlocal nomodifiable
1078         execute printf('set filetype=notmuch-%s', a:type)
1079         execute printf('set syntax=notmuch-%s', a:type)
1080         let b:nm_type = a:type
1081 endfunction
1082
1083 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1084         let fdir = expand(a:fdir)
1085         if !isdirectory(fdir)
1086                 call mkdir(fdir, 'p')
1087         endif
1088         let file_name = <SID>NM_mktemp(fdir, a:fname)
1089         if writefile(a:lines, file_name)
1090                 throw 'Eeek! couldn''t write to temporary file ' . file_name
1091         endif
1092         exec printf('edit %s', file_name)
1093         setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1094         execute printf('set filetype=notmuch-%s', a:type)
1095         execute printf('set syntax=notmuch-%s', a:type)
1096         let b:nm_type = a:type
1097 endfunction
1098
1099 function! s:NM_newComposeBuffer(lines, start_on_line)
1100         let lines = a:lines
1101         let start_on_line = a:start_on_line
1102         let real_hdr_start = 1
1103         if g:notmuch_compose_header_help
1104                 let help_lines = [
1105                   \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1106                   \ 'Notmuch-Help:   ,a    - attach a file',
1107                   \ 'Notmuch-Help:   ,s    - send the message (Notmuch-Help lines will be removed)',
1108                   \ 'Notmuch-Help:   ,q    - abort the message',
1109                   \ 'Notmuch-Help:   <Tab> - skip through header lines',
1110                   \ ]
1111                 call extend(lines, help_lines, 0)
1112                 let real_hdr_start = len(help_lines)
1113                 if start_on_line > 0
1114                         let start_on_line = start_on_line + len(help_lines)
1115                 endif
1116         endif
1117         call extend(lines, g:notmuch_signature)
1118
1119
1120         let prev_bufnr = bufnr('%')
1121         setlocal bufhidden=hide
1122         call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1123                                   \ 'compose', lines)
1124         setlocal bufhidden=hide
1125         let b:nm_prev_bufnr = prev_bufnr
1126
1127         call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1128         call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1129
1130         if start_on_line > 0 && start_on_line <= len(lines)
1131                 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1132         else
1133                 call cursor(real_hdr_start, strlen(getline(real_hdr_start) + 1)
1134                 call <SID>NM_compose_next_entry_area()
1135         endif
1136
1137         if g:notmuch_compose_insert_mode_start
1138                 startinsert!
1139         endif
1140         echo 'Type your message, use <TAB> to jump to next header and then body.'
1141 endfunction
1142
1143 function! s:NM_assert_buffer_type(type)
1144         if !exists('b:nm_type') || b:nm_type != a:type
1145                 throw printf('Eeek! expected type %s, but got %s.', a:type,
1146                             \ exists(b:nm_type) ? b:nm_type : 'something else')
1147         endif
1148 endfunction
1149
1150 function! s:NM_mktemp(dir, name)
1151         let time_stamp = strftime('%Y%m%d-%H%M%S')
1152         let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1153         " TODO: check if it exists, try again
1154         return file_name
1155 endfunction
1156
1157 function! s:NM_shell_escape(word)
1158         " TODO: use shellescape()
1159         let word = substitute(a:word, '''', '\\''', 'g')
1160         return '''' . word . ''''
1161 endfunction
1162
1163 " this function was taken from git.vim, then fixed up
1164 " http://github.com/motemen/git-vim
1165 function! s:NM_shell_split(cmd)
1166         let l:split_cmd = []
1167         let cmd = a:cmd
1168         let iStart = 0
1169         while 1
1170                 let t = match(cmd, '\S', iStart)
1171                 if t < iStart
1172                         break
1173                 endif
1174                 let iStart = t
1175
1176                 let iSpace = match(cmd, '\v(\s|$)', iStart)
1177                 if iSpace < iStart
1178                         break
1179                 endif
1180
1181                 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1182                 if iQuote1 > iSpace || iQuote1 < iStart
1183                         let iEnd = iSpace - 1
1184                         let l:split_cmd += [ cmd[iStart : iEnd] ]
1185                 else
1186                         let q = cmd[iQuote1]
1187                         let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1188                         if iQuote2 < iQuote1
1189                                 throw 'No matching ' . q . ' quote'
1190                         endif
1191                         let iEnd = iQuote2
1192                         let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1193                 endif
1194
1195
1196                 let iStart = iEnd + 1
1197         endwhile
1198
1199         return l:split_cmd
1200 endfunction
1201
1202
1203 function! s:NM_run(args)
1204         let words = a:args
1205         call map(words, 's:NM_shell_escape(v:val)')
1206         let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1207
1208         let start = reltime()
1209         let out = system(cmd)
1210         let err = v:shell_error
1211         let delta = reltime(start)
1212
1213         if exists('g:notmuch_debug') && g:notmuch_debug
1214                 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1215         endif
1216
1217         if err
1218                 echohl Error
1219                 echo substitute(out, '\n*$', '', '')
1220                 echohl None
1221                 return ''
1222         else
1223                 return out
1224         endif
1225 endfunction
1226
1227 " --- external mail handling helpers {{{1
1228
1229 function! s:NM_new_mail()
1230         echo 'not implemented'
1231 endfunction
1232
1233 " --- tag manipulation helpers {{{1
1234
1235 " used to combine an array of words with prefixes and separators
1236 " example:
1237 "     NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1238 "  -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1239 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1240         let res = []
1241         for word in a:words
1242                 if len(res) && strlen(a:separator)
1243                         call add(res, a:separator)
1244                 endif
1245                 call add(res, a:word_prefix . word)
1246         endfor
1247         if len(res) > 1 && strlen(a:brackets)
1248                 if strlen(a:brackets) != 2
1249                         throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1250                 endif
1251                 call insert(res, a:brackets[0])
1252                 call add(res, a:brackets[1])
1253         endif
1254         return res
1255 endfunction
1256
1257 " --- other helpers {{{1
1258
1259 function! s:NM_get_search_words()
1260         if !exists('b:nm_search_words')
1261                 throw 'Eeek! no b:nm_search_words'
1262         endif
1263         return b:nm_search_words
1264 endfunction
1265
1266 function! s:NM_kill_this_buffer()
1267         if exists('b:nm_prev_bufnr')
1268                 let prev_bufnr = b:nm_prev_bufnr
1269                 bdelete!
1270                 exec printf("buffer %d", prev_bufnr)
1271         else
1272                 echo "This is the last buffer; use :q<CR> to quit."
1273         endif
1274 endfunction
1275
1276 function! s:NM_search_expand(arg)
1277         let word = expand(a:arg)
1278         let prev_bufnr = bufnr('%')
1279         setlocal bufhidden=hide
1280         call <SID>NM_cmd_search([word])
1281         setlocal bufhidden=delete
1282         let b:nm_prev_bufnr = prev_bufnr
1283 endfunction
1284
1285 function! s:NM_add_remove_tags(filter, prefix, tags)
1286         let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1287         if !len(filter)
1288                 throw 'Eeek! I couldn''t find the thead id!'
1289         endif
1290         call map(a:tags, 'a:prefix . v:val')
1291         let args = ['tag']
1292         call extend(args, a:tags)
1293         call add(args, '--')
1294         call extend(args, filter)
1295         " TODO: handle errors
1296         call <SID>NM_run(args)
1297 endfunction
1298
1299 function! s:NM_add_remove_tags_on_screen(online, prefix, tags)
1300         setlocal modifiable
1301         if a:prefix == '-'
1302                 for tagname in a:tags
1303                         exec printf('silent! %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', string(a:online), tagname)
1304                 endfor
1305         else
1306                 for tagname in a:tags
1307                         exec printf('silent! %ss/(\([^)]*\))$/(\1 %s)/', string(a:online), tagname)
1308                 endfor
1309         endif
1310         setlocal nomodifiable
1311 endfunction
1312
1313 " --- process and set the defaults {{{1
1314
1315 function! NM_set_defaults(force)
1316         for [key, dflt] in items(s:notmuch_defaults)
1317                 let cmd = ''
1318                 if !a:force && exists(key) && type(dflt) == type(eval(key))
1319                         continue
1320                 elseif type(dflt) == type(0)
1321                         let cmd = printf('let %s = %d', key, dflt)
1322                 elseif type(dflt) == type('')
1323                         let cmd = printf('let %s = ''%s''', key, dflt)
1324                 " FIXME: not sure why this didn't work when dflt is an array
1325                 "elseif type(dflt) == type([])
1326                 "        let cmd = printf('let %s = %s', key, string(dflt))
1327                 else
1328                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1329                                                 \ a:force, key, string(dflt))
1330                         continue
1331                 endif
1332                 exec cmd
1333         endfor
1334 endfunction
1335 call NM_set_defaults(0)
1336
1337 " for some reason NM_set_defaults() didn't work for arrays...
1338 if !exists('g:notmuch_show_headers')
1339         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1340 endif
1341 if !exists('g:notmuch_initial_search_words')
1342         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1343 endif
1344 if !exists('g:notmuch_folders')
1345         let g:notmuch_folders = s:notmuch_folders_defaults
1346 endif
1347
1348 if !exists('g:notmuch_signature')
1349         let g:notmuch_signature = s:notmuch_signature_defaults
1350 endif
1351 if !exists('g:notmuch_compose_headers')
1352         let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1353 endif
1354
1355 " --- assign keymaps {{{1
1356
1357 function! s:NM_set_map(type, maps)
1358         nmapclear
1359         for [key, code] in items(a:maps)
1360                 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1361         endfor
1362         " --- this is a hack for development :)
1363         nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1364 endfunction
1365
1366 " --- command handler {{{1
1367
1368 function! NotMuch(args)
1369         let args = a:args
1370         if !strlen(args)
1371                 let args = 'folders'
1372         endif
1373
1374         let words = <SID>NM_shell_split(args)
1375         if words[0] == 'folders' || words[0] == 'f'
1376                 let words = words[1:]
1377                 call <SID>NM_cmd_folders(words)
1378
1379         elseif words[0] == 'search' || words[0] == 's'
1380                 if len(words) > 1
1381                         let words = words[1:]
1382                 elseif exists('b:nm_search_words')
1383                         let words = b:nm_search_words
1384                 else
1385                         let words = g:notmuch_initial_search_words
1386                 endif
1387                 call <SID>NM_cmd_search(words)
1388
1389         elseif words[0] == 'show'
1390                 echoe 'show is not yet implemented.'
1391
1392         elseif words[0] == 'new' || words[0] == 'compose'
1393                 let words = words[1:]
1394                 call <SID>NM_cmd_compose(words, [])
1395         endif
1396 endfunction
1397 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1398         return []
1399 endfunction
1400
1401
1402 " --- glue {{{1
1403
1404 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1405 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1406
1407 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :