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