1 " notmuch.vim plugin --- run notmuch within vim
3 " Copyright © Carl Worth
5 " This file is part of Notmuch.
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.
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.
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/>.
20 " Authors: Bart Trojanowski <bart@jukie.net>
22 " --- configuration defaults {{{1
24 let s:notmuch_defaults = {
25 \ 'g:notmuch_cmd': 'notmuch' ,
27 \ 'g:notmuch_search_newest_first': 1 ,
28 \ 'g:notmuch_search_from_column_width': 20 ,
30 \ 'g:notmuch_show_fold_signatures': 1 ,
31 \ 'g:notmuch_show_fold_citations': 1 ,
32 \ 'g:notmuch_show_fold_bodies': 0 ,
33 \ 'g:notmuch_show_fold_headers': 1 ,
35 \ 'g:notmuch_show_message_begin_regexp': '^
\fmessage{' ,
36 \ 'g:notmuch_show_message_end_regexp': '^
\fmessage}' ,
37 \ 'g:notmuch_show_header_begin_regexp': '^
\fheader{' ,
38 \ 'g:notmuch_show_header_end_regexp': '^
\fheader}' ,
39 \ 'g:notmuch_show_body_begin_regexp': '^
\fbody{' ,
40 \ 'g:notmuch_show_body_end_regexp': '^
\fbody}' ,
41 \ 'g:notmuch_show_attachment_begin_regexp': '^
\fattachment{' ,
42 \ 'g:notmuch_show_attachment_end_regexp': '^
\fattachment}' ,
43 \ 'g:notmuch_show_part_begin_regexp': '^
\fpart{' ,
44 \ 'g:notmuch_show_part_end_regexp': '^
\fpart}' ,
45 \ 'g:notmuch_show_marker_regexp': '^
\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
47 \ 'g:notmuch_show_message_parse_regexp': '\(id:[^ ]*\) depth:\([0-9]*\) filename:\(.*\)$',
48 \ 'g:notmuch_show_tags_regexp': '(\([^)]*\))$' ,
50 \ 'g:notmuch_show_signature_regexp': '^\(-- \?\|_\+\)$' ,
51 \ 'g:notmuch_show_signature_lines_max': 12 ,
53 \ 'g:notmuch_show_citation_regexp': '^\s*>' ,
56 " defaults for g:notmuch_initial_search_words
57 " override with: let g:notmuch_initial_search_words = [ ... ]
58 let s:notmuch_initial_search_words_defaults = [
59 \ 'tag:inbox and tag:unread',
62 " defaults for g:notmuch_show_headers
63 " override with: let g:notmuch_show_headers = [ ... ]
64 let s:notmuch_show_headers_defaults = [
72 " --- keyboard mapping definitions {{{1
74 " --- --- bindings for search screen {{{2
75 let g:notmuch_search_maps = {
76 \ '<Enter>': ':call <SID>NM_search_show_thread()<CR>',
77 \ 'a': ':call <SID>NM_search_archive_thread()<CR>',
78 \ 'f': ':call <SID>NM_search_filter()<CR>',
79 \ 'm': ':call <SID>NM_new_mail()<CR>',
80 \ 'o': ':call <SID>NM_search_toggle_order()<CR>',
81 \ 'r': ':call <SID>NM_search_reply_to_thread()<CR>',
82 \ 's': ':call <SID>NM_search_prompt()<CR>',
83 \ 'S': ':call <SID>NM_search_edit()<CR>',
84 \ 't': ':call <SID>NM_search_filter_by_tag()<CR>',
85 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
86 \ '+': ':call <SID>NM_search_add_tags([])<CR>',
87 \ '-': ':call <SID>NM_search_remove_tags([])<CR>',
88 \ '=': ':call <SID>NM_search_refresh_view()<CR>',
91 " --- --- bindings for show screen {{{2
92 let g:notmuch_show_maps = {
93 \ '<C-P>': ':call <SID>NM_show_previous(1)<CR>',
94 \ '<C-N>': ':call <SID>NM_show_next(1)<CR>',
95 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
97 \ 'b': ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
98 \ 'c': ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
99 \ 'h': ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
100 \ 's': ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
102 \ 'a': ':call <SID>NM_show_archive_thread()<CR>',
103 \ 'A': ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
104 \ 'N': ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
105 \ 'v': ':call <SID>NM_show_view_all_mime_parts()<CR>',
106 \ '+': ':call <SID>NM_show_add_tag()<CR>',
107 \ '-': ':call <SID>NM_show_remove_tag()<CR>',
108 \ '<Space>': ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
109 \ '\|': ':call <SID>NM_show_pipe_message()<CR>',
111 \ 'r': ':call <SID>NM_show_reply()<CR>',
112 \ 'm': ':call <SID>NM_new_mail()<CR>',
116 " --- implement search screen {{{1
118 function! s:NM_cmd_search(words)
120 if g:notmuch_search_newest_first
121 let cmd = cmd + ['--sort=newest-first']
123 let cmd = cmd + ['--sort=oldest-first']
125 let data = s:NM_run(cmd + a:words)
126 let lines = split(data, "\n")
127 let disp = copy(lines)
128 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
130 call <SID>NM_newBuffer('search', join(disp, "\n"))
131 let b:nm_raw_lines = lines
132 let b:nm_search_words = a:words
134 call <SID>NM_cmd_search_mksyntax()
135 call <SID>NM_set_map(g:notmuch_search_maps)
139 function! s:NM_cmd_search_fmtline(line)
140 let m = matchlist(a:line, '^\(thread:\S\+\)\s\([^]]\+\]\) \([^;]\+\); \(.*\) (\([^(]*\))$')
142 return 'ERROR PARSING: ' . a:line
144 let max = g:notmuch_search_from_column_width
146 if strlen(from) >= max
147 let from = m[3][0:max-4] . '...'
149 return printf('%s %-20s | %s (%s)', m[2], from, m[4], m[5])
151 function! s:NM_cmd_search_mksyntax()
152 syntax clear nmSearchFrom
153 "syntax region nmSearchFrom start='\]\@<=' end='.'me=e+5,he=e+5,re=e+5 oneline contained
154 "syntax match nmSearchFrom /\]\@<=.\{10\}/ oneline contained
155 exec printf('syntax match nmSearchFrom /\(\] \)\@<=.\{%d\}/ oneline contained', g:notmuch_search_from_column_width)
156 "exec printf('syntax region nmSearchFrom start=''\%%%dv'' end=''\%%%dv'' oneline contained', 20, 30)
159 " --- --- search screen action functions {{{2
161 function! s:NM_search_show_thread()
162 let id = <SID>NM_search_find_thread_id()
164 call <SID>NM_cmd_show([id])
168 function! s:NM_search_prompt()
169 " TODO: input() can support completion
170 let text = input('NotMuch Search: ')
172 let tags = split(text)
174 let tags = s:notmuch_initial_search_words_defaults
176 setlocal bufhidden=delete
177 call <SID>NM_cmd_search(tags)
180 function! s:NM_search_edit()
181 " TODO: input() can support completion
182 let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
184 call <SID>NM_cmd_search(split(text))
188 function! s:NM_search_archive_thread()
189 call <SID>NM_add_remove_tags_on_screen('-', ['inbox'])
190 call <SID>NM_add_remove_tags('-', ['inbox'])
194 function! s:NM_search_filter()
195 call <SID>NM_search_filter_helper('Filter: ', '')
198 function! s:NM_search_filter_by_tag()
199 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:')
202 function! s:NM_search_filter_helper(prompt, prefix)
203 " TODO: input() can support completion
204 let text = input(a:prompt)
209 let tags = split(text)
210 map(tags, 'and a:prefix . v:val')
211 let tags = b:nm_search_words + tags
214 let prev_bufnr = bufnr('%')
215 setlocal bufhidden=hide
216 call <SID>NM_cmd_search(tags)
217 setlocal bufhidden=delete
218 let b:nm_prev_bufnr = prev_bufnr
221 function! s:NM_search_toggle_order()
222 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
223 " FIXME: maybe this would be better done w/o reading re-reading the lines
224 " reversing the b:nm_raw_lines and the buffer lines would be better
225 call <SID>NM_search_refresh_view()
228 function! s:NM_search_reply_to_thread()
229 echo 'not implemented'
232 function! s:NM_search_add_tags(tags)
233 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
236 function! s:NM_search_remove_tags(tags)
237 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
240 function! s:NM_search_refresh_view()
242 setlocal bufhidden=delete
243 call <SID>NM_cmd_search(b:nm_search_words)
244 " FIXME: should find the line of the thread we were on if possible
245 exec printf('norm %dG', lno)
248 " --- --- search screen helper functions {{{2
250 function! s:NM_search_find_thread_id()
251 if !exists('b:nm_raw_lines')
252 echoe 'no b:nm_raw_lines'
256 let info = b:nm_raw_lines[line-1]
257 let what = split(info, '\s\+')[0]
262 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
263 if type(a:intags) != type([]) || len(a:intags) == 0
264 " TODO: input() can support completion
265 let text = input(a:prompt)
269 let tags = split(text, ' ')
273 call <SID>NM_add_remove_tags(a:prefix, tags)
274 call <SID>NM_add_remove_tags_on_screen(a:prefix, tags)
277 " --- implement show screen {{{1
279 function! s:NM_cmd_show(words)
280 let prev_bufnr = bufnr('%')
281 let data = s:NM_run(['show'] + a:words)
282 let lines = split(data, "\n")
284 let info = s:NM_cmd_show_parse(lines)
286 setlocal bufhidden=hide
287 call <SID>NM_newBuffer('show', join(info['disp'], "\n"))
288 setlocal bufhidden=delete
289 let b:nm_raw_info = info
290 let b:nm_prev_bufnr = prev_bufnr
292 call <SID>NM_cmd_show_mkfolds()
293 call <SID>NM_cmd_show_mksyntax()
294 call <SID>NM_set_map(g:notmuch_show_maps)
295 setlocal foldtext=NM_cmd_show_foldtext()
297 setlocal foldcolumn=6
301 function! s:NM_show_previous(can_change_thread)
302 let info = b:nm_raw_info
304 for msg in reverse(copy(info['msgs']))
305 if lnum <= msg['start']
309 exec printf('norm %dG', msg['start'])
310 " TODO: try to fit the message on screen
314 if !a:can_change_thread
317 call <SID>NM_kill_this_buffer()
318 if line('.') != line('0')
320 call <SID>NM_search_show_thread()
322 call <SID>NM_show_previous(0)
324 echo 'No more messages.'
328 function! s:NM_show_next(can_change_thread)
329 let info = b:nm_raw_info
331 for msg in info['msgs']
332 if lnum >= msg['start']
336 exec printf('norm %dG', msg['start'])
337 " TODO: try to fit the message on screen
341 if !a:can_change_thread
344 call <SID>NM_kill_this_buffer()
345 if line('.') != line('$')
347 call <SID>NM_search_show_thread()
349 echo 'No more messages.'
353 function! s:NM_show_archive_thread()
354 echo 'not implemented'
357 function! s:NM_show_mark_read_then_archive_thread()
358 echo 'not implemented'
361 function! s:NM_show_next_message()
362 echo 'not implemented'
365 function! s:NM_show_mark_read_then_next_open_message()
366 echo 'not implemented'
369 function! s:NM_show_previous_message()
370 echo 'not implemented'
373 function! s:NM_show_reply()
374 echo 'not implemented'
377 function! s:NM_show_view_all_mime_parts()
378 echo 'not implemented'
381 function! s:NM_show_view_raw_message()
382 echo 'not implemented'
385 function! s:NM_show_add_tag()
386 echo 'not implemented'
389 function! s:NM_show_remove_tag()
390 echo 'not implemented'
393 function! s:NM_show_advance_marking_read_and_archiving()
394 echo 'not implemented'
397 function! s:NM_show_pipe_message()
398 echo 'not implemented'
401 " --- --- search screen helper functions {{{2
403 function! s:NM_show_fold_toggle(key, type, fold)
404 let info = b:nm_raw_info
409 for fld in info['folds']
411 exec printf('%dfold%s', fld[1], act)
414 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
418 " s:NM_cmd_show_parse returns the following dictionary:
419 " 'disp': lines to display
420 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
421 " 'folds': fold info arrays [ type, start, end ]
422 " 'foldtext': fold text indexed by start line
423 function! s:NM_cmd_show_parse(inlines)
424 let info = { 'disp': [],
443 for line in a:inlines
444 let inlnum = inlnum + 1
450 if match(line, g:notmuch_show_part_end_regexp) != -1
451 let part_end = len(info['disp'])
453 call add(info['disp'], line)
456 if in_part == 'text/plain'
457 if !part_end && mode_type == ''
458 if match(line, g:notmuch_show_signature_regexp) != -1
459 let mode_type = 'sig'
460 let mode_start = len(info['disp'])
461 elseif match(line, g:notmuch_show_citation_regexp) != -1
462 let mode_type = 'cit'
463 let mode_start = len(info['disp'])
465 elseif mode_type == 'cit'
466 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
467 let outlnum = len(info['disp'])
468 if mode_start != outlnum
469 let foldinfo = [ mode_type, mode_start, outlnum-1,
470 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
474 elseif mode_type == 'sig'
475 let outlnum = len(info['disp'])
476 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
479 if mode_start != outlnum
480 let foldinfo = [ mode_type, mode_start, outlnum-1,
481 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
489 " FIXME: this is a hack for handling two folds being added for one line
490 " we should handle addinga fold in a function
492 call add(info['folds'], foldinfo[0:2])
493 let info['foldtext'][foldinfo[1]] = foldinfo[3]
496 let foldinfo = [ 'text', part_start, part_end,
497 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
499 call add(info['disp'], '')
503 if !has_key(msg,'body_start')
504 let msg['body_start'] = len(info['disp']) + 1
506 if match(line, g:notmuch_show_body_end_regexp) != -1
507 let body_end = len(info['disp'])
508 let foldinfo = [ 'bdy', body_start, body_end,
509 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
513 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
514 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
515 let in_part = 'unknown'
519 call add(info['disp'],
520 \ printf('--- %s ---', in_part))
521 let part_start = len(info['disp']) + 1
526 let msg['descr'] = line
527 call add(info['disp'], line)
529 let msg['hdr_start'] = len(info['disp']) + 1
532 if match(line, g:notmuch_show_header_end_regexp) != -1
533 let hdr_start = msg['hdr_start']+1
534 let hdr_end = len(info['disp'])
535 let foldinfo = [ 'hdr', hdr_start, hdr_end,
536 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
537 let msg['header'] = hdr
541 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
544 if match(g:notmuch_show_headers, m[1]) != -1
545 call add(info['disp'], line)
552 if match(line, g:notmuch_show_message_end_regexp) != -1
553 let msg['end'] = len(info['disp'])
554 call add(info['disp'], '')
556 let foldinfo = [ 'msg', msg['start'], msg['end'],
557 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
559 call add(info['msgs'], msg)
566 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
570 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
571 let body_start = len(info['disp']) + 1
577 if match(line, g:notmuch_show_message_begin_regexp) != -1
578 let msg['start'] = len(info['disp']) + 1
580 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
583 let msg['depth'] = m[2]
584 let msg['filename'] = m[3]
592 call add(info['folds'], foldinfo[0:2])
593 let info['foldtext'][foldinfo[1]] = foldinfo[3]
599 function! s:NM_cmd_show_mkfolds()
600 let info = b:nm_raw_info
602 for afold in info['folds']
603 exec printf('%d,%dfold', afold[1], afold[2])
604 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
605 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
606 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
607 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
608 exec printf('%dfoldclose', afold[1])
610 exec printf('%dfoldopen', afold[1])
615 function! s:NM_cmd_show_mksyntax()
616 let info = b:nm_raw_info
618 for msg in info['msgs']
620 let start = msg['start']
621 let hdr_start = msg['hdr_start']
622 let body_start = msg['body_start']
624 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
625 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
626 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
630 function! NM_cmd_show_foldtext()
631 let foldtext = b:nm_raw_info['foldtext']
632 return foldtext[v:foldstart]
636 " --- notmuch helper functions {{{1
638 function! s:NM_newBuffer(ft, content)
640 setlocal buftype=nofile readonly modifiable
643 setlocal nomodifiable
644 execute printf('set filetype=notmuch-%s', a:ft)
645 execute printf('set syntax=notmuch-%s', a:ft)
648 function! s:NM_run(args)
649 let cmd = g:notmuch_cmd . ' ' . join(a:args) . '< /dev/null'
651 let start = reltime()
652 let out = system(cmd)
653 let err = v:shell_error
654 let delta = reltime(start)
656 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
660 echo substitute(out, '\n*$', '', '')
668 " --- external mail handling helpers {{{1
670 function! s:NM_new_mail()
671 echo 'not implemented'
674 " --- other helpers {{{1
676 function! s:NM_kill_this_buffer()
677 if exists('b:nm_prev_bufnr')
678 setlocal bufhidden=delete
679 exec printf(":buffer %d", b:nm_prev_bufnr)
681 echo "Nothing to kill."
685 function! s:NM_add_remove_tags(prefix, tags)
686 let id = <SID>NM_search_find_thread_id()
688 echoe 'Eeek! I couldn''t find the thead id!'
690 call map(a:tags, 'a:prefix . v:val')
691 " TODO: handle errors
692 call <SID>NM_run(['tag'] + a:tags + ['--', id])
695 function! s:NM_add_remove_tags_on_screen(prefix, tags)
699 for tagname in a:tags
700 exec printf('silent %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', online, tagname)
703 for tagname in a:tags
704 exec printf('silent %ss/(\([^)]*\)\([^)]*\))$/(\1 %s)/', online, tagname)
707 setlocal nomodifiable
710 " --- process and set the defaults {{{1
712 function! NM_set_defaults(force)
713 for [key, dflt] in items(s:notmuch_defaults)
715 if !a:force && exists(key) && type(dflt) == type(eval(key))
717 elseif type(dflt) == type(0)
718 let cmd = printf('let %s = %d', key, dflt)
719 elseif type(dflt) == type('')
720 let cmd = printf('let %s = ''%s''', key, dflt)
721 "elseif type(dflt) == type([])
722 " let cmd = printf('let %s = %s', key, string(dflt))
724 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
725 \ a:force, key, string(dflt))
731 call NM_set_defaults(0)
733 " for some reason NM_set_defaults() didn't work for arrays...
734 if !exists('g:notmuch_show_headers')
735 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
737 if !exists('g:notmuch_initial_search_words')
738 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
742 " --- assign keymaps {{{1
744 function! s:NM_set_map(maps)
746 for [key, code] in items(a:maps)
747 exec printf('nnoremap <buffer> %s %s', key, code)
749 " --- this is a hack for development :)
750 nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
753 " --- command handler {{{1
755 function! NotMuch(args)
757 if exists('b:nm_search_words')
758 let words = b:nm_search_words
760 let words = g:notmuch_initial_search_words
762 call <SID>NM_cmd_search(words)
768 let words = split(a:args)
769 " TODO: handle commands passed as arguments
771 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
778 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
779 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
781 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :