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