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