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 = [
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_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_cmd_show_prev()<CR>',
94 \ '<C-N>': ':call <SID>NM_cmd_show_next()<CR>',
95 \ 'b': ':call <SID>NM_cmd_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
96 \ 'c': ':call <SID>NM_cmd_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
97 \ 'h': ':call <SID>NM_cmd_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
98 \ 's': ':call <SID>NM_cmd_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
99 \ 'q': ':call <SID>NM_kill_buffer()<CR>',
102 " --- implement search screen {{{1
104 function! s:NM_cmd_search(words)
106 if g:notmuch_search_newest_first
107 let cmd = cmd + ['--sort=newest-first']
109 let cmd = cmd + ['--sort=oldest-first']
111 let data = s:NM_run(cmd + a:words)
112 "let data = substitute(data, '27/27', '25/27', '')
113 "let data = substitute(data, '\[4/4\]', '[0/4]', '')
114 let lines = split(data, "\n")
115 let disp = copy(lines)
116 "call map(disp, 'substitute(v:val, "^thread:\\S* ", "", "")' )
117 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
119 call <SID>NM_newBuffer('search', join(disp, "\n"))
120 let b:nm_raw_lines = lines
121 let b:nm_search_words = a:words
123 call <SID>NM_cmd_search_mksyntax()
124 call <SID>NM_set_map(g:notmuch_search_maps)
128 function! s:NM_cmd_search_fmtline(line)
129 let m = matchlist(a:line, '^\(thread:\S\+\)\s\([^]]\+\]\) \([^;]\+\); \(.*\) (\([^(]*\))$')
131 return 'ERROR PARSING: ' . a:line
133 let max = g:notmuch_search_from_column_width
135 if strlen(from) >= max
136 let from = m[3][0:max-4] . '...'
138 return printf('%s %-20s | %s (%s)', m[2], from, m[4], m[5])
140 function! s:NM_cmd_search_mksyntax()
141 syntax clear nmSearchFrom
142 "syntax region nmSearchFrom start='\]\@<=' end='.'me=e+5,he=e+5,re=e+5 oneline contained
143 "syntax match nmSearchFrom /\]\@<=.\{10\}/ oneline contained
144 exec printf('syntax match nmSearchFrom /\(\] \)\@<=.\{%d\}/ oneline contained', g:notmuch_search_from_column_width)
145 "exec printf('syntax region nmSearchFrom start=''\%%%dv'' end=''\%%%dv'' oneline contained', 20, 30)
148 " --- --- search screen action functions {{{2
150 function! s:NM_search_show_thread()
151 let id = <SID>NM_search_find_thread_id()
153 call <SID>NM_cmd_show([id])
157 function! s:NM_search_prompt()
158 " TODO: input() can support completion
159 let text = input('NotMuch Search: ')
161 let tags = split(text)
163 let tags = s:notmuch_initial_search_words_defaults
165 setlocal bufhidden=delete
166 call <SID>NM_cmd_search(tags)
169 function! s:NM_search_edit()
170 " TODO: input() can support completion
171 let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
173 call <SID>NM_cmd_search(split(text))
177 function! s:NM_search_archive_thread()
178 call <SID>NM_add_remove_tags('-', ['inbox'])
179 " TODO: this could be made better and more generic
181 s/(\([^)]*\)\<inbox\>\([^)]*\))$/(\1\2)/
182 setlocal nomodifiable
186 function! s:NM_search_filter()
187 call <SID>NM_search_filter_helper('Filter: ', '')
190 function! s:NM_search_filter_by_tag()
191 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:')
194 function! s:NM_search_filter_helper(prompt, prefix)
195 " TODO: input() can support completion
196 let text = input(a:prompt)
201 let tags = split(text)
202 map(tags, 'and a:prefix . v:val')
203 let tags = b:nm_search_words + tags
206 let prev_bufnr = bufnr('%')
207 setlocal bufhidden=hide
208 call <SID>NM_cmd_search(tags)
209 setlocal bufhidden=delete
210 let b:nm_prev_bufnr = prev_bufnr
213 function! s:NM_new_mail()
214 echoe 'Not implemented'
217 function! s:NM_search_toggle_order()
218 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
219 " FIXME: maybe this would be better done w/o reading re-reading the lines
220 " reversing the b:nm_raw_lines and the buffer lines would be better
221 call <SID>NM_search_refresh_view()
224 function! s:NM_search_reply_to_thread()
225 echoe 'Not implemented'
228 function! s:NM_search_add_tags(tags)
229 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
232 function! s:NM_search_remove_tags(tags)
233 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
236 function! s:NM_search_refresh_view()
238 setlocal bufhidden=delete
239 call <SID>NM_cmd_search(b:nm_search_words)
240 " FIXME: should find the line of the thread we were on if possible
241 exec printf('norm %dG', lno)
244 " --- --- search screen helper functions {{{2
246 function! s:NM_search_find_thread_id()
247 if !exists('b:nm_raw_lines')
248 echoe 'no b:nm_raw_lines'
252 let info = b:nm_raw_lines[line-1]
253 let what = split(info, '\s\+')[0]
258 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
259 if type(a:intags) != type([]) || len(a:intags) == 0
260 " TODO: input() can support completion
261 let text = input(a:prompt)
265 call <SID>NM_add_remove_tags(a:prefix, split(text, ' '))
267 call <SID>NM_add_remove_tags(a:prefix, a:intags)
269 call <SID>NM_search_refresh_view()
272 function! s:NM_add_remove_tags(prefix, tags)
273 let id = <SID>NM_search_find_thread_id()
275 echoe 'Eeek! I couldn''t find the thead id!'
277 call map(a:tags, 'a:prefix . v:val')
278 " TODO: handle errors
279 call <SID>NM_run(['tag'] + a:tags + ['--', id])
282 " --- implement show screen {{{1
284 function! s:NM_cmd_show(words)
285 let prev_bufnr = bufnr('%')
286 let data = s:NM_run(['show'] + a:words)
287 let lines = split(data, "\n")
289 let info = s:NM_cmd_show_parse(lines)
291 setlocal bufhidden=hide
292 call <SID>NM_newBuffer('show', join(info['disp'], "\n"))
293 setlocal bufhidden=delete
294 let b:nm_raw_info = info
295 let b:nm_prev_bufnr = prev_bufnr
297 call <SID>NM_cmd_show_mkfolds()
298 call <SID>NM_cmd_show_mksyntax()
299 call <SID>NM_set_map(g:notmuch_show_maps)
300 setlocal foldtext=NM_cmd_show_foldtext()
302 setlocal foldcolumn=6
306 function! s:NM_kill_buffer()
307 if exists('b:nm_prev_bufnr')
308 setlocal bufhidden=delete
309 exec printf(":buffer %d", b:nm_prev_bufnr)
311 echo "Nothing to kill."
315 function! s:NM_cmd_show_prev()
316 echoe "not implemented"
319 function! s:NM_cmd_show_next()
320 let info = b:nm_raw_info
323 for msg in info['msgs']
325 if lnum >= msg['start']
329 exec printf('norm %dG', msg['start'])
334 call <SID>NM_search_show_thread()
337 function! s:NM_cmd_show_fold_toggle(key, type, fold)
338 let info = b:nm_raw_info
343 for fld in info['folds']
345 exec printf('%dfold%s', fld[1], act)
348 exec printf('nnoremap <buffer> %s :call <SID>NM_cmd_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
352 " s:NM_cmd_show_parse returns the following dictionary:
353 " 'disp': lines to display
354 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
355 " 'folds': fold info arrays [ type, start, end ]
356 " 'foldtext': fold text indexed by start line
357 function! s:NM_cmd_show_parse(inlines)
358 let info = { 'disp': [],
377 for line in a:inlines
378 let inlnum = inlnum + 1
384 if match(line, g:notmuch_show_part_end_regexp) != -1
385 let part_end = len(info['disp'])
387 call add(info['disp'], line)
390 if in_part == 'text/plain'
391 if !part_end && mode_type == ''
392 if match(line, g:notmuch_show_signature_regexp) != -1
393 let mode_type = 'sig'
394 let mode_start = len(info['disp'])
395 elseif match(line, g:notmuch_show_citation_regexp) != -1
396 let mode_type = 'cit'
397 let mode_start = len(info['disp'])
399 elseif mode_type == 'cit'
400 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
401 let outlnum = len(info['disp'])
402 let foldinfo = [ mode_type, mode_start, outlnum,
403 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
406 elseif mode_type == 'sig'
407 let outlnum = len(info['disp'])
408 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
411 let foldinfo = [ mode_type, mode_start, outlnum,
412 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
419 " FIXME: this is a hack for handling two folds being added for one line
420 " we should handle addinga fold in a function
422 call add(info['folds'], foldinfo[0:2])
423 let info['foldtext'][foldinfo[1]] = foldinfo[3]
426 let foldinfo = [ 'text', part_start, part_end,
427 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
429 call add(info['disp'], '')
433 if !has_key(msg,'body_start')
434 let msg['body_start'] = len(info['disp']) + 1
436 if match(line, g:notmuch_show_body_end_regexp) != -1
437 let body_end = len(info['disp'])
438 let foldinfo = [ 'bdy', body_start, body_end,
439 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
443 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
444 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
445 let in_part = 'unknown'
449 call add(info['disp'],
450 \ printf('--- %s ---', in_part))
451 let part_start = len(info['disp']) + 1
456 let msg['descr'] = line
457 call add(info['disp'], line)
459 let msg['hdr_start'] = len(info['disp']) + 1
462 if match(line, g:notmuch_show_header_end_regexp) != -1
463 let hdr_start = msg['hdr_start']+1
464 let hdr_end = len(info['disp'])
465 let foldinfo = [ 'hdr', hdr_start, hdr_end,
466 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end - hdr_start) ]
467 let msg['header'] = hdr
471 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
474 if match(g:notmuch_show_headers, m[1]) != -1
475 call add(info['disp'], line)
482 if match(line, g:notmuch_show_message_end_regexp) != -1
483 let msg['end'] = len(info['disp'])
484 call add(info['disp'], '')
486 let foldinfo = [ 'msg', msg['start'], msg['end'],
487 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
489 call add(info['msgs'], msg)
496 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
500 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
501 let body_start = len(info['disp']) + 1
507 if match(line, g:notmuch_show_message_begin_regexp) != -1
508 let msg['start'] = len(info['disp']) + 1
510 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
513 let msg['depth'] = m[2]
514 let msg['filename'] = m[3]
522 call add(info['folds'], foldinfo[0:2])
523 let info['foldtext'][foldinfo[1]] = foldinfo[3]
529 function! s:NM_cmd_show_mkfolds()
530 let info = b:nm_raw_info
532 for afold in info['folds']
533 exec printf('%d,%dfold', afold[1], afold[2])
534 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
535 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
536 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
537 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
538 exec printf('%dfoldclose', afold[1])
540 exec printf('%dfoldopen', afold[1])
545 function! s:NM_cmd_show_mksyntax()
546 let info = b:nm_raw_info
548 for msg in info['msgs']
550 let start = msg['start']
551 let hdr_start = msg['hdr_start']
552 let body_start = msg['body_start']
554 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
555 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
556 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
560 function! NM_cmd_show_foldtext()
561 let foldtext = b:nm_raw_info['foldtext']
562 return foldtext[v:foldstart]
566 " --- notmuch helper functions {{{1
568 function! s:NM_newBuffer(ft, content)
570 setlocal buftype=nofile readonly modifiable
573 setlocal nomodifiable
574 execute printf('set filetype=notmuch-%s', a:ft)
575 execute printf('set syntax=notmuch-%s', a:ft)
578 function! s:NM_run(args)
579 let cmd = g:notmuch_cmd . ' ' . join(a:args) . '< /dev/null'
580 let out = system(cmd)
583 echo substitute(out, '\n*$', '', '')
591 " --- process and set the defaults {{{1
593 function! NM_set_defaults(force)
594 for [key, dflt] in items(s:notmuch_defaults)
596 if !a:force && exists(key) && type(dflt) == type(eval(key))
598 elseif type(dflt) == type(0)
599 let cmd = printf('let %s = %d', key, dflt)
600 elseif type(dflt) == type('')
601 let cmd = printf('let %s = ''%s''', key, dflt)
602 "elseif type(dflt) == type([])
603 " let cmd = printf('let %s = %s', key, string(dflt))
605 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
606 \ a:force, key, string(dflt))
612 call NM_set_defaults(0)
614 " for some reason NM_set_defaults() didn't work for arrays...
615 if !exists('g:notmuch_show_headers')
616 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
618 if !exists('g:notmuch_initial_search_words')
619 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
623 " --- assign keymaps {{{1
625 function! s:NM_set_map(maps)
626 for [key, code] in items(a:maps)
627 exec printf('nnoremap <buffer> %s %s', key, code)
631 " --- command handler {{{1
633 function! NotMuch(args)
635 if exists('b:nm_search_words')
636 let words = b:nm_search_words
638 let words = g:notmuch_initial_search_words
640 call <SID>NM_cmd_search(words)
646 let words = split(a:args)
647 " TODO: handle commands passed as arguments
649 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
656 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
657 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
659 " --- hacks, only for development :) {{{1
661 nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
663 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :