]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
vim: add support for :NotMuch compose
[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         \ 'g:notmuch_compose_temp_file_dir':         '~/.notmuch/compose/'        ,
57         \ }
58
59 " defaults for g:notmuch_initial_search_words
60 " override with: let g:notmuch_initial_search_words = [ ... ]
61 let s:notmuch_initial_search_words_defaults = [
62         \ 'tag:inbox and tag:unread',
63         \ ]
64
65 " defaults for g:notmuch_show_headers
66 " override with: let g:notmuch_show_headers = [ ... ]
67 let s:notmuch_show_headers_defaults = [
68         \ 'Subject',
69         \ 'To',
70         \ 'Cc',
71         \ 'Bcc',
72         \ 'Date',
73         \ ]
74
75 " defaults for g:notmuch_folders
76 " override with: let g:notmuch_folders = [ ... ]
77 let s:notmuch_folders_defaults = [
78         \ [ 'new',    'tag:inbox and tag:unread' ],
79         \ [ 'inbox',  'tag:inbox'                ],
80         \ [ 'unread', 'tag:unread'               ],
81         \ ]
82
83 " defaults for g:notmuch_signature
84 " override with: let g:notmuch_signature = [ ... ]
85 let s:notmuch_signature_defaults = [
86         \ '',
87         \ '-- ',
88         \ 'email sent from notmuch.vim plugin'
89         \ ]
90
91 " defaults for g:notmuch_compose_headers
92 " override with: let g:notmuch_compose_headers = [ ... ]
93 let s:notmuch_compose_headers_defaults = [
94         \ 'From',
95         \ 'To',
96         \ 'Cc',
97         \ 'Bcc',
98         \ 'Subject'
99         \ ]
100
101 " --- keyboard mapping definitions {{{1
102
103 " --- --- bindings for folders mode {{{2
104
105 let g:notmuch_folders_maps = {
106         \ 's':          ':call <SID>NM_search_prompt()<CR>',
107         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
108         \ '=':          ':call <SID>NM_folders_refresh_view()<CR>',
109         \ '<Enter>':    ':call <SID>NM_folders_show_search()<CR>',
110         \ }
111
112 " --- --- bindings for search screen {{{2
113 let g:notmuch_search_maps = {
114         \ '<Enter>':    ':call <SID>NM_search_show_thread()<CR>',
115         \ '<C-]>':      ':call <SID>NM_search_expand(''<cword>'')<CR>',
116         \ 'a':          ':call <SID>NM_search_archive_thread()<CR>',
117         \ 'f':          ':call <SID>NM_search_filter()<CR>',
118         \ 'm':          ':call <SID>NM_new_mail()<CR>',
119         \ 'o':          ':call <SID>NM_search_toggle_order()<CR>',
120         \ 'r':          ':call <SID>NM_search_reply_to_thread()<CR>',
121         \ 's':          ':call <SID>NM_search_prompt()<CR>',
122         \ ',s':         ':call <SID>NM_search_edit()<CR>',
123         \ 't':          ':call <SID>NM_search_filter_by_tag()<CR>',
124         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
125         \ '+':          ':call <SID>NM_search_add_tags([])<CR>',
126         \ '-':          ':call <SID>NM_search_remove_tags([])<CR>',
127         \ '=':          ':call <SID>NM_search_refresh_view()<CR>',
128         \ '?':          ':echo <SID>NM_search_thread_id()<CR>',
129         \ }
130
131 " --- --- bindings for show screen {{{2
132 let g:notmuch_show_maps = {
133         \ '<C-P>':      ':call <SID>NM_show_previous(1, 0)<CR>',
134         \ '<C-N>':      ':call <SID>NM_show_next(1, 0)<CR>',
135         \ '<C-]>':      ':call <SID>NM_search_expand(''<cword>'')<CR>',
136         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
137         \
138         \ 'b':          ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
139         \ 'c':          ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
140         \ 'h':          ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
141         \ 's':          ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
142         \
143         \ 'a':          ':call <SID>NM_show_archive_thread()<CR>',
144         \ 'A':          ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
145         \ 'N':          ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
146         \ 'v':          ':call <SID>NM_show_view_all_mime_parts()<CR>',
147         \ '+':          ':call <SID>NM_show_add_tag()<CR>',
148         \ '-':          ':call <SID>NM_show_remove_tag()<CR>',
149         \ '<Space>':    ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
150         \ '\|':         ':call <SID>NM_show_pipe_message()<CR>',
151         \
152         \ '<S-Tab>':    ':call <SID>NM_show_previous_fold()<CR>',
153         \ '<Tab>':      ':call <SID>NM_show_next_fold()<CR>',
154         \ '<Enter>':    ':call <SID>NM_show_toggle_fold()<CR>',
155         \
156         \ 'r':          ':call <SID>NM_show_reply()<CR>',
157         \ 'm':          ':call <SID>NM_new_mail()<CR>',
158         \ '?':          ':echo <SID>NM_show_message_id() . ''  @ '' . join(<SID>NM_show_search_words())<CR>',
159         \ }
160
161
162 " --- implement folders screen {{{1
163
164 function! s:NM_cmd_folders(words)
165         if len(a:words)
166                 echoe 'Not exapecting any arguments for folders command.'
167         endif
168         let cmd = ['count']
169         let disp = []
170         let searches = []
171         for entry in g:notmuch_folders
172                 let [ name, search ] = entry
173                 let data = s:NM_run(cmd + [search])
174                 let cnt = matchlist(data, '\(\d\+\)')[1]
175                 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
176                 call add(searches, search)
177         endfor
178
179         call <SID>NM_newBuffer('folders', join(disp, "\n"))
180         let b:nm_searches = searches
181         let b:nm_timestamp = reltime()
182
183         call <SID>NM_cmd_folders_mksyntax()
184         call <SID>NM_set_map('n', g:notmuch_folders_maps)
185         setlocal cursorline
186         setlocal nowrap
187 endfunction
188
189 function! s:NM_cmd_folders_mksyntax()
190 endfunction
191
192 " --- --- folders screen action functions {{{2
193
194 function! s:NM_folders_refresh_view()
195         let lno = line('.')
196         setlocal bufhidden=delete
197         call s:NM_cmd_folders([])
198         exec printf('norm %dG', lno)
199 endfunction
200
201 function! s:NM_folders_show_search()
202         let line = line('.')
203         let search = b:nm_searches[line-1]
204
205         let prev_bufnr = bufnr('%')
206         setlocal bufhidden=hide
207         call <SID>NM_cmd_search([search])
208         setlocal bufhidden=delete
209         let b:nm_prev_bufnr = prev_bufnr
210 endfunction
211
212
213 " --- implement search screen {{{1
214
215 function! s:NM_cmd_search(words)
216         let cmd = ['search']
217         if g:notmuch_search_newest_first
218                 let cmd = cmd + ['--sort=newest-first']
219         else
220                 let cmd = cmd + ['--sort=oldest-first']
221         endif
222         let data = s:NM_run(cmd + a:words)
223         let lines = split(data, "\n")
224         let disp = copy(lines)
225         call map(disp, 's:NM_cmd_search_fmtline(v:val)')
226
227         call <SID>NM_newBuffer('search', join(disp, "\n"))
228         let b:nm_raw_lines = lines
229         let b:nm_search_words = a:words
230
231         call <SID>NM_cmd_search_mksyntax()
232         call <SID>NM_set_map('n', g:notmuch_search_maps)
233         setlocal cursorline
234         setlocal nowrap
235 endfunction
236 function! s:NM_cmd_search_fmtline(line)
237         let m = matchlist(a:line, '^\(thread:\S\+\)\s\([^]]\+\]\) \([^;]\+\); \(.*\) (\([^(]*\))$')
238         if !len(m)
239                 return 'ERROR PARSING: ' . a:line
240         endif
241         let max = g:notmuch_search_from_column_width
242         let from = m[3]
243         if strlen(from) >= max
244                 let from = substitute(m[3][0:max-4], '[^A-Za-z1-9_]*$', '', '') . '...'
245         endif
246         return printf('%-20s %-20s | %s (%s)', m[2], from, m[4], m[5])
247 endfunction
248 function! s:NM_cmd_search_mksyntax()
249         syntax clear nmSearchFrom
250         exec printf('syntax match nmSearchFrom /\(\] \)\@<=.\{%d\}/ oneline contained', g:notmuch_search_from_column_width)
251 endfunction
252
253 " --- --- search screen action functions {{{2
254
255 function! s:NM_search_show_thread()
256         let id = <SID>NM_search_thread_id()
257         if id != ''
258                 let words = [id]
259                 if exists('b:nm_search_words')
260                         let words = ['('] + b:nm_search_words + [')', 'and', id]
261                 endif
262                 if len(words)
263                         call <SID>NM_cmd_show(words)
264                 endif
265         endif
266 endfunction
267
268 function! s:NM_search_prompt()
269         " TODO: input() can support completion
270         let text = input('NotMuch Search: ')
271         if strlen(text)
272                 let tags = split(text)
273         else
274                 let tags = s:notmuch_initial_search_words_defaults
275         endif
276         let prev_bufnr = bufnr('%')
277         if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
278                 " TODO: we intend to replace the current buffer,
279                 "       ... maybe we could just clear it
280                 let prev_bufnr = b:nm_prev_bufnr
281                 setlocal bufhidden=delete
282         else
283                 setlocal bufhidden=hide
284         endif
285         call <SID>NM_cmd_search(tags)
286         setlocal bufhidden=delete
287         let b:nm_prev_bufnr = prev_bufnr
288 endfunction
289
290 function! s:NM_search_edit()
291         " TODO: input() can support completion
292         let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
293         if strlen(text)
294                 call <SID>NM_cmd_search(split(text))
295         endif
296 endfunction
297
298 function! s:NM_search_archive_thread()
299         call <SID>NM_add_remove_tags_on_screen('', '-', ['inbox'])
300         call <SID>NM_add_remove_tags([], '-', ['inbox'])
301         norm j
302 endfunction
303
304 function! s:NM_search_filter()
305         call <SID>NM_search_filter_helper('Filter: ', '', '')
306 endfunction
307
308 function! s:NM_search_filter_by_tag()
309         call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
310 endfunction
311
312 function! s:NM_search_filter_helper(prompt, prefix, joiner)
313         " TODO: input() can support completion
314         let text = input(a:prompt)
315         if !strlen(text)
316                 return
317         endif
318
319         let tags = split(text)
320         if strlen(a:prefix)
321                 call map(tags, 'a:prefix . v:val')
322         endif
323         if strlen(a:joiner)
324                 let idx = len(tags) - 1
325                 while idx > 0
326                         call insert(tags, a:joiner, idx)
327                         let idx = idx - 1
328                 endwhile
329         endif
330         let tags = b:nm_search_words + ['and', '('] + tags + [')']
331
332         let prev_bufnr = bufnr('%')
333         setlocal bufhidden=hide
334         call <SID>NM_cmd_search(tags)
335         setlocal bufhidden=delete
336         let b:nm_prev_bufnr = prev_bufnr
337 endfunction
338
339 function! s:NM_search_toggle_order()
340         let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
341         " FIXME: maybe this would be better done w/o reading re-reading the lines
342         "         reversing the b:nm_raw_lines and the buffer lines would be better
343         call <SID>NM_search_refresh_view()
344 endfunction
345
346 function! s:NM_search_reply_to_thread()
347         echo 'not implemented'
348 endfunction
349
350 function! s:NM_search_add_tags(tags)
351         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
352 endfunction
353
354 function! s:NM_search_remove_tags(tags)
355         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
356 endfunction
357
358 function! s:NM_search_refresh_view()
359         let lno = line('.')
360         let prev_bufnr = b:nm_prev_bufnr
361         setlocal bufhidden=delete
362         call <SID>NM_cmd_search(b:nm_search_words)
363         let b:nm_prev_bufnr = prev_bufnr
364         " FIXME: should find the line of the thread we were on if possible
365         exec printf('norm %dG', lno)
366 endfunction
367
368 " --- --- search screen helper functions {{{2
369
370 function! s:NM_search_thread_id()
371         if !exists('b:nm_raw_lines')
372                 echoe 'no b:nm_raw_lines'
373                 return ''
374         endif
375         let mnum = line('.') - 1
376         if len(b:nm_raw_lines) <= mnum
377                 return ''
378         endif
379         echo 'len=' . string(len(b:nm_raw_lines)) . '  mnum=' . string(mnum)
380         let info = b:nm_raw_lines[mnum]
381         let what = split(info, '\s\+')[0]
382         return what
383 endfunction
384
385 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
386         if type(a:intags) != type([]) || len(a:intags) == 0
387                 " TODO: input() can support completion
388                 let text = input(a:prompt)
389                 if !strlen(text)
390                         return
391                 endif
392                 let tags = split(text, ' ')
393         else
394                 let tags = a:intags
395         endif
396         call <SID>NM_add_remove_tags([], a:prefix, tags)
397         call <SID>NM_add_remove_tags_on_screen('', a:prefix, tags)
398 endfunction
399
400 " --- implement show screen {{{1
401
402 function! s:NM_cmd_show(words)
403         let prev_bufnr = bufnr('%')
404         let data = s:NM_run(['show'] + a:words)
405         let lines = split(data, "\n")
406
407         let info = s:NM_cmd_show_parse(lines)
408
409         setlocal bufhidden=hide
410         call <SID>NM_newBuffer('show', join(info['disp'], "\n"))
411         setlocal bufhidden=delete
412         let b:nm_words = a:words
413         let b:nm_raw_info = info
414         let b:nm_prev_bufnr = prev_bufnr
415
416         call <SID>NM_cmd_show_mkfolds()
417         call <SID>NM_cmd_show_mksyntax()
418         call <SID>NM_set_map('n', g:notmuch_show_maps)
419         setlocal foldtext=NM_cmd_show_foldtext()
420         setlocal fillchars=
421         setlocal foldcolumn=6
422
423 endfunction
424
425 function! s:NM_show_previous(can_change_thread, find_matching)
426         let info = b:nm_raw_info
427         let lnum = line('.')
428         for msg in reverse(copy(info['msgs']))
429                 if a:find_matching && msg['match'] == '0'
430                         continue
431                 endif
432                 if lnum <= msg['start']
433                         continue
434                 endif
435
436                 exec printf('norm %dGzt', msg['start'])
437                 " TODO: try to fit the message on screen
438                 return
439         endfor
440         if !a:can_change_thread
441                 return
442         endif
443         call <SID>NM_kill_this_buffer()
444         if line('.') > 1
445                 norm k
446                 call <SID>NM_search_show_thread()
447                 norm G
448                 call <SID>NM_show_previous(0, a:find_matching)
449         else
450                 echo 'No more messages.'
451         endif
452 endfunction
453
454 function! s:NM_show_next(can_change_thread, find_matching)
455         let info = b:nm_raw_info
456         let lnum = line('.')
457         for msg in info['msgs']
458                 if a:find_matching && msg['match'] == '0'
459                         continue
460                 endif
461                 if lnum >= msg['start']
462                         continue
463                 endif
464
465                 exec printf('norm %dGzt', msg['start'])
466                 " TODO: try to fit the message on screen
467                 return
468         endfor
469         if a:can_change_thread
470                 call <SID>NM_show_next_thread()
471         endif
472 endfunction
473
474 function! s:NM_show_next_thread()
475         call <SID>NM_kill_this_buffer()
476         if line('.') != line('$')
477                 norm j
478                 call <SID>NM_search_show_thread()
479         else
480                 echo 'No more messages.'
481         endif
482 endfunction
483
484 function! s:NM_show_archive_thread()
485         echo 'not implemented'
486 endfunction
487
488 function! s:NM_show_mark_read_then_archive_thread()
489         echo 'not implemented'
490 endfunction
491
492 function! s:NM_show_mark_read_then_next_open_message()
493         echo 'not implemented'
494 endfunction
495
496 function! s:NM_show_previous_message()
497         echo 'not implemented'
498 endfunction
499
500 function! s:NM_show_reply()
501         echo 'not implemented'
502 endfunction
503
504 function! s:NM_show_view_all_mime_parts()
505         echo 'not implemented'
506 endfunction
507
508 function! s:NM_show_view_raw_message()
509         echo 'not implemented'
510 endfunction
511
512 function! s:NM_show_add_tag()
513         echo 'not implemented'
514 endfunction
515
516 function! s:NM_show_remove_tag()
517         echo 'not implemented'
518 endfunction
519
520 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
521 " otherwise go to next message
522 " any message that is viewed entirely has inbox and unread tags removed
523 function! s:NM_show_advance_marking_read_and_archiving()
524         let advance_tags = ['unread', 'inbox']
525
526         let vis_top = line('w0')
527         let vis_bot = line('w$')
528
529         let msg_top = <SID>NM_show_get_message_for_line(vis_top)
530         if !has_key(msg_top,'id')
531                 echo "No top visible message."
532         endif
533
534         " if the top message is the last message, just expunge the entire thread and move on
535         if msg_top['end'] == line('$')
536                 let ids = []
537                 for msg in b:nm_raw_info['msgs']
538                         if has_key(msg,'match') && msg['match'] != '0'
539                                 if len(ids)
540                                         call add(ids, 'OR')
541                                 endif
542                                 call add(ids, msg['id'])
543                         endif
544                 endfor
545
546                 let filter = ['('] + advance_tags + [')', 'AND', '('] + ids + [')']
547                 call <SID>NM_add_remove_tags(filter, '-', advance_tags)
548                 call <SID>NM_show_next(1, 1)
549                 return
550         endif
551
552         let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
553         if !has_key(msg_bot,'id')
554                 echo "No bottom visible message."
555         endif
556
557         " if entire message fits on the screen, read/archive it, move to the next one
558         if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
559                 call <SID>NM_add_remove_tags_on_screen(msg_top['start'], '-', advance_tags)
560                 exec printf('norm %dG', vis_top)
561                 call <SID>NM_show_next(0, 1)
562                 if has_key(msg_top,'match') && msg_top['match'] != '0'
563                         redraw
564                         " do this last to hide the latency
565                         let filter = ['('] + advance_tags + [')', 'AND', msg_top['id']]
566                         call <SID>NM_add_remove_tags(filter, '-', advance_tags)
567                 endif
568                 return
569         endif
570
571         " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
572         let jmp = winheight(winnr()) / 2
573         let max = msg_bot['end'] - vis_bot
574         if jmp > max
575                 let jmp = max
576         endif
577         exec printf('norm %dGzt', vis_top + jmp)
578         return
579 endfunction
580
581 function! s:NM_show_pipe_message()
582         echo 'not implemented'
583 endfunction
584
585 function! s:NM_show_previous_fold()
586         echo 'not implemented'
587 endfunction
588
589 function! s:NM_show_next_fold()
590         echo 'not implemented'
591 endfunction
592
593 function! s:NM_show_toggle_fold()
594         echo 'not implemented'
595 endfunction
596
597
598 " --- --- show screen helper functions {{{2
599
600 function! s:NM_show_get_message_for_line(line)
601         for msg in b:nm_raw_info['msgs']
602                 if a:line > msg['end']
603                         continue
604                 endif
605                 return msg
606         endfor
607         return {}
608 endfunction
609
610 function! s:NM_show_message_id()
611         if !exists('b:nm_raw_info')
612                 echoe 'no b:nm_raw_info'
613                 return ''
614         endif
615         let msg = <SID>NM_show_get_message_for_line(line('.'))
616         if has_key(msg,'id')
617                 return msg['id']
618         endif
619         return ''
620 endfunction
621
622 function! s:NM_show_search_words()
623         if !exists('b:nm_words')
624                 echoe 'no b:nm_words'
625                 return []
626         endif
627         return b:nm_words
628 endfunction
629
630 function! s:NM_show_fold_toggle(key, type, fold)
631         let info = b:nm_raw_info
632         let act = 'open'
633         if a:fold
634                 let act = 'close'
635         endif
636         for fld in info['folds']
637                 if fld[0] == a:type
638                         exec printf('%dfold%s', fld[1], act)
639                 endif
640         endfor
641         exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
642 endfunction
643
644
645 " s:NM_cmd_show_parse returns the following dictionary:
646 "    'disp':     lines to display
647 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
648 "    'folds':    fold info arrays [ type, start, end ]
649 "    'foldtext': fold text indexed by start line
650 function! s:NM_cmd_show_parse(inlines)
651         let info = { 'disp': [],       
652                    \ 'msgs': [],       
653                    \ 'folds': [],      
654                    \ 'foldtext': {} }  
655         let msg = {}
656         let hdr = {}
657
658         let in_message = 0
659         let in_header = 0
660         let in_body = 0
661         let in_part = ''
662
663         let body_start = -1
664         let part_start = -1
665
666         let mode_type = ''
667         let mode_start = -1
668
669         let inlnum = 0
670         for line in a:inlines
671                 let inlnum = inlnum + 1
672                 let foldinfo = []
673
674                 if strlen(in_part)
675                         let part_end = 0
676
677                         if match(line, g:notmuch_show_part_end_regexp) != -1
678                                 let part_end = len(info['disp'])
679                         else
680                                 call add(info['disp'], line)
681                         endif
682
683                         if in_part == 'text/plain'
684                                 if !part_end && mode_type == ''
685                                         if match(line, g:notmuch_show_signature_regexp) != -1
686                                                 let mode_type = 'sig'
687                                                 let mode_start = len(info['disp'])
688                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
689                                                 let mode_type = 'cit'
690                                                 let mode_start = len(info['disp'])
691                                         endif
692                                 elseif mode_type == 'cit'
693                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
694                                                 let outlnum = len(info['disp'])
695                                                 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
696                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
697                                                 let mode_type = ''
698                                         endif
699                                 elseif mode_type == 'sig'
700                                         let outlnum = len(info['disp'])
701                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
702                                                 let mode_type = ''
703                                         elseif part_end
704                                                 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
705                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
706                                                 let mode_type = ''
707                                         endif
708                                 endif
709                         endif
710
711                         if part_end
712                                 " FIXME: this is a hack for handling two folds being added for one line
713                                 "         we should handle addinga fold in a function
714                                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
715                                         call add(info['folds'], foldinfo[0:3])
716                                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
717                                 endif
718
719                                 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
720                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
721                                 let in_part = ''
722                                 call add(info['disp'], '')
723                         endif
724
725                 elseif in_body
726                         if !has_key(msg,'body_start')
727                                 let msg['body_start'] = len(info['disp']) + 1
728                         endif
729                         if match(line, g:notmuch_show_body_end_regexp) != -1
730                                 let body_end = len(info['disp'])
731                                 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
732                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
733
734                                 let in_body = 0
735
736                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
737                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
738                                 let in_part = 'unknown'
739                                 if len(m)
740                                         let in_part = m[2]
741                                 endif
742                                 call add(info['disp'],
743                                          \ printf('--- %s ---', in_part))
744                                 let part_start = len(info['disp']) + 1
745                         endif
746
747                 elseif in_header
748                         if in_header == 1
749                                 let msg['descr'] = line
750                                 call add(info['disp'], line)
751                                 let in_header = 2
752                                 let msg['hdr_start'] = len(info['disp']) + 1
753
754                         else
755                                 if match(line, g:notmuch_show_header_end_regexp) != -1
756                                         let hdr_start = msg['hdr_start']+1
757                                         let hdr_end = len(info['disp'])
758                                         let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
759                                                \ printf('[ %d-line headers.  Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
760                                         let msg['header'] = hdr
761                                         let in_header = 0
762                                         let hdr = {}
763                                 else
764                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
765                                         if len(m)
766                                                 let hdr[m[1]] = m[2]
767                                                 if match(g:notmuch_show_headers, m[1]) != -1
768                                                         call add(info['disp'], line)
769                                                 endif
770                                         endif
771                                 endif
772                         endif
773
774                 elseif in_message
775                         if match(line, g:notmuch_show_message_end_regexp) != -1
776                                 let msg['end'] = len(info['disp'])
777                                 call add(info['disp'], '')
778
779                                 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
780                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
781
782                                 call add(info['msgs'], msg)
783                                 let msg = {}
784                                 let in_message = 0
785                                 let in_header = 0
786                                 let in_body = 0
787                                 let in_part = ''
788
789                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
790                                 let in_header = 1
791                                 continue
792
793                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
794                                 let body_start = len(info['disp']) + 1
795                                 let in_body = 1
796                                 continue
797                         endif
798
799                 else
800                         if match(line, g:notmuch_show_message_begin_regexp) != -1
801                                 let msg['start'] = len(info['disp']) + 1
802
803                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
804                                 if len(m)
805                                         let msg['id'] = m[1]
806                                         let msg['depth'] = m[2]
807                                         let msg['match'] = m[3]
808                                         let msg['filename'] = m[4]
809                                 endif
810
811                                 let in_message = 1
812                         endif
813                 endif
814
815                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
816                         call add(info['folds'], foldinfo[0:3])
817                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
818                 endif
819         endfor
820         return info
821 endfunction
822
823 function! s:NM_cmd_show_mkfolds()
824         let info = b:nm_raw_info
825
826         for afold in info['folds']
827                 exec printf('%d,%dfold', afold[1], afold[2])
828                 let state = 'open'
829                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
830                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
831                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
832                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
833                         let state = 'close'
834                 elseif afold[0] == 'msg'
835                         let idx = afold[3]
836                         let msg = info['msgs'][idx]
837                         if has_key(msg,'match') && msg['match'] == '0'
838                                 let state = 'close'
839                         endif
840                 endif
841                 exec printf('%dfold%s', afold[1], state)
842         endfor
843 endfunction
844
845 function! s:NM_cmd_show_mksyntax()
846         let info = b:nm_raw_info
847         let cnt = 0
848         for msg in info['msgs']
849                 let cnt = cnt + 1
850                 let start = msg['start']
851                 let hdr_start = msg['hdr_start']
852                 let body_start = msg['body_start']
853                 let end = msg['end']
854                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
855                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
856                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
857         endfor
858 endfunction
859
860 function! NM_cmd_show_foldtext()
861         let foldtext = b:nm_raw_info['foldtext']
862         return foldtext[v:foldstart]
863 endfunction
864
865
866 " --- implement compose screen {{{1
867
868 function! s:NM_cmd_compose(words, body_lines)
869         let lines = []
870         let start_on_line = 0
871
872         let hdrs = { }
873         for word in a:words
874                 let m = matchlist(word, '^\([^:]\+\):\s*\(.*\)\s*$')
875                 if !len(m)
876                         throw 'Eeek! bad parameter ''' . string(word) . ''''
877                 endif
878                 let key = substitute(m[1], '\<\w', '\U&', 'g')
879                 if !has_key(hdrs, key)
880                         let hdrs[key] = []
881                 endif
882                 if strlen(m[2])
883                         call add(hdrs[key], m[2])
884                 endif
885         endfor
886
887         if !has_key(hdrs, 'From') || !len(hdrs['From'])
888                 let me = <SID>NM_compose_get_user_email()
889                 let hdrs['From'] = [ me ]
890         endif
891
892         for key in g:notmuch_compose_headers
893                 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
894                 call add(lines, key . ': ' . text)
895                 if !start_on_line && !strlen(text)
896                         let start_on_line = len(lines)
897                 endif
898         endfor
899
900         for [key,val] in items(hdrs)
901                 if match(g:notmuch_compose_headers, key) == -1
902                         let line = key . ': ' . join(val, ', ')
903                         call add(lines, line)
904                 endif
905         endfor
906
907         call extend(lines, [ '', '' ])
908         if !start_on_line
909                 let start_on_line = len(lines) + 1
910         endif
911
912         if len(a:body_lines)
913                 call extend(lines, a:body_lines)
914         else
915                 call add(lines, '')
916         endif
917         call extend(lines, g:notmuch_signature)
918
919         let prev_bufnr = bufnr('%')
920         setlocal bufhidden=hide
921         call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
922                                   \ 'compose', lines)
923         setlocal bufhidden=hide
924
925         call <SID>NM_cmd_compose_mksyntax()
926         call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
927         call <SID>NM_set_map('i', g:notmuch_compose_imaps)
928
929         exec printf('norm %dG', start_on_line)
930         startinsert!
931         echo 'Type your message, use <TAB> to jump to next header and then body.'
932 endfunction
933 function! s:NM_cmd_compose_mksyntax()
934         silent! setlocal syntax=mail
935 endfunction
936
937 function! s:NM_compose_send()
938         echo 'not implemented'
939 endfunction
940
941 " --- --- compose screen helper functions {{{2
942
943 function! s:NM_compose_get_user_email()
944         let name = substitute(system('id -u -n'), '\v(^\s*|\s*$|\n)', '', 'g')
945         let fqdn = substitute(system('hostname -f'), '\v(^\s*|\s*$|\n)', '', 'g')
946
947         " TODO: do this properly
948         return name . '@' . fqdn
949 endfunction
950
951
952 " --- notmuch helper functions {{{1
953
954 function! s:NM_newBuffer(type, content)
955         enew
956         setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
957         silent put=a:content
958         keepjumps 0d
959         setlocal nomodifiable
960         execute printf('set filetype=notmuch-%s', a:type)
961         execute printf('set syntax=notmuch-%s', a:type)
962         let b:nm_type = a:type
963 endfunction
964
965 function! s:NM_newFileBuffer(fdir, fname, type, lines)
966         let fdir = expand(a:fdir)
967         if !isdirectory(fdir)
968                 call mkdir(fdir, 'p')
969         endif
970         let file_name = <SID>NM_mktemp(fdir, a:fname)
971         if writefile(a:lines, file_name)
972                 throw 'Eeek! couldn''t write to temporary file ' . file_name
973         endif
974         exec printf('edit %s', file_name)
975         setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
976         execute printf('set filetype=notmuch-%s', a:type)
977         execute printf('set syntax=notmuch-%s', a:type)
978         let b:nm_type = a:type
979 endfunction
980
981 function! s:NM_mktemp(dir, name)
982         let time_stamp = strftime('%Y%m%d-%H%M%S')
983         let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
984         " TODO: check if it exists, try again
985         return file_name
986 endfunction
987
988 function! s:NM_shell_escape(word)
989         " TODO: use shellescape()
990         let word = substitute(a:word, '''', '\\''', 'g')
991         return '''' . word . ''''
992 endfunction
993
994 " this function was taken from git.vim, then fixed up
995 " http://github.com/motemen/git-vim
996 function! s:NM_shell_split(cmd)
997         let l:split_cmd = []
998         let cmd = a:cmd
999         let iStart = 0
1000         while 1
1001                 let t = match(cmd, '\S', iStart)
1002                 if t < iStart
1003                         break
1004                 endif
1005                 let iStart = t
1006
1007                 let iSpace = match(cmd, '\v(\s|$)', iStart)
1008                 if iSpace < iStart
1009                         break
1010                 endif
1011
1012                 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1013                 if iQuote1 > iSpace || iQuote1 < iStart
1014                         let iEnd = iSpace - 1
1015                         let l:split_cmd += [ cmd[iStart : iEnd] ]
1016                 else
1017                         let q = cmd[iQuote1]
1018                         let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1019                         if iQuote2 < iQuote1
1020                                 throw 'No matching ' . q . ' quote'
1021                         endif
1022                         let iEnd = iQuote2
1023                         let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1024                 endif
1025
1026
1027                 let iStart = iEnd + 1
1028         endwhile
1029
1030         return l:split_cmd
1031 endfunction
1032
1033
1034 function! s:NM_run(args)
1035         let words = a:args
1036         call map(words, 's:NM_shell_escape(v:val)')
1037         let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1038
1039         let start = reltime()
1040         let out = system(cmd)
1041         let err = v:shell_error
1042         let delta = reltime(start)
1043
1044         if exists('g:notmuch_debug') && g:notmuch_debug
1045                 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1046         endif
1047
1048         if err
1049                 echohl Error
1050                 echo substitute(out, '\n*$', '', '')
1051                 echohl None
1052                 return ''
1053         else
1054                 return out
1055         endif
1056 endfunction
1057
1058 " --- external mail handling helpers {{{1
1059
1060 function! s:NM_new_mail()
1061         echo 'not implemented'
1062 endfunction
1063
1064 " --- other helpers {{{1
1065
1066 function! s:NM_kill_this_buffer()
1067         if exists('b:nm_prev_bufnr')
1068                 setlocal bufhidden=delete
1069                 exec printf(":buffer %d", b:nm_prev_bufnr)
1070         else
1071                 echo "This is the last buffer; use :q<CR> to quit."
1072         endif
1073 endfunction
1074
1075 function! s:NM_search_expand(arg)
1076         let word = expand(a:arg)
1077         let prev_bufnr = bufnr('%')
1078         setlocal bufhidden=hide
1079         call <SID>NM_cmd_search([word])
1080         setlocal bufhidden=delete
1081         let b:nm_prev_bufnr = prev_bufnr
1082 endfunction
1083
1084 function! s:NM_add_remove_tags(filter, prefix, tags)
1085         let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1086         if !len(filter)
1087                 echoe 'Eeek! I couldn''t find the thead id!'
1088         endif
1089         call map(a:tags, 'a:prefix . v:val')
1090         let args = ['tag']
1091         call extend(args, a:tags)
1092         call add(args, '--')
1093         call extend(args, filter)
1094         " TODO: handle errors
1095         call <SID>NM_run(args)
1096 endfunction
1097
1098 function! s:NM_add_remove_tags_on_screen(online, prefix, tags)
1099         setlocal modifiable
1100         if a:prefix == '-'
1101                 for tagname in a:tags
1102                         exec printf('silent! %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', string(a:online), tagname)
1103                 endfor
1104         else
1105                 for tagname in a:tags
1106                         exec printf('silent! %ss/(\([^)]*\)\([^)]*\))$/(\1 %s)/', string(a:online), tagname)
1107                 endfor
1108         endif
1109         setlocal nomodifiable
1110 endfunction
1111
1112 " --- process and set the defaults {{{1
1113
1114 function! NM_set_defaults(force)
1115         for [key, dflt] in items(s:notmuch_defaults)
1116                 let cmd = ''
1117                 if !a:force && exists(key) && type(dflt) == type(eval(key))
1118                         continue
1119                 elseif type(dflt) == type(0)
1120                         let cmd = printf('let %s = %d', key, dflt)
1121                 elseif type(dflt) == type('')
1122                         let cmd = printf('let %s = ''%s''', key, dflt)
1123                 " FIXME: not sure why this didn't work when dflt is an array
1124                 "elseif type(dflt) == type([])
1125                 "        let cmd = printf('let %s = %s', key, string(dflt))
1126                 else
1127                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1128                                                 \ a:force, key, string(dflt))
1129                         continue
1130                 endif
1131                 exec cmd
1132         endfor
1133 endfunction
1134 call NM_set_defaults(0)
1135
1136 " for some reason NM_set_defaults() didn't work for arrays...
1137 if !exists('g:notmuch_show_headers')
1138         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1139 endif
1140 if !exists('g:notmuch_initial_search_words')
1141         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1142 endif
1143 if !exists('g:notmuch_folders')
1144         let g:notmuch_folders = s:notmuch_folders_defaults
1145 endif
1146
1147 if !exists('g:notmuch_signature')
1148         let g:notmuch_signature = s:notmuch_signature_defaults
1149 endif
1150 if !exists('g:notmuch_compose_headers')
1151         let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1152 endif
1153
1154 " --- assign keymaps {{{1
1155
1156 function! s:NM_set_map(type, maps)
1157         nmapclear
1158         for [key, code] in items(a:maps)
1159                 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1160         endfor
1161         " --- this is a hack for development :)
1162         nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
1163 endfunction
1164
1165 " --- command handler {{{1
1166
1167 function! NotMuch(args)
1168         let args = a:args
1169         if !strlen(args)
1170                 let args = 'folders'
1171         endif
1172
1173         let words = <SID>NM_shell_split(args)
1174         if words[0] == 'folders' || words[0] == 'f'
1175                 let words = words[1:]
1176                 call <SID>NM_cmd_folders(words)
1177
1178         elseif words[0] == 'search' || words[0] == 's'
1179                 if len(words) > 1
1180                         let words = words[1:]
1181                 elseif exists('b:nm_search_words')
1182                         let words = b:nm_search_words
1183                 else
1184                         let words = g:notmuch_initial_search_words
1185                 endif
1186                 call <SID>NM_cmd_search(words)
1187
1188         elseif words[0] == 'show'
1189                 echoe 'show is not yet implemented.'
1190
1191         elseif words[0] == 'new' || words[0] == 'compose'
1192                 let words = words[1:]
1193                 call <SID>NM_cmd_compose(words, [])
1194         endif
1195 endfunction
1196 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1197         return []
1198 endfunction
1199
1200
1201 " --- glue {{{1
1202
1203 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1204 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1205
1206 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :