]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
vim: fix a case where we started with :NotMuch 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         \ '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, 0)<CR>',
114         \ '<C-N>':      ':call <SID>NM_show_next(1, 0)<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' && exists('b:nm_prev_bufnr')
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         endif
355         let mnum = line('.') - 1
356         if len(b:nm_raw_lines) <= mnum
357                 return ''
358         endif
359         echo 'len=' . string(len(b:nm_raw_lines)) . '  mnum=' . string(mnum)
360         let info = b:nm_raw_lines[mnum]
361         let what = split(info, '\s\+')[0]
362         return what
363 endfunction
364
365 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
366         if type(a:intags) != type([]) || len(a:intags) == 0
367                 " TODO: input() can support completion
368                 let text = input(a:prompt)
369                 if !strlen(text)
370                         return
371                 endif
372                 let tags = split(text, ' ')
373         else
374                 let tags = a:intags
375         endif
376         call <SID>NM_add_remove_tags([], a:prefix, tags)
377         call <SID>NM_add_remove_tags_on_screen('', a:prefix, tags)
378 endfunction
379
380 " --- implement show screen {{{1
381
382 function! s:NM_cmd_show(words)
383         let prev_bufnr = bufnr('%')
384         let data = s:NM_run(['show'] + a:words)
385         let lines = split(data, "\n")
386
387         let info = s:NM_cmd_show_parse(lines)
388
389         setlocal bufhidden=hide
390         call <SID>NM_newBuffer('show', join(info['disp'], "\n"))
391         setlocal bufhidden=delete
392         let b:nm_words = a:words
393         let b:nm_raw_info = info
394         let b:nm_prev_bufnr = prev_bufnr
395
396         call <SID>NM_cmd_show_mkfolds()
397         call <SID>NM_cmd_show_mksyntax()
398         call <SID>NM_set_map(g:notmuch_show_maps)
399         setlocal foldtext=NM_cmd_show_foldtext()
400         setlocal fillchars=
401         setlocal foldcolumn=6
402
403 endfunction
404
405 function! s:NM_show_previous(can_change_thread, find_matching)
406         let info = b:nm_raw_info
407         let lnum = line('.')
408         for msg in reverse(copy(info['msgs']))
409                 if a:find_matching && msg['match'] == '0'
410                         continue
411                 endif
412                 if lnum <= msg['start']
413                         continue
414                 endif
415
416                 exec printf('norm %dGzt', msg['start'])
417                 " TODO: try to fit the message on screen
418                 return
419         endfor
420         if !a:can_change_thread
421                 return
422         endif
423         call <SID>NM_kill_this_buffer()
424         if line('.') > 1
425                 norm k
426                 call <SID>NM_search_show_thread()
427                 norm G
428                 call <SID>NM_show_previous(0, a:find_matching)
429         else
430                 echo 'No more messages.'
431         endif
432 endfunction
433
434 function! s:NM_show_next(can_change_thread, find_matching)
435         let info = b:nm_raw_info
436         let lnum = line('.')
437         for msg in info['msgs']
438                 if a:find_matching && msg['match'] == '0'
439                         continue
440                 endif
441                 if lnum >= msg['start']
442                         continue
443                 endif
444
445                 exec printf('norm %dGzt', msg['start'])
446                 " TODO: try to fit the message on screen
447                 return
448         endfor
449         if a:can_change_thread
450                 call <SID>NM_show_next_thread()
451         endif
452 endfunction
453
454 function! s:NM_show_next_thread()
455         call <SID>NM_kill_this_buffer()
456         if line('.') != line('$')
457                 norm j
458                 call <SID>NM_search_show_thread()
459         else
460                 echo 'No more messages.'
461         endif
462 endfunction
463
464 function! s:NM_show_archive_thread()
465         echo 'not implemented'
466 endfunction
467
468 function! s:NM_show_mark_read_then_archive_thread()
469         echo 'not implemented'
470 endfunction
471
472 function! s:NM_show_mark_read_then_next_open_message()
473         echo 'not implemented'
474 endfunction
475
476 function! s:NM_show_previous_message()
477         echo 'not implemented'
478 endfunction
479
480 function! s:NM_show_reply()
481         echo 'not implemented'
482 endfunction
483
484 function! s:NM_show_view_all_mime_parts()
485         echo 'not implemented'
486 endfunction
487
488 function! s:NM_show_view_raw_message()
489         echo 'not implemented'
490 endfunction
491
492 function! s:NM_show_add_tag()
493         echo 'not implemented'
494 endfunction
495
496 function! s:NM_show_remove_tag()
497         echo 'not implemented'
498 endfunction
499
500 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
501 " otherwise go to next message
502 " any message that is viewed entirely has inbox and unread tags removed
503 function! s:NM_show_advance_marking_read_and_archiving()
504         let advance_tags = ['unread', 'inbox']
505
506         let vis_top = line('w0')
507         let vis_bot = line('w$')
508
509         let msg_top = <SID>NM_show_get_message_for_line(vis_top)
510         if !has_key(msg_top,'id')
511                 echo "No top visible message."
512         endif
513
514         " if the top message is the last message, just expunge the entire thread and move on
515         if msg_top['end'] == line('$')
516                 let ids = []
517                 for msg in b:nm_raw_info['msgs']
518                         if has_key(msg,'match') && msg['match'] != '0'
519                                 if len(ids)
520                                         call add(ids, 'OR')
521                                 endif
522                                 call add(ids, msg['id'])
523                         endif
524                 endfor
525
526                 let filter = ['('] + advance_tags + [')', 'AND', '('] + ids + [')']
527                 call <SID>NM_add_remove_tags(filter, '-', advance_tags)
528                 call <SID>NM_show_next(1, 1)
529                 return
530         endif
531
532         let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
533         if !has_key(msg_bot,'id')
534                 echo "No bottom visible message."
535         endif
536
537         " if entire message fits on the screen, read/archive it, move to the next one
538         if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
539                 call <SID>NM_add_remove_tags_on_screen(msg_top['start'], '-', advance_tags)
540                 exec printf('norm %dG', vis_top)
541                 call <SID>NM_show_next(0, 1)
542                 if has_key(msg_top,'match') && msg_top['match'] != '0'
543                         redraw
544                         " do this last to hide the latency
545                         let filter = ['('] + advance_tags + [')', 'AND', msg_top['id']]
546                         call <SID>NM_add_remove_tags(filter, '-', advance_tags)
547                 endif
548                 return
549         endif
550
551         " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
552         let jmp = winheight(winnr()) / 2
553         let max = msg_bot['end'] - vis_bot
554         if jmp > max
555                 let jmp = max
556         endif
557         exec printf('norm %dGzt', vis_top + jmp)
558         return
559 endfunction
560
561 function! s:NM_show_pipe_message()
562         echo 'not implemented'
563 endfunction
564
565 function! s:NM_show_previous_fold()
566         echo 'not implemented'
567 endfunction
568
569 function! s:NM_show_next_fold()
570         echo 'not implemented'
571 endfunction
572
573 function! s:NM_show_toggle_fold()
574         echo 'not implemented'
575 endfunction
576
577
578 " --- --- show screen helper functions {{{2
579
580 function! s:NM_show_get_message_for_line(line)
581         for msg in b:nm_raw_info['msgs']
582                 if a:line > msg['end']
583                         continue
584                 endif
585                 return msg
586         endfor
587         return {}
588 endfunction
589
590 function! s:NM_show_message_id()
591         if !exists('b:nm_raw_info')
592                 echoe 'no b:nm_raw_info'
593                 return ''
594         endif
595         let msg = <SID>NM_show_get_message_for_line(line('.'))
596         if has_key(msg,'id')
597                 return msg['id']
598         endif
599         return ''
600 endfunction
601
602 function! s:NM_show_search_words()
603         if !exists('b:nm_words')
604                 echoe 'no b:nm_words'
605                 return []
606         endif
607         return b:nm_words
608 endfunction
609
610 function! s:NM_show_fold_toggle(key, type, fold)
611         let info = b:nm_raw_info
612         let act = 'open'
613         if a:fold
614                 let act = 'close'
615         endif
616         for fld in info['folds']
617                 if fld[0] == a:type
618                         exec printf('%dfold%s', fld[1], act)
619                 endif
620         endfor
621         exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
622 endfunction
623
624
625 " s:NM_cmd_show_parse returns the following dictionary:
626 "    'disp':     lines to display
627 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
628 "    'folds':    fold info arrays [ type, start, end ]
629 "    'foldtext': fold text indexed by start line
630 function! s:NM_cmd_show_parse(inlines)
631         let info = { 'disp': [],       
632                    \ 'msgs': [],       
633                    \ 'folds': [],      
634                    \ 'foldtext': {} }  
635         let msg = {}
636         let hdr = {}
637
638         let in_message = 0
639         let in_header = 0
640         let in_body = 0
641         let in_part = ''
642
643         let body_start = -1
644         let part_start = -1
645
646         let mode_type = ''
647         let mode_start = -1
648
649         let inlnum = 0
650         for line in a:inlines
651                 let inlnum = inlnum + 1
652                 let foldinfo = []
653
654                 if strlen(in_part)
655                         let part_end = 0
656
657                         if match(line, g:notmuch_show_part_end_regexp) != -1
658                                 let part_end = len(info['disp'])
659                         else
660                                 call add(info['disp'], line)
661                         endif
662
663                         if in_part == 'text/plain'
664                                 if !part_end && mode_type == ''
665                                         if match(line, g:notmuch_show_signature_regexp) != -1
666                                                 let mode_type = 'sig'
667                                                 let mode_start = len(info['disp'])
668                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
669                                                 let mode_type = 'cit'
670                                                 let mode_start = len(info['disp'])
671                                         endif
672                                 elseif mode_type == 'cit'
673                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
674                                                 let outlnum = len(info['disp'])
675                                                 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
676                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
677                                                 let mode_type = ''
678                                         endif
679                                 elseif mode_type == 'sig'
680                                         let outlnum = len(info['disp'])
681                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
682                                                 let mode_type = ''
683                                         elseif part_end
684                                                 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
685                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
686                                                 let mode_type = ''
687                                         endif
688                                 endif
689                         endif
690
691                         if part_end
692                                 " FIXME: this is a hack for handling two folds being added for one line
693                                 "         we should handle addinga fold in a function
694                                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
695                                         call add(info['folds'], foldinfo[0:3])
696                                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
697                                 endif
698
699                                 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
700                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
701                                 let in_part = ''
702                                 call add(info['disp'], '')
703                         endif
704
705                 elseif in_body
706                         if !has_key(msg,'body_start')
707                                 let msg['body_start'] = len(info['disp']) + 1
708                         endif
709                         if match(line, g:notmuch_show_body_end_regexp) != -1
710                                 let body_end = len(info['disp'])
711                                 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
712                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
713
714                                 let in_body = 0
715
716                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
717                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
718                                 let in_part = 'unknown'
719                                 if len(m)
720                                         let in_part = m[2]
721                                 endif
722                                 call add(info['disp'],
723                                          \ printf('--- %s ---', in_part))
724                                 let part_start = len(info['disp']) + 1
725                         endif
726
727                 elseif in_header
728                         if in_header == 1
729                                 let msg['descr'] = line
730                                 call add(info['disp'], line)
731                                 let in_header = 2
732                                 let msg['hdr_start'] = len(info['disp']) + 1
733
734                         else
735                                 if match(line, g:notmuch_show_header_end_regexp) != -1
736                                         let hdr_start = msg['hdr_start']+1
737                                         let hdr_end = len(info['disp'])
738                                         let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
739                                                \ printf('[ %d-line headers.  Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
740                                         let msg['header'] = hdr
741                                         let in_header = 0
742                                         let hdr = {}
743                                 else
744                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
745                                         if len(m)
746                                                 let hdr[m[1]] = m[2]
747                                                 if match(g:notmuch_show_headers, m[1]) != -1
748                                                         call add(info['disp'], line)
749                                                 endif
750                                         endif
751                                 endif
752                         endif
753
754                 elseif in_message
755                         if match(line, g:notmuch_show_message_end_regexp) != -1
756                                 let msg['end'] = len(info['disp'])
757                                 call add(info['disp'], '')
758
759                                 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
760                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
761
762                                 call add(info['msgs'], msg)
763                                 let msg = {}
764                                 let in_message = 0
765                                 let in_header = 0
766                                 let in_body = 0
767                                 let in_part = ''
768
769                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
770                                 let in_header = 1
771                                 continue
772
773                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
774                                 let body_start = len(info['disp']) + 1
775                                 let in_body = 1
776                                 continue
777                         endif
778
779                 else
780                         if match(line, g:notmuch_show_message_begin_regexp) != -1
781                                 let msg['start'] = len(info['disp']) + 1
782
783                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
784                                 if len(m)
785                                         let msg['id'] = m[1]
786                                         let msg['depth'] = m[2]
787                                         let msg['match'] = m[3]
788                                         let msg['filename'] = m[4]
789                                 endif
790
791                                 let in_message = 1
792                         endif
793                 endif
794
795                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
796                         call add(info['folds'], foldinfo[0:3])
797                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
798                 endif
799         endfor
800         return info
801 endfunction
802
803 function! s:NM_cmd_show_mkfolds()
804         let info = b:nm_raw_info
805
806         for afold in info['folds']
807                 exec printf('%d,%dfold', afold[1], afold[2])
808                 let state = 'open'
809                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
810                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
811                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
812                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
813                         let state = 'close'
814                 elseif afold[0] == 'msg'
815                         let idx = afold[3]
816                         let msg = info['msgs'][idx]
817                         if has_key(msg,'match') && msg['match'] == '0'
818                                 let state = 'close'
819                         endif
820                 endif
821                 exec printf('%dfold%s', afold[1], state)
822         endfor
823 endfunction
824
825 function! s:NM_cmd_show_mksyntax()
826         let info = b:nm_raw_info
827         let cnt = 0
828         for msg in info['msgs']
829                 let cnt = cnt + 1
830                 let start = msg['start']
831                 let hdr_start = msg['hdr_start']
832                 let body_start = msg['body_start']
833                 let end = msg['end']
834                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
835                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
836                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
837         endfor
838 endfunction
839
840 function! NM_cmd_show_foldtext()
841         let foldtext = b:nm_raw_info['foldtext']
842         return foldtext[v:foldstart]
843 endfunction
844
845
846 " --- notmuch helper functions {{{1
847
848 function! s:NM_newBuffer(type, content)
849         enew
850         setlocal buftype=nofile readonly modifiable
851         silent put=a:content
852         keepjumps 0d
853         setlocal nomodifiable
854         set scrolloff=0
855         set sidescrolloff=0
856         execute printf('set filetype=notmuch-%s', a:type)
857         execute printf('set syntax=notmuch-%s', a:type)
858         let b:nm_type = a:type
859 endfunction
860
861 function! s:NM_shell_escape(word)
862         let word = substitute(a:word, '''', '\\''', 'g')
863         return '''' . word . ''''
864 endfunction
865
866 function! s:NM_run(args)
867         let words = a:args
868         call map(words, 's:NM_shell_escape(v:val)')
869         let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
870
871         let start = reltime()
872         let out = system(cmd)
873         let err = v:shell_error
874         let delta = reltime(start)
875
876         if exists('g:notmuch_debug') && g:notmuch_debug
877                 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
878         endif
879
880         if err
881                 echohl Error
882                 echo substitute(out, '\n*$', '', '')
883                 echohl None
884                 return ''
885         else
886                 return out
887         endif
888 endfunction
889
890 " --- external mail handling helpers {{{1
891
892 function! s:NM_new_mail()
893         echo 'not implemented'
894 endfunction
895
896 " --- other helpers {{{1
897
898 function! s:NM_kill_this_buffer()
899         if exists('b:nm_prev_bufnr')
900                 setlocal bufhidden=delete
901                 exec printf(":buffer %d", b:nm_prev_bufnr)
902         else
903                 echo "This is the last buffer; use :q<CR> to quit."
904         endif
905 endfunction
906
907 function! s:NM_search_expand(arg)
908         let word = expand(a:arg)
909         let prev_bufnr = bufnr('%')
910         setlocal bufhidden=hide
911         call <SID>NM_cmd_search([word])
912         setlocal bufhidden=delete
913         let b:nm_prev_bufnr = prev_bufnr
914 endfunction
915
916 function! s:NM_add_remove_tags(filter, prefix, tags)
917         let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
918         if !len(filter)
919                 echoe 'Eeek! I couldn''t find the thead id!'
920         endif
921         call map(a:tags, 'a:prefix . v:val')
922         let args = ['tag']
923         call extend(args, a:tags)
924         call add(args, '--')
925         call extend(args, filter)
926         " TODO: handle errors
927         call <SID>NM_run(args)
928 endfunction
929
930 function! s:NM_add_remove_tags_on_screen(online, prefix, tags)
931         setlocal modifiable
932         if a:prefix == '-'
933                 for tagname in a:tags
934                         exec printf('silent! %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', string(a:online), tagname)
935                 endfor
936         else
937                 for tagname in a:tags
938                         exec printf('silent! %ss/(\([^)]*\)\([^)]*\))$/(\1 %s)/', string(a:online), tagname)
939                 endfor
940         endif
941         setlocal nomodifiable
942 endfunction
943
944 " --- process and set the defaults {{{1
945
946 function! NM_set_defaults(force)
947         for [key, dflt] in items(s:notmuch_defaults)
948                 let cmd = ''
949                 if !a:force && exists(key) && type(dflt) == type(eval(key))
950                         continue
951                 elseif type(dflt) == type(0)
952                         let cmd = printf('let %s = %d', key, dflt)
953                 elseif type(dflt) == type('')
954                         let cmd = printf('let %s = ''%s''', key, dflt)
955                 " FIXME: not sure why this didn't work when dflt is an array
956                 "elseif type(dflt) == type([])
957                 "        let cmd = printf('let %s = %s', key, string(dflt))
958                 else
959                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
960                                                 \ a:force, key, string(dflt))
961                         continue
962                 endif
963                 exec cmd
964         endfor
965 endfunction
966 call NM_set_defaults(0)
967
968 " for some reason NM_set_defaults() didn't work for arrays...
969 if !exists('g:notmuch_show_headers')
970         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
971 endif
972 if !exists('g:notmuch_initial_search_words')
973         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
974 endif
975 if !exists('g:notmuch_folders')
976         let g:notmuch_folders = s:notmuch_folders_defaults
977 endif
978
979
980 " --- assign keymaps {{{1
981
982 function! s:NM_set_map(maps)
983         nmapclear
984         for [key, code] in items(a:maps)
985                 exec printf('nnoremap <buffer> %s %s', key, code)
986         endfor
987         " --- this is a hack for development :)
988         nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
989 endfunction
990
991 " --- command handler {{{1
992
993 function! NotMuch(args)
994         let args = a:args
995         if !strlen(args)
996                 let args = 'folders'
997         endif
998
999         let words = split(args)
1000         if words[0] == 'folders'
1001                 let words = words[1:]
1002                 call <SID>NM_cmd_folders(words)
1003
1004         elseif words[0] == 'search'
1005                 if len(words) > 1
1006                         let words = words[1:]
1007                 elseif exists('b:nm_search_words')
1008                         let words = b:nm_search_words
1009                 else
1010                         let words = g:notmuch_initial_search_words
1011                 endif
1012                 call <SID>NM_cmd_search(words)
1013
1014         elseif words[0] == 'show'
1015                 echoe 'show is not yet implemented.'
1016         endif
1017 endfunction
1018 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1019         return []
1020 endfunction
1021
1022
1023 " --- glue {{{1
1024
1025 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1026 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1027
1028 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :