]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
clear the nmap before creating our bindings
[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         \
27         \ 'g:notmuch_search_newest_first':           1                            ,
28         \ 'g:notmuch_search_from_column_width':      20                           ,
29         \
30         \ 'g:notmuch_show_fold_signatures':          1                            ,
31         \ 'g:notmuch_show_fold_citations':           1                            ,
32         \ 'g:notmuch_show_fold_bodies':              0                            ,
33         \ 'g:notmuch_show_fold_headers':             1                            ,
34         \
35         \ 'g:notmuch_show_message_begin_regexp':     '^\fmessage{'                ,
36         \ 'g:notmuch_show_message_end_regexp':       '^\fmessage}'                ,
37         \ 'g:notmuch_show_header_begin_regexp':      '^\fheader{'                 ,
38         \ 'g:notmuch_show_header_end_regexp':        '^\fheader}'                 ,
39         \ 'g:notmuch_show_body_begin_regexp':        '^\fbody{'                   ,
40         \ 'g:notmuch_show_body_end_regexp':          '^\fbody}'                   ,
41         \ 'g:notmuch_show_attachment_begin_regexp':  '^\fattachment{'             ,
42         \ 'g:notmuch_show_attachment_end_regexp':    '^\fattachment}'             ,
43         \ 'g:notmuch_show_part_begin_regexp':        '^\fpart{'                   ,
44         \ 'g:notmuch_show_part_end_regexp':          '^\fpart}'                   ,
45         \ 'g:notmuch_show_marker_regexp':            '^\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
46         \
47         \ 'g:notmuch_show_message_parse_regexp':     '\(id:[^ ]*\) depth:\([0-9]*\) filename:\(.*\)$',
48         \ 'g:notmuch_show_tags_regexp':              '(\([^)]*\))$'               ,
49         \
50         \ 'g:notmuch_show_signature_regexp':         '^\(-- \?\|_\+\)$'           ,
51         \ 'g:notmuch_show_signature_lines_max':      12                           ,
52         \
53         \ 'g:notmuch_show_citation_regexp':          '^\s*>'                      ,
54         \ }
55
56 " defaults for g:notmuch_initial_search_words
57 " override with: let g:notmuch_initial_search_words = [ ... ]
58 let s:notmuch_initial_search_words_defaults = [
59         \ 'tag:inbox and tag:unread',
60         \ ]
61
62 " defaults for g:notmuch_show_headers
63 " override with: let g:notmuch_show_headers = [ ... ]
64 let s:notmuch_show_headers_defaults = [
65         \ 'Subject',
66         \ 'To',
67         \ 'Cc',
68         \ 'Bcc',
69         \ 'Date',
70         \ ]
71
72 " --- keyboard mapping definitions {{{1
73
74 " --- --- bindings for search screen {{{2
75 let g:notmuch_search_maps = {
76         \ '<Enter>':    ':call <SID>NM_search_show_thread()<CR>',
77         \ 'a':          ':call <SID>NM_search_archive_thread()<CR>',
78         \ 'f':          ':call <SID>NM_search_filter()<CR>',
79         \ 'm':          ':call <SID>NM_new_mail()<CR>',
80         \ 'o':          ':call <SID>NM_search_toggle_order()<CR>',
81         \ 'r':          ':call <SID>NM_search_reply_to_thread()<CR>',
82         \ 's':          ':call <SID>NM_search_prompt()<CR>',
83         \ 'S':          ':call <SID>NM_search_edit()<CR>',
84         \ 't':          ':call <SID>NM_search_filter_by_tag()<CR>',
85         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
86         \ '+':          ':call <SID>NM_search_add_tags([])<CR>',
87         \ '-':          ':call <SID>NM_search_remove_tags([])<CR>',
88         \ '=':          ':call <SID>NM_search_refresh_view()<CR>',
89         \ }
90
91 " --- --- bindings for show screen {{{2
92 let g:notmuch_show_maps = {
93         \ '<C-P>':      ':call <SID>NM_show_prev(1)<CR>',
94         \ '<C-N>':      ':call <SID>NM_show_next(1)<CR>',
95         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
96         \
97         \ 'b':          ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
98         \ 'c':          ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
99         \ 'h':          ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
100         \ 's':          ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
101         \
102         \ 'a':          ':call <SID>NM_show_archive_thread()<CR>',
103         \ 'A':          ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
104         \ 'N':          ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
105         \ 'v':          ':call <SID>NM_show_view_all_mime_parts()<CR>',
106         \ '+':          ':call <SID>NM_show_add_tag()<CR>',
107         \ '-':          ':call <SID>NM_show_remove_tag()<CR>',
108         \ '<Space>':    ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
109         \ '\|':         ':call <SID>NM_show_pipe_message()<CR>',
110         \
111         \ 'r':          ':call <SID>NM_show_reply()<CR>',
112         \ 'm':          ':call <SID>NM_new_mail()<CR>',
113         \ }
114
115
116 " --- implement search screen {{{1
117
118 function! s:NM_cmd_search(words)
119         let cmd = ['search']
120         if g:notmuch_search_newest_first
121                 let cmd = cmd + ['--sort=newest-first']
122         else
123                 let cmd = cmd + ['--sort=oldest-first']
124         endif
125         let data = s:NM_run(cmd + a:words)
126         "let data = substitute(data, '27/27', '25/27', '')
127         "let data = substitute(data, '\[4/4\]', '[0/4]', '')
128         let lines = split(data, "\n")
129         let disp = copy(lines)
130         "call map(disp, 'substitute(v:val, "^thread:\\S* ", "", "")' )
131         call map(disp, 's:NM_cmd_search_fmtline(v:val)')
132
133         call <SID>NM_newBuffer('search', join(disp, "\n"))
134         let b:nm_raw_lines = lines
135         let b:nm_search_words = a:words
136
137         call <SID>NM_cmd_search_mksyntax()
138         call <SID>NM_set_map(g:notmuch_search_maps)
139         setlocal cursorline
140         setlocal nowrap
141 endfunction
142 function! s:NM_cmd_search_fmtline(line)
143         let m = matchlist(a:line, '^\(thread:\S\+\)\s\([^]]\+\]\) \([^;]\+\); \(.*\) (\([^(]*\))$')
144         if !len(m)
145                 return 'ERROR PARSING: ' . a:line
146         endif
147         let max = g:notmuch_search_from_column_width
148         let from = m[3]
149         if strlen(from) >= max
150                 let from = m[3][0:max-4] . '...'
151         endif
152         return printf('%s %-20s | %s (%s)', m[2], from, m[4], m[5])
153 endfunction
154 function! s:NM_cmd_search_mksyntax()
155         syntax clear nmSearchFrom
156         "syntax region nmSearchFrom start='\]\@<=' end='.'me=e+5,he=e+5,re=e+5 oneline contained
157         "syntax match nmSearchFrom /\]\@<=.\{10\}/ oneline contained
158         exec printf('syntax match nmSearchFrom /\(\] \)\@<=.\{%d\}/ oneline contained', g:notmuch_search_from_column_width)
159         "exec printf('syntax region nmSearchFrom start=''\%%%dv'' end=''\%%%dv'' oneline contained', 20, 30)
160 endfunction
161
162 " --- --- search screen action functions {{{2
163
164 function! s:NM_search_show_thread()
165         let id = <SID>NM_search_find_thread_id()
166         if id != ''
167                 call <SID>NM_cmd_show([id])
168         endif
169 endfunction
170
171 function! s:NM_search_prompt()
172         " TODO: input() can support completion
173         let text = input('NotMuch Search: ')
174         if strlen(text)
175                 let tags = split(text)
176         else
177                 let tags = s:notmuch_initial_search_words_defaults
178         endif
179         setlocal bufhidden=delete
180         call <SID>NM_cmd_search(tags)
181 endfunction
182
183 function! s:NM_search_edit()
184         " TODO: input() can support completion
185         let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
186         if strlen(text)
187                 call <SID>NM_cmd_search(split(text))
188         endif
189 endfunction
190
191 function! s:NM_search_archive_thread()
192         call <SID>NM_add_remove_tags_on_screen('-', ['inbox'])
193         call <SID>NM_add_remove_tags('-', ['inbox'])
194         norm j
195 endfunction
196
197 function! s:NM_search_filter()
198         call <SID>NM_search_filter_helper('Filter: ', '')
199 endfunction
200
201 function! s:NM_search_filter_by_tag()
202         call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:')
203 endfunction
204
205 function! s:NM_search_filter_helper(prompt, prefix)
206         " TODO: input() can support completion
207         let text = input(a:prompt)
208         if !strlen(text)
209                 return
210         endif
211
212         let tags = split(text)
213         map(tags, 'and a:prefix . v:val')
214         let tags = b:nm_search_words + tags
215         echo tags
216
217         let prev_bufnr = bufnr('%')
218         setlocal bufhidden=hide
219         call <SID>NM_cmd_search(tags)
220         setlocal bufhidden=delete
221         let b:nm_prev_bufnr = prev_bufnr
222 endfunction
223
224 function! s:NM_search_toggle_order()
225         let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
226         " FIXME: maybe this would be better done w/o reading re-reading the lines
227         "         reversing the b:nm_raw_lines and the buffer lines would be better
228         call <SID>NM_search_refresh_view()
229 endfunction
230
231 function! s:NM_search_reply_to_thread()
232         echo 'not implemented'
233 endfunction
234
235 function! s:NM_search_add_tags(tags)
236         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
237 endfunction
238
239 function! s:NM_search_remove_tags(tags)
240         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
241 endfunction
242
243 function! s:NM_search_refresh_view()
244         let lno = line('.')
245         setlocal bufhidden=delete
246         call <SID>NM_cmd_search(b:nm_search_words)
247         " FIXME: should find the line of the thread we were on if possible
248         exec printf('norm %dG', lno)
249 endfunction
250
251 " --- --- search screen helper functions {{{2
252
253 function! s:NM_search_find_thread_id()
254         if !exists('b:nm_raw_lines')
255                 echoe 'no b:nm_raw_lines'
256                 return ''
257         else
258                 let line = line('.')
259                 let info = b:nm_raw_lines[line-1]
260                 let what = split(info, '\s\+')[0]
261                 return what
262         endif
263 endfunction
264
265 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
266         if type(a:intags) != type([]) || len(a:intags) == 0
267                 " TODO: input() can support completion
268                 let text = input(a:prompt)
269                 if !strlen(text)
270                         return
271                 endif
272                 let tags = split(text, ' ')
273         else
274                 let tags = a:intags
275         endif
276         call <SID>NM_add_remove_tags(a:prefix, tags)
277         call <SID>NM_add_remove_tags_on_screen(a:prefix, tags)
278 endfunction
279
280 " --- implement show screen {{{1
281
282 function! s:NM_cmd_show(words)
283         let prev_bufnr = bufnr('%')
284         let data = s:NM_run(['show'] + a:words)
285         let lines = split(data, "\n")
286
287         let info = s:NM_cmd_show_parse(lines)
288
289         setlocal bufhidden=hide
290         call <SID>NM_newBuffer('show', join(info['disp'], "\n"))
291         setlocal bufhidden=delete
292         let b:nm_raw_info = info
293         let b:nm_prev_bufnr = prev_bufnr
294
295         call <SID>NM_cmd_show_mkfolds()
296         call <SID>NM_cmd_show_mksyntax()
297         call <SID>NM_set_map(g:notmuch_show_maps)
298         setlocal foldtext=NM_cmd_show_foldtext()
299         setlocal fillchars=
300         setlocal foldcolumn=6
301
302 endfunction
303
304 function! s:NM_show_prev(can_change_thread)
305         let info = b:nm_raw_info
306         let lnum = line('.')
307         for msg in reverse(copy(info['msgs']))
308                 if lnum <= msg['start']
309                         continue
310                 endif
311
312                 exec printf('norm %dG', msg['start'])
313                 " TODO: try to fit the message on screen
314                 norm zz
315                 return
316         endfor
317         if !a:can_change_thread
318                 return
319         endif
320         call <SID>NM_kill_this_buffer()
321         if line('.') != line('0')
322                 norm k
323                 call <SID>NM_search_show_thread()
324                 norm G
325                 call <SID>NM_show_prev(0)
326         else
327                 echo 'No more messages.'
328         endif
329 endfunction
330
331 function! s:NM_show_next(can_change_thread)
332         let info = b:nm_raw_info
333         let lnum = line('.')
334         for msg in info['msgs']
335                 if lnum >= msg['start']
336                         continue
337                 endif
338
339                 exec printf('norm %dG', msg['start'])
340                 " TODO: try to fit the message on screen
341                 norm zz
342                 return
343         endfor
344         if !a:can_change_thread
345                 return
346         endif
347         call <SID>NM_kill_this_buffer()
348         if line('.') != line('$')
349                 norm j
350                 call <SID>NM_search_show_thread()
351         else
352                 echo 'No more messages.'
353         endif
354 endfunction
355
356 function! s:NM_show_archive_thread()
357         echo 'not implemented'
358 endfunction
359
360 function! s:NM_show_mark_read_then_archive_thread()
361         echo 'not implemented'
362 endfunction
363
364 function! s:NM_show_next_message()
365         echo 'not implemented'
366 endfunction
367
368 function! s:NM_show_mark_read_then_next_open_message()
369         echo 'not implemented'
370 endfunction
371
372 function! s:NM_show_previous_message()
373         echo 'not implemented'
374 endfunction
375
376 function! s:NM_show_reply()
377         echo 'not implemented'
378 endfunction
379
380 function! s:NM_show_view_all_mime_parts()
381         echo 'not implemented'
382 endfunction
383
384 function! s:NM_show_view_raw_message()
385         echo 'not implemented'
386 endfunction
387
388 function! s:NM_show_add_tag()
389         echo 'not implemented'
390 endfunction
391
392 function! s:NM_show_remove_tag()
393         echo 'not implemented'
394 endfunction
395
396 function! s:NM_show_advance_marking_read_and_archiving()
397         echo 'not implemented'
398 endfunction
399
400 function! s:NM_show_pipe_message()
401         echo 'not implemented'
402 endfunction
403
404 " --- --- search screen helper functions {{{2
405
406 function! s:NM_show_fold_toggle(key, type, fold)
407         let info = b:nm_raw_info
408         let act = 'open'
409         if a:fold
410                 let act = 'close'
411         endif
412         for fld in info['folds']
413                 if fld[0] == a:type
414                         exec printf('%dfold%s', fld[1], act)
415                 endif
416         endfor
417         exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
418 endfunction
419
420
421 " s:NM_cmd_show_parse returns the following dictionary:
422 "    'disp':     lines to display
423 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
424 "    'folds':    fold info arrays [ type, start, end ]
425 "    'foldtext': fold text indexed by start line
426 function! s:NM_cmd_show_parse(inlines)
427         let info = { 'disp': [],       
428                    \ 'msgs': [],       
429                    \ 'folds': [],      
430                    \ 'foldtext': {} }  
431         let msg = {}
432         let hdr = {}
433
434         let in_message = 0
435         let in_header = 0
436         let in_body = 0
437         let in_part = ''
438
439         let body_start = -1
440         let part_start = -1
441
442         let mode_type = ''
443         let mode_start = -1
444
445         let inlnum = 0
446         for line in a:inlines
447                 let inlnum = inlnum + 1
448                 let foldinfo = []
449
450                 if strlen(in_part)
451                         let part_end = 0
452
453                         if match(line, g:notmuch_show_part_end_regexp) != -1
454                                 let part_end = len(info['disp'])
455                         else
456                                 call add(info['disp'], line)
457                         endif
458
459                         if in_part == 'text/plain'
460                                 if !part_end && mode_type == ''
461                                         if match(line, g:notmuch_show_signature_regexp) != -1
462                                                 let mode_type = 'sig'
463                                                 let mode_start = len(info['disp'])
464                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
465                                                 let mode_type = 'cit'
466                                                 let mode_start = len(info['disp'])
467                                         endif
468                                 elseif mode_type == 'cit'
469                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
470                                                 let outlnum = len(info['disp'])
471                                                 if mode_start != outlnum
472                                                         let foldinfo = [ mode_type, mode_start, outlnum-1,
473                                                                        \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
474                                                 endif
475                                                 let mode_type = ''
476                                         endif
477                                 elseif mode_type == 'sig'
478                                         let outlnum = len(info['disp'])
479                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
480                                                 let mode_type = ''
481                                         elseif part_end
482                                                 let foldinfo = [ mode_type, mode_start, outlnum,
483                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
484                                                 let mode_type = ''
485                                         endif
486                                 endif
487                         endif
488
489                         if part_end
490                                 " FIXME: this is a hack for handling two folds being added for one line
491                                 "         we should handle addinga fold in a function
492                                 if len(foldinfo)
493                                         call add(info['folds'], foldinfo[0:2])
494                                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
495                                 endif
496
497                                 let foldinfo = [ 'text', part_start, part_end,
498                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
499                                 let in_part = ''
500                                 call add(info['disp'], '')
501                         endif
502
503                 elseif in_body
504                         if !has_key(msg,'body_start')
505                                 let msg['body_start'] = len(info['disp']) + 1
506                         endif
507                         if match(line, g:notmuch_show_body_end_regexp) != -1
508                                 let body_end = len(info['disp'])
509                                 let foldinfo = [ 'bdy', body_start, body_end,
510                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
511
512                                 let in_body = 0
513
514                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
515                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
516                                 let in_part = 'unknown'
517                                 if len(m)
518                                         let in_part = m[2]
519                                 endif
520                                 call add(info['disp'],
521                                          \ printf('--- %s ---', in_part))
522                                 let part_start = len(info['disp']) + 1
523                         endif
524
525                 elseif in_header
526                         if in_header == 1
527                                 let msg['descr'] = line
528                                 call add(info['disp'], line)
529                                 let in_header = 2
530                                 let msg['hdr_start'] = len(info['disp']) + 1
531
532                         else
533                                 if match(line, g:notmuch_show_header_end_regexp) != -1
534                                         let hdr_start = msg['hdr_start']+1
535                                         let hdr_end = len(info['disp'])
536                                         let foldinfo = [ 'hdr', hdr_start, hdr_end,
537                                                \ printf('[ %d-line headers.  Press "h" to show. ]', hdr_end - hdr_start) ]
538                                         let msg['header'] = hdr
539                                         let in_header = 0
540                                         let hdr = {}
541                                 else
542                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
543                                         if len(m)
544                                                 let hdr[m[1]] = m[2]
545                                                 if match(g:notmuch_show_headers, m[1]) != -1
546                                                         call add(info['disp'], line)
547                                                 endif
548                                         endif
549                                 endif
550                         endif
551
552                 elseif in_message
553                         if match(line, g:notmuch_show_message_end_regexp) != -1
554                                 let msg['end'] = len(info['disp'])
555                                 call add(info['disp'], '')
556
557                                 let foldinfo = [ 'msg', msg['start'], msg['end'],
558                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
559
560                                 call add(info['msgs'], msg)
561                                 let msg = {}
562                                 let in_message = 0
563                                 let in_header = 0
564                                 let in_body = 0
565                                 let in_part = ''
566
567                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
568                                 let in_header = 1
569                                 continue
570
571                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
572                                 let body_start = len(info['disp']) + 1
573                                 let in_body = 1
574                                 continue
575                         endif
576
577                 else
578                         if match(line, g:notmuch_show_message_begin_regexp) != -1
579                                 let msg['start'] = len(info['disp']) + 1
580
581                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
582                                 if len(m)
583                                         let msg['id'] = m[1]
584                                         let msg['depth'] = m[2]
585                                         let msg['filename'] = m[3]
586                                 endif
587
588                                 let in_message = 1
589                         endif
590                 endif
591
592                 if len(foldinfo)
593                         call add(info['folds'], foldinfo[0:2])
594                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
595                 endif
596         endfor
597         return info
598 endfunction
599
600 function! s:NM_cmd_show_mkfolds()
601         let info = b:nm_raw_info
602
603         for afold in info['folds']
604                 exec printf('%d,%dfold', afold[1], afold[2])
605                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
606                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
607                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
608                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
609                         exec printf('%dfoldclose', afold[1])
610                 else
611                         exec printf('%dfoldopen', afold[1])
612                 endif
613         endfor
614 endfunction
615
616 function! s:NM_cmd_show_mksyntax()
617         let info = b:nm_raw_info
618         let cnt = 0
619         for msg in info['msgs']
620                 let cnt = cnt + 1
621                 let start = msg['start']
622                 let hdr_start = msg['hdr_start']
623                 let body_start = msg['body_start']
624                 let end = msg['end']
625                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
626                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
627                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
628         endfor
629 endfunction
630
631 function! NM_cmd_show_foldtext()
632         let foldtext = b:nm_raw_info['foldtext']
633         return foldtext[v:foldstart]
634 endfunction
635
636
637 " --- notmuch helper functions {{{1
638
639 function! s:NM_newBuffer(ft, content)
640         enew
641         setlocal buftype=nofile readonly modifiable
642         silent put=a:content
643         keepjumps 0d
644         setlocal nomodifiable
645         execute printf('set filetype=notmuch-%s', a:ft)
646         execute printf('set syntax=notmuch-%s', a:ft)
647 endfunction
648
649 function! s:NM_run(args)
650         let cmd = g:notmuch_cmd . ' ' . join(a:args) . '< /dev/null'
651
652         let start = reltime()
653         let out = system(cmd)
654         let err = v:shell_error
655         let delta = reltime(start)
656
657         echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
658
659         if err
660                 echohl Error
661                 echo substitute(out, '\n*$', '', '')
662                 echohl None
663                 return ''
664         else
665                 return out
666         endif
667 endfunction
668
669 " --- external mail handling helpers {{{1
670
671 function! s:NM_new_mail()
672         echo 'not implemented'
673 endfunction
674
675 " --- other helpers {{{1
676
677 function! s:NM_kill_this_buffer()
678         if exists('b:nm_prev_bufnr')
679                 setlocal bufhidden=delete
680                 exec printf(":buffer %d", b:nm_prev_bufnr)
681         else
682                 echo "Nothing to kill."
683         endif
684 endfunction
685
686 function! s:NM_add_remove_tags(prefix, tags)
687         let id = <SID>NM_search_find_thread_id()
688         if id == ''
689                 echoe 'Eeek! I couldn''t find the thead id!'
690         endif
691         call map(a:tags, 'a:prefix . v:val')
692         " TODO: handle errors
693         call <SID>NM_run(['tag'] + a:tags + ['--', id])
694 endfunction
695
696 function! s:NM_add_remove_tags_on_screen(prefix, tags)
697         let online = ''
698         setlocal modifiable
699         if a:prefix == '-'
700                 for tagname in a:tags
701                         exec printf('silent %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', online, tagname)
702                 endfor
703         else
704                 for tagname in a:tags
705                         exec printf('silent %ss/(\([^)]*\)\([^)]*\))$/(\1 %s)/', online, tagname)
706                 endfor
707         endif
708         setlocal nomodifiable
709 endfunction
710
711 " --- process and set the defaults {{{1
712
713 function! NM_set_defaults(force)
714         for [key, dflt] in items(s:notmuch_defaults)
715                 let cmd = ''
716                 if !a:force && exists(key) && type(dflt) == type(eval(key))
717                         continue
718                 elseif type(dflt) == type(0)
719                         let cmd = printf('let %s = %d', key, dflt)
720                 elseif type(dflt) == type('')
721                         let cmd = printf('let %s = ''%s''', key, dflt)
722                 "elseif type(dflt) == type([])
723                 "        let cmd = printf('let %s = %s', key, string(dflt))
724                 else
725                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
726                                                 \ a:force, key, string(dflt))
727                         continue
728                 endif
729                 exec cmd
730         endfor
731 endfunction
732 call NM_set_defaults(0)
733
734 " for some reason NM_set_defaults() didn't work for arrays...
735 if !exists('g:notmuch_show_headers')
736         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
737 endif
738 if !exists('g:notmuch_initial_search_words')
739         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
740 endif
741
742
743 " --- assign keymaps {{{1
744
745 function! s:NM_set_map(maps)
746         nmapclear
747         for [key, code] in items(a:maps)
748                 exec printf('nnoremap <buffer> %s %s', key, code)
749         endfor
750 endfunction
751
752 " --- command handler {{{1
753
754 function! NotMuch(args)
755         if !strlen(a:args)
756                 if exists('b:nm_search_words')
757                         let words = b:nm_search_words
758                 else
759                         let words = g:notmuch_initial_search_words
760                 endif
761                 call <SID>NM_cmd_search(words)
762                 return
763         endif
764
765         echo "blarg!"
766
767         let words = split(a:args)
768         " TODO: handle commands passed as arguments
769 endfunction
770 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
771         return []
772 endfunction
773
774
775 " --- glue {{{1
776
777 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
778 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
779
780 " --- hacks, only for development :) {{{1
781
782 nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
783
784 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :