]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
ed67d34a332688c3375b17732fff49347c0ab4bf
[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_search_reverse':                1                            ,
27         \ 'g:notmuch_show_fold_signatures':          1                            ,
28         \ 'g:notmuch_show_fold_citations':           1                            ,
29         \
30         \ 'g:notmuch_show_message_begin_regexp':     '^\fmessage{'                ,
31         \ 'g:notmuch_show_message_end_regexp':       '^\fmessage}'                ,
32         \ 'g:notmuch_show_header_begin_regexp':      '^\fheader{'                 ,
33         \ 'g:notmuch_show_header_end_regexp':        '^\fheader}'                 ,
34         \ 'g:notmuch_show_body_begin_regexp':        '^\fbody{'                   ,
35         \ 'g:notmuch_show_body_end_regexp':          '^\fbody}'                   ,
36         \ 'g:notmuch_show_attachment_begin_regexp':  '^\fattachment{'             ,
37         \ 'g:notmuch_show_attachment_end_regexp':    '^\fattachment}'             ,
38         \ 'g:notmuch_show_part_begin_regexp':        '^\fpart{'                   ,
39         \ 'g:notmuch_show_part_end_regexp':          '^\fpart}'                   ,
40         \ 'g:notmuch_show_marker_regexp':            '^\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
41         \
42         \ 'g:notmuch_show_message_parse_regexp':     '\(id:[^ ]*\) depth:\([0-9]*\) filename:\(.*\)$',
43         \ 'g:notmuch_show_tags_regexp':              '(\([^)]*\))$'               ,
44         \
45         \ 'g:notmuch_show_signature_regexp':         '^\(-- \?\|_\+\)$'           ,
46         \ 'g:notmuch_show_signature_lines_max':      12                           ,
47         \
48         \ 'g:notmuch_show_citation_regexp':          '^\s*>'                      ,
49         \ }
50
51 " defaults for g:notmuch_initial_search_words
52 " override with: let g:notmuch_initial_search_words = [ ... ]
53 let s:notmuch_initial_search_words_defaults = [
54         \ 'tag:inbox'
55         \ ]
56
57 " defaults for g:notmuch_show_headers
58 " override with: let g:notmuch_show_headers = [ ... ]
59 let s:notmuch_show_headers_defaults = [
60         \ 'Subject',
61         \ 'From'
62         \ ]
63
64 " --- keyboard mapping definitions {{{1
65
66 " --- --- bindings for search screen {{{2
67 let g:notmuch_search_maps = {
68         \ '<Enter>':    ':call <SID>NM_search_show_thread()<CR>',
69         \ 'a':          ':call <SID>NM_search_archive_thread()<CR>',
70         \ 'f':          ':call <SID>NM_search_filter()<CR>',
71         \ 'm':          ':call <SID>NM_new_mail()<CR>',
72         \ 'o':          ':call <SID>NM_search_toggle_order()<CR>',
73         \ 'r':          ':call <SID>NM_search_reply_to_thread()<CR>',
74         \ 's':          ':call <SID>NM_search_prompt()<CR>',
75         \ 'S':          ':call <SID>NM_search_edit()<CR>',
76         \ 't':          ':call <SID>NM_search_filter_by_tag()<CR>',
77         \ 'q':          ':call <SID>NM_kill_buffer()<CR>',
78         \ '+':          ':call <SID>NM_search_add_tags([])<CR>',
79         \ '-':          ':call <SID>NM_search_remove_tags([])<CR>',
80         \ '=':          ':call <SID>NM_search_refresh_view()<CR>',
81         \ }
82
83 " --- --- bindings for show screen {{{2
84 let g:notmuch_show_maps = {
85         \ '<C-N>':      ':call <SID>NM_cmd_show_next()<CR>',
86         \ 'c':          ':call <SID>NM_cmd_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
87         \ 's':          ':call <SID>NM_cmd_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
88         \ 'q':          ':call <SID>NM_kill_buffer()<CR>',
89         \ }
90
91 " --- implement search screen {{{1
92
93 function! s:NM_cmd_search(words)
94         let cmd = ['search']
95         if g:notmuch_search_reverse
96                 let cmd = cmd + ['--reverse']
97         endif
98         let data = s:NM_run(cmd + a:words)
99         "let data = substitute(data, '27/27', '25/27', '')
100         "let data = substitute(data, '\[4/4\]', '[0/4]', '')
101         let lines = split(data, "\n")
102         let disp = copy(lines)
103         call map(disp, 'substitute(v:val, "^thread:\\S* ", "", "")' )
104
105         call <SID>NM_newBuffer('search', join(disp, "\n"))
106         let b:nm_raw_lines = lines
107         let b:nm_search_words = a:words
108
109         call <SID>NM_set_map(g:notmuch_search_maps)
110         setlocal cursorline
111         setlocal nowrap
112 endfunction
113
114 " --- --- search screen action functions {{{2
115
116 function! s:NM_search_show_thread()
117         let id = <SID>NM_search_find_thread_id()
118         if id != ''
119                 call <SID>NM_cmd_show([id])
120         endif
121 endfunction
122
123 function! s:NM_search_prompt()
124         " TODO: input() can support completion
125         let text = input('NotMuch Search: ')
126         if strlen(text)
127                 let tags = split(text)
128         else
129                 let tags = s:notmuch_initial_search_words_defaults
130         endif
131         setlocal bufhidden=delete
132         call <SID>NM_cmd_search(tags)
133 endfunction
134
135 function! s:NM_search_edit()
136         " TODO: input() can support completion
137         let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
138         if strlen(text)
139                 call <SID>NM_cmd_search(split(text))
140         endif
141 endfunction
142
143 function! s:NM_search_archive_thread()
144         call <SID>NM_add_remove_tags('-', ['inbox'])
145         " TODO: this could be made better and more generic
146         setlocal modifiable
147         s/(\([^)]*\)\<inbox\>\([^)]*\))$/(\1\2)/
148         setlocal nomodifiable
149         norm j
150 endfunction
151
152 function! s:NM_search_filter()
153         call <SID>NM_search_filter_helper('Filter: ', '')
154 endfunction
155
156 function! s:NM_search_filter_by_tag()
157         call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:')
158 endfunction
159
160 function! s:NM_search_filter_helper(prompt, prefix)
161         " TODO: input() can support completion
162         let text = input(a:prompt)
163         if !strlen(text)
164                 return
165         endif
166
167         let tags = split(text)
168         map(tags, 'a:prefix . v:val')
169         let tags = b:nm_search_words + tags
170         echo tags
171
172         let prev_bufnr = bufnr('%')
173         setlocal bufhidden=hide
174         call <SID>NM_cmd_search(tags)
175         setlocal bufhidden=delete
176         let b:nm_prev_bufnr = prev_bufnr
177 endfunction
178
179 function! s:NM_new_mail()
180         echoe 'Not implemented'
181 endfunction
182
183 function! s:NM_search_toggle_order()
184         let g:notmuch_search_reverse = !g:notmuch_search_reverse
185         " FIXME: maybe this would be better done w/o reading re-reading the lines
186         "         reversing the b:nm_raw_lines and the buffer lines would be better
187         call <SID>NM_search_refresh_view()
188 endfunction
189
190 function! s:NM_search_reply_to_thread()
191         echoe 'Not implemented'
192 endfunction
193
194 function! s:NM_search_add_tags(tags)
195         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
196 endfunction
197
198 function! s:NM_search_remove_tags(tags)
199         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
200 endfunction
201
202 function! s:NM_search_refresh_view()
203         let lno = line('.')
204         setlocal bufhidden=delete
205         call <SID>NM_cmd_search(b:nm_search_words)
206         " FIXME: should find the line of the thread we were on if possible
207         exec printf('norm %dG', lno)
208 endfunction
209
210 " --- --- search screen helper functions {{{2
211
212 function! s:NM_search_find_thread_id()
213         if !exists('b:nm_raw_lines')
214                 echoe 'no b:nm_raw_lines'
215                 return ''
216         else
217                 let line = line('.')
218                 let info = b:nm_raw_lines[line-1]
219                 let what = split(info, '\s\+')[0]
220                 return what
221         endif
222 endfunction
223
224 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
225         if type(a:intags) != type([]) || len(a:intags) == 0
226                 " TODO: input() can support completion
227                 let text = input(a:prompt)
228                 if !strlen(text)
229                         return
230                 endif
231                 call <SID>NM_add_remove_tags(prefix, split(text, ' '))
232         else
233                 call <SID>NM_add_remove_tags(prefix, a:intags)
234         endif
235         call <SID>NM_search_refresh_view()
236 endfunction
237
238 function! s:NM_add_remove_tags(prefix, tags)
239         let id = <SID>NM_search_find_thread_id()
240         if id == ''
241                 echoe 'Eeek! I couldn''t find the thead id!'
242         endif
243         call map(a:tags, 'a:prefix . v:val')
244         " TODO: handle errors
245         call <SID>NM_run(['tag'] + a:tags + ['--', id])
246 endfunction
247
248 " --- implement show screen {{{1
249
250 function! s:NM_cmd_show(words)
251         let prev_bufnr = bufnr('%')
252         let data = s:NM_run(['show'] + a:words)
253         let lines = split(data, "\n")
254
255         let info = s:NM_cmd_show_parse(lines)
256
257         setlocal bufhidden=hide
258         call <SID>NM_newBuffer('show', join(info['disp'], "\n"))
259         setlocal bufhidden=delete
260         let b:nm_raw_info = info
261         let b:nm_prev_bufnr = prev_bufnr
262
263         call <SID>NM_cmd_show_mkfolds()
264         call <SID>NM_cmd_show_mksyntax()
265         call <SID>NM_set_map(g:notmuch_show_maps)
266         setlocal foldtext=NM_cmd_show_foldtext()
267         setlocal fillchars=
268         setlocal foldcolumn=6
269
270 endfunction
271
272 function! s:NM_kill_buffer()
273         if exists('b:nm_prev_bufnr')
274                 setlocal bufhidden=delete
275                 exec printf(":buffer %d", b:nm_prev_bufnr)
276         else
277                 echo "Nothing to kill."
278         endif
279 endfunction
280
281 function! s:NM_cmd_show_next()
282         let info = b:nm_raw_info
283         let lnum = line('.')
284         let cnt = 0
285         for msg in info['msgs']
286                 let cnt = cnt + 1
287                 if lnum >= msg['start']
288                         continue
289                 endif
290
291                 exec printf('norm %dG', msg['start'])
292                 norm zz
293                 return
294         endfor
295         norm qj
296         call <SID>NM_search_show_thread()
297 endfunction
298
299 function! s:NM_cmd_show_fold_toggle(key, type, fold)
300         let info = b:nm_raw_info
301         let act = 'open'
302         if a:fold
303                 let act = 'close'
304         endif
305         for fld in info['folds']
306                 if fld[0] == a:type
307                         exec printf('%dfold%s', fld[1], act)
308                 endif
309         endfor
310         exec printf('nnoremap <buffer> %s :call <SID>NM_cmd_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
311 endfunction
312
313
314 " s:NM_cmd_show_parse returns the following dictionary:
315 "    'disp':     lines to display
316 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
317 "    'folds':    fold info arrays [ type, start, end ]
318 "    'foldtext': fold text indexed by start line
319 function! s:NM_cmd_show_parse(inlines)
320         let info = { 'disp': [],       
321                    \ 'msgs': [],       
322                    \ 'folds': [],      
323                    \ 'foldtext': {} }  
324         let msg = {}
325         let hdr = {}
326
327         let in_message = 0
328         let in_header = 0
329         let in_body = 0
330         let in_part = ''
331
332         let body_start = -1
333         let part_start = -1
334
335         let mode_type = ''
336         let mode_start = -1
337
338         let inlnum = 0
339         for line in a:inlines
340                 let inlnum = inlnum + 1
341                 let foldinfo = []
342
343                 if strlen(in_part)
344                         let part_end = 0
345
346                         if match(line, g:notmuch_show_part_end_regexp) != -1
347                                 let part_end = len(info['disp'])
348                         else
349                                 call add(info['disp'], line)
350                         endif
351
352                         if in_part == 'text/plain'
353                                 if !part_end && mode_type == ''
354                                         if match(line, g:notmuch_show_signature_regexp) != -1
355                                                 let mode_type = 'sig'
356                                                 let mode_start = len(info['disp'])
357                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
358                                                 let mode_type = 'cit'
359                                                 let mode_start = len(info['disp'])
360                                         endif
361                                 elseif mode_type == 'cit'
362                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
363                                                 let outlnum = len(info['disp'])
364                                                 let foldinfo = [ mode_type, mode_start, outlnum,
365                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
366                                                 let mode_type = ''
367                                         endif
368                                 elseif mode_type == 'sig'
369                                         let outlnum = len(info['disp'])
370                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
371                                                 echoe 'line ' . outlnum . ' stopped matching'
372                                                 let mode_type = ''
373                                         elseif part_end
374                                                 let foldinfo = [ mode_type, mode_start, outlnum,
375                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
376                                                 let mode_type = ''
377                                         endif
378                                 endif
379                         endif
380
381                         if part_end
382                                 " FIXME: this is a hack for handling two folds being added for one line
383                                 "         we should handle addinga fold in a function
384                                 if len(foldinfo)
385                                         call add(info['folds'], foldinfo[0:2])
386                                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
387                                 endif
388
389                                 let foldinfo = [ 'text', part_start, part_end,
390                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
391                                 let in_part = ''
392                                 call add(info['disp'], '')
393                         endif
394
395                 elseif in_body
396                         if !has_key(msg,'body_start')
397                                 let msg['body_start'] = len(info['disp']) + 1
398                         endif
399                         if match(line, g:notmuch_show_body_end_regexp) != -1
400                                 let body_end = len(info['disp'])
401                                 let foldinfo = [ 'body', body_start, body_end,
402                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
403
404                                 let in_body = 0
405
406                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
407                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
408                                 let in_part = 'unknown'
409                                 if len(m)
410                                         let in_part = m[2]
411                                 endif
412                                 call add(info['disp'],
413                                          \ printf('--- %s ---', in_part))
414                                 let part_start = len(info['disp']) + 1
415                         endif
416
417                 elseif in_header
418                         if in_header == 1
419                                 let msg['descr'] = line
420                                 call add(info['disp'], line)
421                                 let in_header = 2
422                                 let msg['hdr_start'] = len(info['disp']) + 1
423
424                         else
425                                 if match(line, g:notmuch_show_header_end_regexp) != -1
426                                         let msg['header'] = hdr
427                                         let in_header = 0
428                                         let hdr = {}
429                                 else
430                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
431                                         if len(m)
432                                                 let hdr[m[1]] = m[2]
433                                                 if match(g:notmuch_show_headers, m[1]) != -1
434                                                         call add(info['disp'], line)
435                                                 endif
436                                         endif
437                                 endif
438                         endif
439
440                 elseif in_message
441                         if match(line, g:notmuch_show_message_end_regexp) != -1
442                                 let msg['end'] = len(info['disp'])
443                                 call add(info['disp'], '')
444
445                                 let foldinfo = [ 'match', msg['start'], msg['end'],
446                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
447
448                                 call add(info['msgs'], msg)
449                                 let msg = {}
450                                 let in_message = 0
451                                 let in_header = 0
452                                 let in_body = 0
453                                 let in_part = ''
454
455                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
456                                 let in_header = 1
457                                 continue
458
459                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
460                                 let body_start = len(info['disp']) + 1
461                                 let in_body = 1
462                                 continue
463                         endif
464
465                 else
466                         if match(line, g:notmuch_show_message_begin_regexp) != -1
467                                 let msg['start'] = len(info['disp']) + 1
468
469                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
470                                 if len(m)
471                                         let msg['id'] = m[1]
472                                         let msg['depth'] = m[2]
473                                         let msg['filename'] = m[3]
474                                 endif
475
476                                 let in_message = 1
477                         endif
478                 endif
479
480                 if len(foldinfo)
481                         call add(info['folds'], foldinfo[0:2])
482                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
483                 endif
484         endfor
485         return info
486 endfunction
487
488 function! s:NM_cmd_show_mkfolds()
489         let info = b:nm_raw_info
490
491         for afold in info['folds']
492                 exec printf('%d,%dfold', afold[1], afold[2])
493                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
494                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
495                         exec printf('%dfoldclose', afold[1])
496                 else
497                         exec printf('%dfoldopen', afold[1])
498                 endif
499         endfor
500 endfunction
501
502 function! s:NM_cmd_show_mksyntax()
503         let info = b:nm_raw_info
504         let cnt = 0
505         for msg in info['msgs']
506                 let cnt = cnt + 1
507                 let start = msg['start']
508                 let hdr_start = msg['hdr_start']
509                 let body_start = msg['body_start']
510                 let end = msg['end']
511                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
512                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
513                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
514         endfor
515 endfunction
516
517 function! NM_cmd_show_foldtext()
518         let foldtext = b:nm_raw_info['foldtext']
519         return foldtext[v:foldstart]
520 endfunction
521
522
523 " --- notmuch helper functions {{{1
524
525 function! s:NM_newBuffer(ft, content)
526         enew
527         setlocal buftype=nofile readonly modifiable
528         silent put=a:content
529         keepjumps 0d
530         setlocal nomodifiable
531         execute printf('set filetype=notmuch-%s', a:ft)
532         execute printf('set syntax=notmuch-%s', a:ft)
533 endfunction
534
535 function! s:NM_run(args)
536         let cmd = g:notmuch_cmd . ' ' . join(a:args) . '< /dev/null'
537         let out = system(cmd)
538         if v:shell_error
539                 echohl Error
540                 echo substitute(out, '\n*$', '', '')
541                 echohl None
542                 return ''
543         else
544                 return out
545         endif
546 endfunction
547
548 " --- process and set the defaults {{{1
549
550 function! NM_set_defaults(force)
551         for [key, dflt] in items(s:notmuch_defaults)
552                 let cmd = ''
553                 if !a:force && exists(key) && type(dflt) == type(eval(key))
554                         continue
555                 elseif type(dflt) == type(0)
556                         let cmd = printf('let %s = %d', key, dflt)
557                 elseif type(dflt) == type('')
558                         let cmd = printf('let %s = ''%s''', key, dflt)
559                 "elseif type(dflt) == type([])
560                 "        let cmd = printf('let %s = %s', key, string(dflt))
561                 else
562                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
563                                                 \ a:force, key, string(dflt))
564                         continue
565                 endif
566                 exec cmd
567         endfor
568 endfunction
569 call NM_set_defaults(0)
570
571 " for some reason NM_set_defaults() didn't work for arrays...
572 if !exists('g:notmuch_show_headers')
573         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
574 endif
575 if !exists('g:notmuch_initial_search_words')
576         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
577 endif
578
579
580 " --- assign keymaps {{{1
581
582 function! s:NM_set_map(maps)
583         for [key, code] in items(a:maps)
584                 exec printf('nnoremap <buffer> %s %s', key, code)
585         endfor
586 endfunction
587
588 " --- command handler {{{1
589
590 function! NotMuch(args)
591         if !strlen(a:args)
592                 if exists('b:nm_search_words')
593                         let words = b:nm_search_words
594                 else
595                         let words = g:notmuch_initial_search_words
596                 endif
597                 call <SID>NM_cmd_search(words)
598                 return
599         endif
600
601         echo "blarg!"
602
603         let words = split(a:args)
604         " TODO: handle commands passed as arguments
605 endfunction
606 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
607         return []
608 endfunction
609
610
611 " --- glue {{{1
612
613 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
614 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
615
616 " --- hacks, only for development :) {{{1
617
618 nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
619
620 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :