]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
vim: cleanup tag filtering
[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:', 'and')
279 endfunction
280
281 function! s:NM_search_filter_helper(prompt, prefix, joiner)
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         if strlen(a:prefix)
290                 call map(tags, 'a:prefix . v:val')
291         endif
292         if strlen(a:joiner)
293                 let idx = len(tags) - 1
294                 while idx > 0
295                         call insert(tags, a:joiner, idx)
296                         let idx = idx - 1
297                 endwhile
298         endif
299         let tags = b:nm_search_words + ['and', '''('] + tags + [')''']
300
301         let prev_bufnr = bufnr('%')
302         setlocal bufhidden=hide
303         call <SID>NM_cmd_search(tags)
304         setlocal bufhidden=delete
305         let b:nm_prev_bufnr = prev_bufnr
306 endfunction
307
308 function! s:NM_search_toggle_order()
309         let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
310         " FIXME: maybe this would be better done w/o reading re-reading the lines
311         "         reversing the b:nm_raw_lines and the buffer lines would be better
312         call <SID>NM_search_refresh_view()
313 endfunction
314
315 function! s:NM_search_reply_to_thread()
316         echo 'not implemented'
317 endfunction
318
319 function! s:NM_search_add_tags(tags)
320         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
321 endfunction
322
323 function! s:NM_search_remove_tags(tags)
324         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
325 endfunction
326
327 function! s:NM_search_refresh_view()
328         let lno = line('.')
329         setlocal bufhidden=delete
330         call <SID>NM_cmd_search(b:nm_search_words)
331         " FIXME: should find the line of the thread we were on if possible
332         exec printf('norm %dG', lno)
333 endfunction
334
335 " --- --- search screen helper functions {{{2
336
337 function! s:NM_search_thread_id()
338         if !exists('b:nm_raw_lines')
339                 echoe 'no b:nm_raw_lines'
340                 return ''
341         else
342                 let line = line('.')
343                 let info = b:nm_raw_lines[line-1]
344                 let what = split(info, '\s\+')[0]
345                 return what
346         endif
347 endfunction
348
349 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
350         if type(a:intags) != type([]) || len(a:intags) == 0
351                 " TODO: input() can support completion
352                 let text = input(a:prompt)
353                 if !strlen(text)
354                         return
355                 endif
356                 let tags = split(text, ' ')
357         else
358                 let tags = a:intags
359         endif
360         call <SID>NM_add_remove_tags(a:prefix, tags)
361         call <SID>NM_add_remove_tags_on_screen(a:prefix, tags)
362 endfunction
363
364 " --- implement show screen {{{1
365
366 function! s:NM_cmd_show(words)
367         let prev_bufnr = bufnr('%')
368         let data = s:NM_run(['show'] + a:words)
369         let lines = split(data, "\n")
370
371         let info = s:NM_cmd_show_parse(lines)
372
373         setlocal bufhidden=hide
374         call <SID>NM_newBuffer('show', join(info['disp'], "\n"))
375         setlocal bufhidden=delete
376         let b:nm_words = a:words
377         let b:nm_raw_info = info
378         let b:nm_prev_bufnr = prev_bufnr
379
380         call <SID>NM_cmd_show_mkfolds()
381         call <SID>NM_cmd_show_mksyntax()
382         call <SID>NM_set_map(g:notmuch_show_maps)
383         setlocal foldtext=NM_cmd_show_foldtext()
384         setlocal fillchars=
385         setlocal foldcolumn=6
386
387 endfunction
388
389 function! s:NM_show_previous(can_change_thread)
390         let info = b:nm_raw_info
391         let lnum = line('.')
392         for msg in reverse(copy(info['msgs']))
393                 if lnum <= msg['start']
394                         continue
395                 endif
396
397                 exec printf('norm %dG', msg['start'])
398                 " TODO: try to fit the message on screen
399                 norm zz
400                 return
401         endfor
402         if !a:can_change_thread
403                 return
404         endif
405         call <SID>NM_kill_this_buffer()
406         if line('.') != line('0')
407                 norm k
408                 call <SID>NM_search_show_thread()
409                 norm G
410                 call <SID>NM_show_previous(0)
411         else
412                 echo 'No more messages.'
413         endif
414 endfunction
415
416 function! s:NM_show_next(can_change_thread)
417         let info = b:nm_raw_info
418         let lnum = line('.')
419         for msg in info['msgs']
420                 if lnum >= msg['start']
421                         continue
422                 endif
423
424                 exec printf('norm %dG', msg['start'])
425                 " TODO: try to fit the message on screen
426                 norm zz
427                 return
428         endfor
429         if !a:can_change_thread
430                 return
431         endif
432         call <SID>NM_kill_this_buffer()
433         if line('.') != line('$')
434                 norm j
435                 call <SID>NM_search_show_thread()
436         else
437                 echo 'No more messages.'
438         endif
439 endfunction
440
441 function! s:NM_show_archive_thread()
442         echo 'not implemented'
443 endfunction
444
445 function! s:NM_show_mark_read_then_archive_thread()
446         echo 'not implemented'
447 endfunction
448
449 function! s:NM_show_next_message()
450         echo 'not implemented'
451 endfunction
452
453 function! s:NM_show_mark_read_then_next_open_message()
454         echo 'not implemented'
455 endfunction
456
457 function! s:NM_show_previous_message()
458         echo 'not implemented'
459 endfunction
460
461 function! s:NM_show_reply()
462         echo 'not implemented'
463 endfunction
464
465 function! s:NM_show_view_all_mime_parts()
466         echo 'not implemented'
467 endfunction
468
469 function! s:NM_show_view_raw_message()
470         echo 'not implemented'
471 endfunction
472
473 function! s:NM_show_add_tag()
474         echo 'not implemented'
475 endfunction
476
477 function! s:NM_show_remove_tag()
478         echo 'not implemented'
479 endfunction
480
481 function! s:NM_show_advance_marking_read_and_archiving()
482         echo 'not implemented'
483 endfunction
484
485 function! s:NM_show_pipe_message()
486         echo 'not implemented'
487 endfunction
488
489 " --- --- show screen helper functions {{{2
490
491 function! s:NM_show_thread_id()
492         if !exists('b:nm_words')
493                 echoe 'no b:nm_words'
494                 return ''
495         endif
496         return b:nm_words[0]
497 endfunction
498
499 function! s:NM_show_message_id()
500         if !exists('b:nm_raw_info')
501                 echoe 'no b:nm_raw_info'
502                 return ''
503         endif
504         let info = b:nm_raw_info
505         let lnum = line('.')
506         for msg in info['msgs']
507                 if lnum >= msg['start']
508                         continue
509                 endif
510
511                 return msg['id']
512         endfor
513         return ''
514 endfunction
515
516 function! s:NM_show_fold_toggle(key, type, fold)
517         let info = b:nm_raw_info
518         let act = 'open'
519         if a:fold
520                 let act = 'close'
521         endif
522         for fld in info['folds']
523                 if fld[0] == a:type
524                         exec printf('%dfold%s', fld[1], act)
525                 endif
526         endfor
527         exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
528 endfunction
529
530
531 " s:NM_cmd_show_parse returns the following dictionary:
532 "    'disp':     lines to display
533 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
534 "    'folds':    fold info arrays [ type, start, end ]
535 "    'foldtext': fold text indexed by start line
536 function! s:NM_cmd_show_parse(inlines)
537         let info = { 'disp': [],       
538                    \ 'msgs': [],       
539                    \ 'folds': [],      
540                    \ 'foldtext': {} }  
541         let msg = {}
542         let hdr = {}
543
544         let in_message = 0
545         let in_header = 0
546         let in_body = 0
547         let in_part = ''
548
549         let body_start = -1
550         let part_start = -1
551
552         let mode_type = ''
553         let mode_start = -1
554
555         let inlnum = 0
556         for line in a:inlines
557                 let inlnum = inlnum + 1
558                 let foldinfo = []
559
560                 if strlen(in_part)
561                         let part_end = 0
562
563                         if match(line, g:notmuch_show_part_end_regexp) != -1
564                                 let part_end = len(info['disp'])
565                         else
566                                 call add(info['disp'], line)
567                         endif
568
569                         if in_part == 'text/plain'
570                                 if !part_end && mode_type == ''
571                                         if match(line, g:notmuch_show_signature_regexp) != -1
572                                                 let mode_type = 'sig'
573                                                 let mode_start = len(info['disp'])
574                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
575                                                 let mode_type = 'cit'
576                                                 let mode_start = len(info['disp'])
577                                         endif
578                                 elseif mode_type == 'cit'
579                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
580                                                 let outlnum = len(info['disp'])
581                                                 let foldinfo = [ mode_type, mode_start, outlnum-1,
582                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
583                                                 let mode_type = ''
584                                         endif
585                                 elseif mode_type == 'sig'
586                                         let outlnum = len(info['disp'])
587                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
588                                                 let mode_type = ''
589                                         elseif part_end
590                                                 let foldinfo = [ mode_type, mode_start, outlnum-1,
591                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
592                                                 let mode_type = ''
593                                         endif
594                                 endif
595                         endif
596
597                         if part_end
598                                 " FIXME: this is a hack for handling two folds being added for one line
599                                 "         we should handle addinga fold in a function
600                                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
601                                         call add(info['folds'], foldinfo[0:2])
602                                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
603                                 endif
604
605                                 let foldinfo = [ 'text', part_start, part_end,
606                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
607                                 let in_part = ''
608                                 call add(info['disp'], '')
609                         endif
610
611                 elseif in_body
612                         if !has_key(msg,'body_start')
613                                 let msg['body_start'] = len(info['disp']) + 1
614                         endif
615                         if match(line, g:notmuch_show_body_end_regexp) != -1
616                                 let body_end = len(info['disp'])
617                                 let foldinfo = [ 'bdy', body_start, body_end,
618                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
619
620                                 let in_body = 0
621
622                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
623                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
624                                 let in_part = 'unknown'
625                                 if len(m)
626                                         let in_part = m[2]
627                                 endif
628                                 call add(info['disp'],
629                                          \ printf('--- %s ---', in_part))
630                                 let part_start = len(info['disp']) + 1
631                         endif
632
633                 elseif in_header
634                         if in_header == 1
635                                 let msg['descr'] = line
636                                 call add(info['disp'], line)
637                                 let in_header = 2
638                                 let msg['hdr_start'] = len(info['disp']) + 1
639
640                         else
641                                 if match(line, g:notmuch_show_header_end_regexp) != -1
642                                         let hdr_start = msg['hdr_start']+1
643                                         let hdr_end = len(info['disp'])
644                                         let foldinfo = [ 'hdr', hdr_start, hdr_end,
645                                                \ printf('[ %d-line headers.  Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
646                                         let msg['header'] = hdr
647                                         let in_header = 0
648                                         let hdr = {}
649                                 else
650                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
651                                         if len(m)
652                                                 let hdr[m[1]] = m[2]
653                                                 if match(g:notmuch_show_headers, m[1]) != -1
654                                                         call add(info['disp'], line)
655                                                 endif
656                                         endif
657                                 endif
658                         endif
659
660                 elseif in_message
661                         if match(line, g:notmuch_show_message_end_regexp) != -1
662                                 let msg['end'] = len(info['disp'])
663                                 call add(info['disp'], '')
664
665                                 let foldinfo = [ 'msg', msg['start'], msg['end'],
666                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
667
668                                 call add(info['msgs'], msg)
669                                 let msg = {}
670                                 let in_message = 0
671                                 let in_header = 0
672                                 let in_body = 0
673                                 let in_part = ''
674
675                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
676                                 let in_header = 1
677                                 continue
678
679                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
680                                 let body_start = len(info['disp']) + 1
681                                 let in_body = 1
682                                 continue
683                         endif
684
685                 else
686                         if match(line, g:notmuch_show_message_begin_regexp) != -1
687                                 let msg['start'] = len(info['disp']) + 1
688
689                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
690                                 if len(m)
691                                         let msg['id'] = m[1]
692                                         let msg['depth'] = m[2]
693                                         let msg['filename'] = m[3]
694                                 endif
695
696                                 let in_message = 1
697                         endif
698                 endif
699
700                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
701                         call add(info['folds'], foldinfo[0:2])
702                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
703                 endif
704         endfor
705         return info
706 endfunction
707
708 function! s:NM_cmd_show_mkfolds()
709         let info = b:nm_raw_info
710
711         for afold in info['folds']
712                 exec printf('%d,%dfold', afold[1], afold[2])
713                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
714                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
715                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
716                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
717                         exec printf('%dfoldclose', afold[1])
718                 else
719                         exec printf('%dfoldopen', afold[1])
720                 endif
721         endfor
722 endfunction
723
724 function! s:NM_cmd_show_mksyntax()
725         let info = b:nm_raw_info
726         let cnt = 0
727         for msg in info['msgs']
728                 let cnt = cnt + 1
729                 let start = msg['start']
730                 let hdr_start = msg['hdr_start']
731                 let body_start = msg['body_start']
732                 let end = msg['end']
733                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
734                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
735                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
736         endfor
737 endfunction
738
739 function! NM_cmd_show_foldtext()
740         let foldtext = b:nm_raw_info['foldtext']
741         return foldtext[v:foldstart]
742 endfunction
743
744
745 " --- notmuch helper functions {{{1
746
747 function! s:NM_newBuffer(type, content)
748         enew
749         setlocal buftype=nofile readonly modifiable
750         silent put=a:content
751         keepjumps 0d
752         setlocal nomodifiable
753         execute printf('set filetype=notmuch-%s', a:type)
754         execute printf('set syntax=notmuch-%s', a:type)
755         let b:nm_type = a:type
756 endfunction
757
758 function! s:NM_run(args)
759         let cmd = g:notmuch_cmd . ' ' . join(a:args) . '< /dev/null'
760
761         let start = reltime()
762         let out = system(cmd)
763         let err = v:shell_error
764         let delta = reltime(start)
765
766         echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
767
768         if err
769                 echohl Error
770                 echo substitute(out, '\n*$', '', '')
771                 echohl None
772                 return ''
773         else
774                 return out
775         endif
776 endfunction
777
778 " --- external mail handling helpers {{{1
779
780 function! s:NM_new_mail()
781         echo 'not implemented'
782 endfunction
783
784 " --- other helpers {{{1
785
786 function! s:NM_kill_this_buffer()
787         if exists('b:nm_prev_bufnr')
788                 setlocal bufhidden=delete
789                 exec printf(":buffer %d", b:nm_prev_bufnr)
790         else
791                 echo "This is the last buffer; use :q<CR> to quit."
792         endif
793 endfunction
794
795 function! s:NM_search_expand(arg)
796         let word = expand(a:arg)
797         let prev_bufnr = bufnr('%')
798         setlocal bufhidden=hide
799         call <SID>NM_cmd_search([word])
800         setlocal bufhidden=delete
801         let b:nm_prev_bufnr = prev_bufnr
802 endfunction
803
804 function! s:NM_add_remove_tags(prefix, tags)
805         let id = <SID>NM_search_thread_id()
806         if id == ''
807                 echoe 'Eeek! I couldn''t find the thead id!'
808         endif
809         call map(a:tags, 'a:prefix . v:val')
810         " TODO: handle errors
811         call <SID>NM_run(['tag'] + a:tags + ['--', id])
812 endfunction
813
814 function! s:NM_add_remove_tags_on_screen(prefix, tags)
815         let online = ''
816         setlocal modifiable
817         if a:prefix == '-'
818                 for tagname in a:tags
819                         exec printf('silent %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', online, tagname)
820                 endfor
821         else
822                 for tagname in a:tags
823                         exec printf('silent %ss/(\([^)]*\)\([^)]*\))$/(\1 %s)/', online, tagname)
824                 endfor
825         endif
826         setlocal nomodifiable
827 endfunction
828
829 " --- process and set the defaults {{{1
830
831 function! NM_set_defaults(force)
832         for [key, dflt] in items(s:notmuch_defaults)
833                 let cmd = ''
834                 if !a:force && exists(key) && type(dflt) == type(eval(key))
835                         continue
836                 elseif type(dflt) == type(0)
837                         let cmd = printf('let %s = %d', key, dflt)
838                 elseif type(dflt) == type('')
839                         let cmd = printf('let %s = ''%s''', key, dflt)
840                 " FIXME: not sure why this didn't work when dflt is an array
841                 "elseif type(dflt) == type([])
842                 "        let cmd = printf('let %s = %s', key, string(dflt))
843                 else
844                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
845                                                 \ a:force, key, string(dflt))
846                         continue
847                 endif
848                 exec cmd
849         endfor
850 endfunction
851 call NM_set_defaults(0)
852
853 " for some reason NM_set_defaults() didn't work for arrays...
854 if !exists('g:notmuch_show_headers')
855         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
856 endif
857 if !exists('g:notmuch_initial_search_words')
858         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
859 endif
860 if !exists('g:notmuch_folders')
861         let g:notmuch_folders = s:notmuch_folders_defaults
862 endif
863
864
865 " --- assign keymaps {{{1
866
867 function! s:NM_set_map(maps)
868         nmapclear
869         for [key, code] in items(a:maps)
870                 exec printf('nnoremap <buffer> %s %s', key, code)
871         endfor
872         " --- this is a hack for development :)
873         nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
874 endfunction
875
876 " --- command handler {{{1
877
878 function! NotMuch(args)
879         let args = a:args
880         if !strlen(args)
881                 let args = 'folders'
882         endif
883
884         let words = split(args)
885         if words[0] == 'folders'
886                 let words = words[1:]
887                 call <SID>NM_cmd_folders(words)
888         elseif words[0] == 'search'
889                 if len(words) > 1
890                         let words = words[1:]
891                 elseif exists('b:nm_search_words')
892                         let words = b:nm_search_words
893                 else
894                         let words = g:notmuch_initial_search_words
895                 endif
896                 call <SID>NM_cmd_search(words)
897
898         elseif words[0] == 'show'
899                 echoe 'show is not yet implemented.'
900         endif
901 endfunction
902 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
903         return []
904 endfunction
905
906
907 " --- glue {{{1
908
909 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
910 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
911
912 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :