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>
21 " Contributors: Felipe Contreras <felipe.contreras@gmail.com>,
22 " Peter Hartman <peterjohnhartman@gmail.com>
24 " --- configuration defaults {{{1
26 let s:notmuch_defaults = {
27 \ 'g:notmuch_cmd': 'notmuch' ,
28 \ 'g:notmuch_sendmail': 'sendmail' ,
29 \ 'g:notmuch_debug': 0 ,
31 \ 'g:notmuch_search_newest_first': 1 ,
32 \ 'g:notmuch_search_from_column_width': 20 ,
34 \ 'g:notmuch_show_fold_signatures': 1 ,
35 \ 'g:notmuch_show_fold_citations': 1 ,
36 \ 'g:notmuch_show_fold_bodies': 0 ,
37 \ 'g:notmuch_show_fold_headers': 1 ,
39 \ 'g:notmuch_show_message_begin_regexp': '
\fmessage{' ,
40 \ 'g:notmuch_show_message_end_regexp': '
\fmessage}' ,
41 \ 'g:notmuch_show_header_begin_regexp': '
\fheader{' ,
42 \ 'g:notmuch_show_header_end_regexp': '
\fheader}' ,
43 \ 'g:notmuch_show_body_begin_regexp': '
\fbody{' ,
44 \ 'g:notmuch_show_body_end_regexp': '
\fbody}' ,
45 \ 'g:notmuch_show_attachment_begin_regexp': '
\fattachment{' ,
46 \ 'g:notmuch_show_attachment_end_regexp': '
\fattachment}' ,
47 \ 'g:notmuch_show_part_begin_regexp': '
\fpart{' ,
48 \ 'g:notmuch_show_part_end_regexp': '
\fpart}' ,
49 \ 'g:notmuch_show_marker_regexp': '
\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
51 \ 'g:notmuch_show_message_parse_regexp': '\(id:[^ ]*\) depth:\([0-9]*\) match:\([0-9]*\) filename:\(.*\)$',
52 \ 'g:notmuch_show_tags_regexp': '(\([^)]*\))$' ,
54 \ 'g:notmuch_show_signature_regexp': '^\(-- \?\|_\+\)$' ,
55 \ 'g:notmuch_show_signature_lines_max': 12 ,
57 \ 'g:notmuch_show_citation_regexp': '^\s*>' ,
59 \ 'g:notmuch_compose_insert_mode_start': 1 ,
60 \ 'g:notmuch_compose_header_help': 1 ,
61 \ 'g:notmuch_compose_temp_file_dir': '~/.notmuch/compose/' ,
64 " defaults for g:notmuch_initial_search_words
65 " override with: let g:notmuch_initial_search_words = [ ... ]
66 let s:notmuch_initial_search_words_defaults = [
67 \ 'tag:inbox and tag:unread',
70 " defaults for g:notmuch_show_headers
71 " override with: let g:notmuch_show_headers = [ ... ]
72 let s:notmuch_show_headers_defaults = [
80 " defaults for g:notmuch_folders
81 " override with: let g:notmuch_folders = [ ... ]
82 let s:notmuch_folders_defaults = [
83 \ [ 'new', 'tag:inbox and tag:unread' ],
84 \ [ 'inbox', 'tag:inbox' ],
85 \ [ 'unread', 'tag:unread' ],
88 " defaults for g:notmuch_signature
89 " override with: let g:notmuch_signature = [ ... ]
90 let s:notmuch_signature_defaults = [
93 \ 'email sent from notmuch.vim plugin'
96 " defaults for g:notmuch_compose_headers
97 " override with: let g:notmuch_compose_headers = [ ... ]
98 let s:notmuch_compose_headers_defaults = [
106 " --- keyboard mapping definitions {{{1
108 " --- --- bindings for folders mode {{{2
110 let g:notmuch_folders_maps = {
111 \ 'm': ':call <SID>NM_new_mail()<CR>',
112 \ 's': ':call <SID>NM_search_prompt()<CR>',
113 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
114 \ '=': ':call <SID>NM_folders_refresh_view()<CR>',
115 \ '<Enter>': ':call <SID>NM_folders_show_search()<CR>',
118 " --- --- bindings for search screen {{{2
119 let g:notmuch_search_maps = {
120 \ '<Space>': ':call <SID>NM_search_show_thread(0)<CR>',
121 \ '<Enter>': ':call <SID>NM_search_show_thread(1)<CR>',
122 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
123 \ 'a': ':call <SID>NM_search_archive_thread()<CR>',
124 \ 'A': ':call <SID>NM_search_mark_read_then_archive_thread()<CR>',
125 \ 'f': ':call <SID>NM_search_filter()<CR>',
126 \ 'm': ':call <SID>NM_new_mail()<CR>',
127 \ 'o': ':call <SID>NM_search_toggle_order()<CR>',
128 \ 'r': ':call <SID>NM_search_reply_to_thread()<CR>',
129 \ 's': ':call <SID>NM_search_prompt()<CR>',
130 \ ',s': ':call <SID>NM_search_edit()<CR>',
131 \ 't': ':call <SID>NM_search_filter_by_tag()<CR>',
132 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
133 \ '+': ':call <SID>NM_search_add_tags([])<CR>',
134 \ '-': ':call <SID>NM_search_remove_tags([])<CR>',
135 \ '=': ':call <SID>NM_search_refresh_view()<CR>',
136 \ '?': ':echo <SID>NM_search_thread_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
139 " --- --- bindings for show screen {{{2
140 let g:notmuch_show_maps = {
141 \ '<C-P>': ':call <SID>NM_show_previous(1, 0)<CR>',
142 \ '<C-N>': ':call <SID>NM_show_next(1, 0)<CR>',
143 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
144 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
145 \ 's': ':call <SID>NM_search_prompt()<CR>',
147 \ 'b': ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
148 \ 'c': ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
149 \ 'h': ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
150 \ 'i': ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
152 \ 'a': ':call <SID>NM_show_archive_thread()<CR>',
153 \ 'A': ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
154 \ 'N': ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
155 \ 'v': ':call <SID>NM_show_view_all_mime_parts()<CR>',
156 \ '+': ':call <SID>NM_show_add_tag()<CR>',
157 \ '-': ':call <SID>NM_show_remove_tag()<CR>',
158 \ '<Space>': ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
159 \ '\|': ':call <SID>NM_show_pipe_message()<CR>',
161 \ '<S-Tab>': ':call <SID>NM_show_previous_fold()<CR>',
162 \ '<Tab>': ':call <SID>NM_show_next_fold()<CR>',
163 \ '<Enter>': ':call <SID>NM_show_toggle_fold()<CR>',
165 \ 'r': ':call <SID>NM_show_reply()<CR>',
166 \ 'm': ':call <SID>NM_new_mail()<CR>',
167 \ '?': ':echo <SID>NM_show_message_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
170 " --- --- bindings for compose screen {{{2
171 let g:notmuch_compose_nmaps = {
172 \ ',s': ':call <SID>NM_compose_send()<CR>',
173 \ ',a': ':call <SID>NM_compose_attach()<CR>',
174 \ ',q': ':call <SID>NM_kill_this_buffer()<CR>',
175 \ '<Tab>': ':call <SID>NM_compose_next_entry_area()<CR>',
177 let g:notmuch_compose_imaps = {
178 \ '<Tab>': '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
181 " --- implement folders screen {{{1
183 function! s:NM_cmd_folders(words)
185 throw 'Not expecting any arguments for folders command.'
190 for entry in g:notmuch_folders
191 let [ name, search ] = entry
192 let data = s:NM_run(cmd + [search])
193 let cnt = matchlist(data, '\(\d\+\)')[1]
194 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
195 call add(searches, search)
198 call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
199 let b:nm_searches = searches
200 let b:nm_timestamp = reltime()
202 call <SID>NM_cmd_folders_mksyntax()
203 call <SID>NM_set_map('n', g:notmuch_folders_maps)
208 function! s:NM_cmd_folders_mksyntax()
211 " --- --- folders screen action functions {{{2
213 function! s:NM_folders_refresh_view()
215 setlocal bufhidden=delete
216 call s:NM_cmd_folders([])
217 exec printf('norm %dG', lno)
220 function! s:NM_folders_show_search()
222 let search = b:nm_searches[line-1]
224 let prev_bufnr = bufnr('%')
225 setlocal bufhidden=hide
226 call <SID>NM_cmd_search([search])
227 setlocal bufhidden=delete
228 let b:nm_prev_bufnr = prev_bufnr
232 " --- implement search screen {{{1
234 function! s:NM_cmd_search(words)
236 if g:notmuch_search_newest_first
237 let cmd = cmd + ['--sort=newest-first']
239 let cmd = cmd + ['--sort=oldest-first']
241 let data = s:NM_run(cmd + a:words)
242 let lines = split(data, "\n")
243 let disp = copy(lines)
244 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
246 call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
247 let b:nm_raw_lines = lines
248 let b:nm_search_words = a:words
250 call <SID>NM_set_map('n', g:notmuch_search_maps)
254 function! s:NM_cmd_search_fmtline(line)
255 let m = matchlist(a:line, '^\(thread:\S\+\)\s\(.\{12\}\) \[\(\d\+\)/\d\+\] \([^;]\+\); \%(\[[^\[]\+\] \)*\(.*\) (\([^(]*\))$')
257 return 'ERROR PARSING: ' . a:line
259 let max = g:notmuch_search_from_column_width
261 for at in split(m[4], ", ")
262 let p = min([stridx(at, "."), stridx(at, "@")])
263 call insert(flist, tolower(at[0:p - 1]))
265 let from = join(flist, ", ")
266 return printf("%-12s %3s %-20.20s | %s (%s)", m[2], m[3], from, m[5], m[6])
269 " --- --- search screen action functions {{{2
271 function! s:NM_search_show_thread(everything)
272 let words = [ <SID>NM_search_thread_id() ]
273 if !a:everything && exists('b:nm_search_words')
274 call extend(words, ['AND', '('])
275 call extend(words, b:nm_search_words)
278 call <SID>NM_cmd_show(words)
279 let b:nm_show_everything = a:everything
282 function! s:NM_search_prompt()
283 " TODO: input() can support completion
284 let text = input('NotMuch Search: ')
286 let tags = split(text)
288 let tags = s:notmuch_initial_search_words_defaults
290 let prev_bufnr = bufnr('%')
291 if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
292 " TODO: we intend to replace the current buffer,
293 " ... maybe we could just clear it
294 let prev_bufnr = b:nm_prev_bufnr
295 setlocal bufhidden=delete
297 setlocal bufhidden=hide
299 call <SID>NM_cmd_search(tags)
300 setlocal bufhidden=delete
301 let b:nm_prev_bufnr = prev_bufnr
304 function! s:NM_search_edit()
305 " TODO: input() can support completion
306 let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
308 call <SID>NM_cmd_search(split(text))
312 function! s:NM_search_archive_thread()
313 call <SID>NM_tag([], ['-inbox'])
317 function! s:NM_search_mark_read_then_archive_thread()
318 call <SID>NM_tag([], ['-unread', '-inbox'])
322 function! s:NM_search_filter()
323 call <SID>NM_search_filter_helper('Filter: ', '', '')
326 function! s:NM_search_filter_by_tag()
327 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
330 function! s:NM_search_filter_helper(prompt, prefix, joiner)
331 " TODO: input() can support completion
332 let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
337 let tags = b:nm_search_words + ['AND']
338 \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
340 let prev_bufnr = bufnr('%')
341 setlocal bufhidden=hide
342 call <SID>NM_cmd_search(tags)
343 setlocal bufhidden=delete
344 let b:nm_prev_bufnr = prev_bufnr
347 function! s:NM_search_toggle_order()
348 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
349 " FIXME: maybe this would be better done w/o reading re-reading the lines
350 " reversing the b:nm_raw_lines and the buffer lines would be better
351 call <SID>NM_search_refresh_view()
354 function! s:NM_search_reply_to_thread()
356 call add(cmd, <SID>NM_search_thread_id())
358 call extend(cmd, <SID>NM_get_search_words())
360 let data = <SID>NM_run(cmd)
361 let lines = split(data, "\n")
362 call <SID>NM_newComposeBuffer(lines, 0)
365 function! s:NM_search_add_tags(tags)
366 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
369 function! s:NM_search_remove_tags(tags)
370 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
373 function! s:NM_search_refresh_view()
375 let prev_bufnr = b:nm_prev_bufnr
376 setlocal bufhidden=delete
377 call <SID>NM_cmd_search(b:nm_search_words)
378 let b:nm_prev_bufnr = prev_bufnr
379 " FIXME: should find the line of the thread we were on if possible
380 exec printf('norm %dG', lno)
383 " --- --- search screen helper functions {{{2
385 function! s:NM_search_thread_id()
386 if !exists('b:nm_raw_lines')
387 throw 'Eeek! no b:nm_raw_lines'
389 let mnum = line('.') - 1
390 if len(b:nm_raw_lines) <= mnum
393 let info = b:nm_raw_lines[mnum]
394 let what = split(info, '\s\+')[0]
398 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
399 if type(a:intags) != type([]) || len(a:intags) == 0
400 " TODO: input() can support completion
401 let text = input(a:prompt)
405 let tags = split(text, ' ')
409 call map(tags, 'a:prefix . v:val')
410 call <SID>NM_tag([], tags)
413 " --- implement show screen {{{1
415 function! s:NM_cmd_show(words)
416 let prev_bufnr = bufnr('%')
417 let data = s:NM_run(['show', '--entire-thread'] + a:words)
418 let lines = split(data, "\n")
420 let info = s:NM_cmd_show_parse(lines)
422 setlocal bufhidden=hide
423 call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
424 setlocal bufhidden=delete
425 let b:nm_search_words = a:words
426 let b:nm_raw_info = info
427 let b:nm_prev_bufnr = prev_bufnr
429 call <SID>NM_cmd_show_mkfolds()
430 call <SID>NM_cmd_show_mksyntax()
431 call <SID>NM_set_map('n', g:notmuch_show_maps)
432 setlocal foldtext=NM_cmd_show_foldtext()
434 setlocal foldcolumn=6
438 function! s:NM_show_previous(can_change_thread, find_matching)
439 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
440 let info = b:nm_raw_info
442 for msg in reverse(copy(info['msgs']))
443 if a:find_matching && msg['match'] == '0'
446 if lnum <= msg['start']
450 exec printf('norm %dGzt', msg['start'])
451 " TODO: try to fit the message on screen
454 if !a:can_change_thread
457 call <SID>NM_kill_this_buffer()
460 call <SID>NM_search_show_thread(everything)
462 call <SID>NM_show_previous(0, a:find_matching)
464 echo 'No more messages.'
468 function! s:NM_show_next(can_change_thread, find_matching)
469 let info = b:nm_raw_info
471 for msg in info['msgs']
472 if a:find_matching && msg['match'] == '0'
475 if lnum >= msg['start']
479 exec printf('norm %dGzt', msg['start'])
480 " TODO: try to fit the message on screen
483 if a:can_change_thread
484 call <SID>NM_show_next_thread()
488 function! s:NM_show_next_thread()
489 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
490 call <SID>NM_kill_this_buffer()
491 if line('.') != line('$')
493 call <SID>NM_search_show_thread(everything)
495 echo 'No more messages.'
499 function! s:NM_show_archive_thread()
500 call <SID>NM_tag(b:nm_search_words, ['-inbox'])
501 call <SID>NM_show_next_thread()
504 function! s:NM_show_mark_read_then_archive_thread()
505 call <SID>NM_tag(b:nm_search_words, ['-unread', '-inbox'])
506 call <SID>NM_show_next_thread()
509 function! s:NM_show_mark_read_then_next_open_message()
510 echo 'not implemented'
513 function! s:NM_show_previous_message()
514 echo 'not implemented'
517 function! s:NM_show_reply()
519 call add(cmd, <SID>NM_show_message_id())
521 call extend(cmd, <SID>NM_get_search_words())
523 let data = <SID>NM_run(cmd)
524 let lines = split(data, "\n")
525 call <SID>NM_newComposeBuffer(lines, 0)
528 function! s:NM_show_view_all_mime_parts()
529 echo 'not implemented'
532 function! s:NM_show_view_raw_message()
533 echo 'not implemented'
536 function! s:NM_show_add_tag()
537 echo 'not implemented'
540 function! s:NM_show_remove_tag()
541 echo 'not implemented'
544 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
545 " otherwise go to next message
546 " any message that is viewed entirely has inbox and unread tags removed
547 function! s:NM_show_advance_marking_read_and_archiving()
548 let advance_tags = ['unread', 'inbox']
550 let vis_top = line('w0')
551 let vis_bot = line('w$')
553 let msg_top = <SID>NM_show_get_message_for_line(vis_top)
554 if !has_key(msg_top,'id')
555 throw "No top visible message."
558 " if the top message is the last message, just expunge the entire thread and move on
559 if msg_top['end'] == line('$')
561 for msg in b:nm_raw_info['msgs']
562 if has_key(msg,'match') && msg['match'] != '0'
563 call add(ids, msg['id'])
566 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
568 \ + <SID>NM_combine_tags('', ids, 'OR', '()')
569 call map(advance_tags, '"+" . v:val')
570 call <SID>NM_tag(filter, advance_tags)
571 call <SID>NM_show_next(1, 1)
575 let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
576 if !has_key(msg_bot,'id')
577 throw "No bottom visible message."
580 " if entire message fits on the screen, read/archive it, move to the next one
581 if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
582 exec printf('norm %dG', vis_top)
583 call <SID>NM_show_next(0, 1)
584 if has_key(msg_top,'match') && msg_top['match'] != '0'
586 " do this last to hide the latency
587 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
588 \ + ['AND', msg_top['id']]
589 call map(advance_tags, '"-" . v:val')
590 call <SID>NM_tag(filter, advance_tags)
595 " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
596 let jmp = winheight(winnr()) / 2
597 let max = msg_bot['end'] - vis_bot
601 exec printf('norm %dGzt', vis_top + jmp)
605 function! s:NM_show_pipe_message()
606 echo 'not implemented'
609 function! s:NM_show_previous_fold()
610 echo 'not implemented'
613 function! s:NM_show_next_fold()
614 echo 'not implemented'
617 function! s:NM_show_toggle_fold()
618 echo 'not implemented'
622 " --- --- show screen helper functions {{{2
624 function! s:NM_show_get_message_for_line(line)
625 for msg in b:nm_raw_info['msgs']
626 if a:line > msg['end']
634 function! s:NM_show_message_id()
635 if !exists('b:nm_raw_info')
636 throw 'Eeek! no b:nm_raw_info'
638 let msg = <SID>NM_show_get_message_for_line(line('.'))
645 function! s:NM_show_fold_toggle(key, type, fold)
646 let info = b:nm_raw_info
651 for fld in info['folds']
656 "let msg = info['msgs'][idx]
657 "if has_key(msg,'match') && msg['match'] == '0'
660 let cls = foldclosed(fld[1])
661 if cls != -1 && cls != fld[1]
664 exec printf('%dfold%s', fld[1], act)
666 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
670 " s:NM_cmd_show_parse returns the following dictionary:
671 " 'disp': lines to display
672 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
673 " 'folds': fold info arrays [ type, start, end ]
674 " 'foldtext': fold text indexed by start line
675 function! s:NM_cmd_show_parse(inlines)
676 let info = { 'disp': [],
695 for line in a:inlines
696 let inlnum = inlnum + 1
702 if match(line, g:notmuch_show_part_end_regexp) != -1
703 let part_end = len(info['disp'])
705 call add(info['disp'], line)
708 if in_part == 'text/plain'
709 if !part_end && mode_type == ''
710 if match(line, g:notmuch_show_signature_regexp) != -1
711 let mode_type = 'sig'
712 let mode_start = len(info['disp'])
713 elseif match(line, g:notmuch_show_citation_regexp) != -1
714 let mode_type = 'cit'
715 let mode_start = len(info['disp'])
717 elseif mode_type == 'cit'
718 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
719 let outlnum = len(info['disp'])
720 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
721 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
724 elseif mode_type == 'sig'
725 let outlnum = len(info['disp'])
726 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
729 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
730 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
737 " FIXME: this is a hack for handling two folds being added for one line
738 " we should handle addinga fold in a function
739 if len(foldinfo) && foldinfo[1] < foldinfo[2]
740 call add(info['folds'], foldinfo[0:3])
741 let info['foldtext'][foldinfo[1]] = foldinfo[4]
744 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
745 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
747 call add(info['disp'], '')
751 if !has_key(msg,'body_start')
752 let msg['body_start'] = len(info['disp']) + 1
754 if match(line, g:notmuch_show_body_end_regexp) != -1
755 let body_end = len(info['disp'])
756 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
757 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
761 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
762 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
763 let in_part = 'unknown'
767 call add(info['disp'],
768 \ printf('--- %s ---', in_part))
769 let part_start = len(info['disp']) + 1
774 let msg['descr'] = line
775 call add(info['disp'], line)
777 let msg['hdr_start'] = len(info['disp']) + 1
780 if match(line, g:notmuch_show_header_end_regexp) != -1
781 let hdr_start = msg['hdr_start']+1
782 let hdr_end = len(info['disp'])
783 let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
784 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
785 let msg['header'] = hdr
789 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
792 if match(g:notmuch_show_headers, m[1]) != -1
793 call add(info['disp'], line)
800 if match(line, g:notmuch_show_message_end_regexp) != -1
801 let msg['end'] = len(info['disp'])
802 call add(info['disp'], '')
804 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
805 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
807 call add(info['msgs'], msg)
814 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
818 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
819 let body_start = len(info['disp']) + 1
825 if match(line, g:notmuch_show_message_begin_regexp) != -1
826 let msg['start'] = len(info['disp']) + 1
828 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
831 let msg['depth'] = m[2]
832 let msg['match'] = m[3]
833 let msg['filename'] = m[4]
840 if len(foldinfo) && foldinfo[1] < foldinfo[2]
841 call add(info['folds'], foldinfo[0:3])
842 let info['foldtext'][foldinfo[1]] = foldinfo[4]
848 function! s:NM_cmd_show_mkfolds()
849 let info = b:nm_raw_info
851 for afold in info['folds']
852 exec printf('%d,%dfold', afold[1], afold[2])
854 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
855 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
856 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
857 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
859 elseif afold[0] == 'msg'
861 let msg = info['msgs'][idx]
862 if has_key(msg,'match') && msg['match'] == '0'
866 exec printf('%dfold%s', afold[1], state)
870 function! s:NM_cmd_show_mksyntax()
871 let info = b:nm_raw_info
873 for msg in info['msgs']
875 let start = msg['start']
876 let hdr_start = msg['hdr_start']
877 let body_start = msg['body_start']
879 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
880 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
881 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
885 function! NM_cmd_show_foldtext()
886 let foldtext = b:nm_raw_info['foldtext']
887 return foldtext[v:foldstart]
891 " --- implement compose screen {{{1
893 function! s:NM_cmd_compose(words, body_lines)
895 let start_on_line = 0
899 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
901 throw 'Eeek! bad parameter ''' . string(word) . ''''
903 let key = substitute(m[1], '\<\w', '\U&', 'g')
904 if !has_key(hdrs, key)
908 call add(hdrs[key], m[2])
912 if !has_key(hdrs, 'From') || !len(hdrs['From'])
913 let me = <SID>NM_compose_get_user_email()
914 let hdrs['From'] = [ me ]
917 for key in g:notmuch_compose_headers
918 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
919 call add(lines, key . ': ' . text)
920 if !start_on_line && !strlen(text)
921 let start_on_line = len(lines)
925 for [key,val] in items(hdrs)
926 if match(g:notmuch_compose_headers, key) == -1
927 let line = key . ': ' . join(val, ', ')
928 call add(lines, line)
934 let start_on_line = len(lines) + 1
938 call extend(lines, a:body_lines)
940 call extend(lines, [ '', '' ])
943 call <SID>NM_newComposeBuffer(lines, start_on_line)
946 function! s:NM_compose_send()
947 call <SID>NM_assert_buffer_type('compose')
948 let fname = expand('%')
950 let line = getline(lnum)
952 while match(line, '^$') == -1
953 if !exists("hdr_starts") && match(line, '^Notmuch-Help:') == -1
954 let hdr_starts = lnum - 1
957 let line = getline(lnum)
959 let body_starts = lnum - 1
961 call append(body_starts, 'Date: ' . strftime('%a, %d %b %Y %H:%M:%S %z'))
962 exec printf(':0,%dd', hdr_starts)
965 let line = getline(1)
966 let m = matchlist(line, '^From:\s*\(.*\)\s*<\(.*\)>$')
970 let m = matchlist(line, '^From:\s*\(.*\)$')
974 let cmdtxt = g:notmuch_sendmail . ' -t -f ' . from . ' < ' . fname
975 let out = system(cmdtxt)
976 let err = v:shell_error
980 call <SID>NM_newBuffer('new', 'error',
981 \ "While running...\n" .
982 \ ' ' . cmdtxt . "\n" .
984 \ "Failed with...\n" .
985 \ substitute(out, '^', ' ', 'g'))
987 echo 'Eeek! unable to send mail'
992 if !exists('b:nm_prev_bufnr')
995 let prev_bufnr = b:nm_prev_bufnr
997 if prev_bufnr == bufnr('%')
998 exec printf("buffer %d", prev_bufnr)
1002 echo 'Mail sent successfully.'
1005 function! s:NM_compose_attach()
1006 echo 'not implemented'
1009 function! s:NM_compose_next_entry_area()
1010 let lnum = line('.')
1011 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1014 let line = getline(lnum)
1015 if match(line, '^\([^:]\+\):\s*$') == -1
1016 call cursor(lnum, strlen(line) + 1)
1019 while match(getline(lnum+1), '^\s') != -1
1022 call cursor(lnum, strlen(getline(lnum)) + 1)
1025 elseif lnum == hdr_end
1026 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1030 if !getbufvar(bufnr('.'), '&et')
1034 let shiftwidth = a:shiftwidth
1035 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1036 " we assume no one has shiftwidth set to more than 40 :)
1037 return ' '[0:shiftwidth]
1041 " --- --- compose screen helper functions {{{2
1043 function! s:NM_compose_get_user_email()
1044 " TODO: do this properly (still), i.e., allow for multiple email accounts
1045 let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1049 function! s:NM_compose_find_line_match(start, pattern, failure)
1051 let lend = line('$')
1053 if match(getline(lnum), a:pattern) != -1
1062 " --- notmuch helper functions {{{1
1064 function! s:NM_newBuffer(how, type, content)
1070 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1071 silent put=a:content
1073 setlocal nomodifiable
1074 execute printf('set filetype=notmuch-%s', a:type)
1075 execute printf('set syntax=notmuch-%s', a:type)
1076 let b:nm_type = a:type
1079 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1080 let fdir = expand(a:fdir)
1081 if !isdirectory(fdir)
1082 call mkdir(fdir, 'p')
1084 let file_name = <SID>NM_mktemp(fdir, a:fname)
1085 if writefile(a:lines, file_name)
1086 throw 'Eeek! couldn''t write to temporary file ' . file_name
1088 exec printf('edit %s', file_name)
1089 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1090 execute printf('set filetype=notmuch-%s', a:type)
1091 execute printf('set syntax=notmuch-%s', a:type)
1092 let b:nm_type = a:type
1095 function! s:NM_newComposeBuffer(lines, start_on_line)
1097 let start_on_line = a:start_on_line
1098 let real_hdr_start = 1
1099 if g:notmuch_compose_header_help
1101 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1102 \ 'Notmuch-Help: ,a - attach a file',
1103 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
1104 \ 'Notmuch-Help: ,q - abort the message',
1105 \ 'Notmuch-Help: <Tab> - skip through header lines',
1107 call extend(lines, help_lines, 0)
1108 let real_hdr_start = len(help_lines)
1109 if start_on_line > 0
1110 let start_on_line = start_on_line + len(help_lines)
1113 call extend(lines, g:notmuch_signature)
1116 let prev_bufnr = bufnr('%')
1117 setlocal bufhidden=hide
1118 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1120 setlocal bufhidden=hide
1121 let b:nm_prev_bufnr = prev_bufnr
1123 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1124 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1126 if start_on_line > 0 && start_on_line <= len(lines)
1127 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1129 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1130 call <SID>NM_compose_next_entry_area()
1133 if g:notmuch_compose_insert_mode_start
1136 echo 'Type your message, use <TAB> to jump to next header and then body.'
1139 function! s:NM_assert_buffer_type(type)
1140 if !exists('b:nm_type') || b:nm_type != a:type
1141 throw printf('Eeek! expected type %s, but got %s.', a:type,
1142 \ exists(b:nm_type) ? b:nm_type : 'something else')
1146 function! s:NM_mktemp(dir, name)
1147 let time_stamp = strftime('%Y%m%d-%H%M%S')
1148 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1149 " TODO: check if it exists, try again
1153 function! s:NM_shell_escape(word)
1154 " TODO: use shellescape()
1155 let word = substitute(a:word, '''', '\\''', 'g')
1156 return '''' . word . ''''
1159 " this function was taken from git.vim, then fixed up
1160 " http://github.com/motemen/git-vim
1161 function! s:NM_shell_split(cmd)
1162 let l:split_cmd = []
1166 let t = match(cmd, '\S', iStart)
1172 let iSpace = match(cmd, '\v(\s|$)', iStart)
1177 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1178 if iQuote1 > iSpace || iQuote1 < iStart
1179 let iEnd = iSpace - 1
1180 let l:split_cmd += [ cmd[iStart : iEnd] ]
1182 let q = cmd[iQuote1]
1183 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1184 if iQuote2 < iQuote1
1185 throw 'No matching ' . q . ' quote'
1188 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1192 let iStart = iEnd + 1
1199 function! s:NM_run(args)
1201 call map(words, 's:NM_shell_escape(v:val)')
1202 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1204 if exists('g:notmuch_debug') && g:notmuch_debug
1205 let start = reltime()
1206 let out = system(cmd)
1207 let err = v:shell_error
1208 let delta = reltime(start)
1210 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1212 let out = system(cmd)
1213 let err = v:shell_error
1218 echo substitute(out, '\n*$', '', '')
1226 " --- external mail handling helpers {{{1
1228 function! s:NM_new_mail()
1229 call <SID>NM_cmd_compose([], [])
1232 " --- tag manipulation helpers {{{1
1234 " used to combine an array of words with prefixes and separators
1236 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1237 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1238 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1241 if len(res) && strlen(a:separator)
1242 call add(res, a:separator)
1244 call add(res, a:word_prefix . word)
1246 if len(res) > 1 && strlen(a:brackets)
1247 if strlen(a:brackets) != 2
1248 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1250 call insert(res, a:brackets[0])
1251 call add(res, a:brackets[1])
1256 " --- other helpers {{{1
1258 function! s:NM_get_search_words()
1259 if !exists('b:nm_search_words')
1260 throw 'Eeek! no b:nm_search_words'
1262 return b:nm_search_words
1265 function! s:NM_kill_this_buffer()
1266 if exists('b:nm_prev_bufnr')
1267 let prev_bufnr = b:nm_prev_bufnr
1269 exec printf("buffer %d", prev_bufnr)
1271 echo "This is the last buffer; use :q<CR> to quit."
1275 function! s:NM_search_expand(arg)
1276 let word = expand(a:arg)
1277 let prev_bufnr = bufnr('%')
1278 setlocal bufhidden=hide
1279 call <SID>NM_cmd_search([word])
1280 setlocal bufhidden=delete
1281 let b:nm_prev_bufnr = prev_bufnr
1284 function! s:NM_tag(filter, tags)
1285 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1287 throw 'Eeek! I couldn''t find the thead id!'
1290 call extend(args, a:tags)
1291 call add(args, '--')
1292 call extend(args, filter)
1293 " TODO: handle errors
1294 call <SID>NM_run(args)
1297 " --- process and set the defaults {{{1
1299 function! NM_set_defaults(force)
1300 for [key, dflt] in items(s:notmuch_defaults)
1302 if !a:force && exists(key) && type(dflt) == type(eval(key))
1304 elseif type(dflt) == type(0)
1305 let cmd = printf('let %s = %d', key, dflt)
1306 elseif type(dflt) == type('')
1307 let cmd = printf('let %s = ''%s''', key, dflt)
1308 " FIXME: not sure why this didn't work when dflt is an array
1309 "elseif type(dflt) == type([])
1310 " let cmd = printf('let %s = %s', key, string(dflt))
1312 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1313 \ a:force, key, string(dflt))
1319 call NM_set_defaults(0)
1321 " for some reason NM_set_defaults() didn't work for arrays...
1322 if !exists('g:notmuch_show_headers')
1323 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1325 if !exists('g:notmuch_initial_search_words')
1326 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1328 if !exists('g:notmuch_folders')
1329 let g:notmuch_folders = s:notmuch_folders_defaults
1332 if !exists('g:notmuch_signature')
1333 let g:notmuch_signature = s:notmuch_signature_defaults
1335 if !exists('g:notmuch_compose_headers')
1336 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1339 " --- assign keymaps {{{1
1341 function! s:NM_set_map(type, maps)
1343 for [key, code] in items(a:maps)
1344 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1346 " --- this is a hack for development :)
1347 nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1350 " --- command handler {{{1
1352 function! NotMuch(args)
1355 let args = 'folders'
1358 let words = <SID>NM_shell_split(args)
1359 if words[0] == 'folders' || words[0] == 'f'
1360 let words = words[1:]
1361 call <SID>NM_cmd_folders(words)
1363 elseif words[0] == 'search' || words[0] == 's'
1365 let words = words[1:]
1366 elseif exists('b:nm_search_words')
1367 let words = b:nm_search_words
1369 let words = g:notmuch_initial_search_words
1371 call <SID>NM_cmd_search(words)
1373 elseif words[0] == 'show'
1374 echoe 'show is not yet implemented.'
1376 elseif words[0] == 'new' || words[0] == 'compose'
1377 let words = words[1:]
1378 call <SID>NM_cmd_compose(words, [])
1381 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1388 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1389 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1391 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :