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 \ 'I': ':call <SID>NM_show_mark_read_thread()<CR>',
153 \ 'a': ':call <SID>NM_show_archive_thread()<CR>',
154 \ 'A': ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
155 \ 'N': ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
156 \ 'v': ':call <SID>NM_show_view_all_mime_parts()<CR>',
157 \ '+': ':call <SID>NM_show_add_tag()<CR>',
158 \ '-': ':call <SID>NM_show_remove_tag()<CR>',
159 \ '<Space>': ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
160 \ '\|': ':call <SID>NM_show_pipe_message()<CR>',
162 \ '<S-Tab>': ':call <SID>NM_show_previous_fold()<CR>',
163 \ '<Tab>': ':call <SID>NM_show_next_fold()<CR>',
164 \ '<Enter>': ':call <SID>NM_show_toggle_fold()<CR>',
166 \ 'r': ':call <SID>NM_show_reply()<CR>',
167 \ 'm': ':call <SID>NM_new_mail()<CR>',
168 \ '?': ':echo <SID>NM_show_message_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
171 " --- --- bindings for compose screen {{{2
172 let g:notmuch_compose_nmaps = {
173 \ ',s': ':call <SID>NM_compose_send()<CR>',
174 \ ',a': ':call <SID>NM_compose_attach()<CR>',
175 \ ',q': ':call <SID>NM_kill_this_buffer()<CR>',
176 \ '<Tab>': ':call <SID>NM_compose_next_entry_area()<CR>',
178 let g:notmuch_compose_imaps = {
179 \ '<Tab>': '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
182 " --- implement folders screen {{{1
184 function! s:NM_cmd_folders(words)
186 throw 'Not expecting any arguments for folders command.'
191 for entry in g:notmuch_folders
192 let [ name, search ] = entry
193 let data = s:NM_run(cmd + [search])
194 let cnt = matchlist(data, '\(\d\+\)')[1]
195 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
196 call add(searches, search)
199 call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
200 let b:nm_searches = searches
201 let b:nm_timestamp = reltime()
203 call <SID>NM_cmd_folders_mksyntax()
204 call <SID>NM_set_map('n', g:notmuch_folders_maps)
209 function! s:NM_cmd_folders_mksyntax()
212 " --- --- folders screen action functions {{{2
214 function! s:NM_folders_refresh_view()
216 setlocal bufhidden=delete
217 call s:NM_cmd_folders([])
218 exec printf('norm %dG', lno)
221 function! s:NM_folders_show_search()
223 let search = b:nm_searches[line-1]
225 let prev_bufnr = bufnr('%')
226 setlocal bufhidden=hide
227 call <SID>NM_cmd_search([search])
228 setlocal bufhidden=delete
229 let b:nm_prev_bufnr = prev_bufnr
233 " --- implement search screen {{{1
235 function! s:NM_cmd_search(words)
237 if g:notmuch_search_newest_first
238 let cmd = cmd + ['--sort=newest-first']
240 let cmd = cmd + ['--sort=oldest-first']
242 let data = s:NM_run(cmd + a:words)
243 let lines = split(data, "\n")
244 let disp = copy(lines)
245 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
247 call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
248 let b:nm_raw_lines = lines
249 let b:nm_search_words = a:words
251 call <SID>NM_set_map('n', g:notmuch_search_maps)
255 function! s:NM_cmd_search_fmtline(line)
256 let m = matchlist(a:line, '^\(thread:\S\+\)\s\(.\{12\}\) \[\(\d\+\)/\d\+\] \([^;]\+\); \%(\[[^\[]\+\] \)*\(.*\) (\([^(]*\))$')
258 return 'ERROR PARSING: ' . a:line
260 let max = g:notmuch_search_from_column_width
262 for at in split(m[4], ", ")
263 let p = min([stridx(at, "."), stridx(at, "@")])
264 call insert(flist, tolower(at[0:p - 1]))
266 let from = join(flist, ", ")
267 return printf("%-12s %3s %-20.20s | %s (%s)", m[2], m[3], from, m[5], m[6])
270 " --- --- search screen action functions {{{2
272 function! s:NM_search_show_thread(everything)
273 let words = [ <SID>NM_search_thread_id() ]
274 if !a:everything && exists('b:nm_search_words')
275 call extend(words, ['AND', '('])
276 call extend(words, b:nm_search_words)
279 call <SID>NM_cmd_show(words)
280 let b:nm_show_everything = a:everything
283 function! s:NM_search_prompt()
284 " TODO: input() can support completion
285 let text = input('NotMuch Search: ')
287 let tags = split(text)
289 let tags = s:notmuch_initial_search_words_defaults
291 let prev_bufnr = bufnr('%')
292 if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
293 " TODO: we intend to replace the current buffer,
294 " ... maybe we could just clear it
295 let prev_bufnr = b:nm_prev_bufnr
296 setlocal bufhidden=delete
298 setlocal bufhidden=hide
300 call <SID>NM_cmd_search(tags)
301 setlocal bufhidden=delete
302 let b:nm_prev_bufnr = prev_bufnr
305 function! s:NM_search_edit()
306 " TODO: input() can support completion
307 let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
309 call <SID>NM_cmd_search(split(text))
313 function! s:NM_search_archive_thread()
314 call <SID>NM_tag([], ['-inbox'])
318 function! s:NM_search_mark_read_then_archive_thread()
319 call <SID>NM_tag([], ['-unread', '-inbox'])
323 function! s:NM_search_filter()
324 call <SID>NM_search_filter_helper('Filter: ', '', '')
327 function! s:NM_search_filter_by_tag()
328 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
331 function! s:NM_search_filter_helper(prompt, prefix, joiner)
332 " TODO: input() can support completion
333 let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
338 let tags = b:nm_search_words + ['AND']
339 \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
341 let prev_bufnr = bufnr('%')
342 setlocal bufhidden=hide
343 call <SID>NM_cmd_search(tags)
344 setlocal bufhidden=delete
345 let b:nm_prev_bufnr = prev_bufnr
348 function! s:NM_search_toggle_order()
349 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
350 " FIXME: maybe this would be better done w/o reading re-reading the lines
351 " reversing the b:nm_raw_lines and the buffer lines would be better
352 call <SID>NM_search_refresh_view()
355 function! s:NM_search_reply_to_thread()
357 call add(cmd, <SID>NM_search_thread_id())
359 call extend(cmd, <SID>NM_get_search_words())
361 let data = <SID>NM_run(cmd)
362 let lines = split(data, "\n")
363 call <SID>NM_newComposeBuffer(lines, 0)
366 function! s:NM_search_add_tags(tags)
367 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
370 function! s:NM_search_remove_tags(tags)
371 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
374 function! s:NM_search_refresh_view()
376 let prev_bufnr = b:nm_prev_bufnr
377 setlocal bufhidden=delete
378 call <SID>NM_cmd_search(b:nm_search_words)
379 let b:nm_prev_bufnr = prev_bufnr
380 " FIXME: should find the line of the thread we were on if possible
381 exec printf('norm %dG', lno)
384 " --- --- search screen helper functions {{{2
386 function! s:NM_search_thread_id()
387 if !exists('b:nm_raw_lines')
388 throw 'Eeek! no b:nm_raw_lines'
390 let mnum = line('.') - 1
391 if len(b:nm_raw_lines) <= mnum
394 let info = b:nm_raw_lines[mnum]
395 let what = split(info, '\s\+')[0]
399 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
400 if type(a:intags) != type([]) || len(a:intags) == 0
401 " TODO: input() can support completion
402 let text = input(a:prompt)
406 let tags = split(text, ' ')
410 call map(tags, 'a:prefix . v:val')
411 call <SID>NM_tag([], tags)
414 " --- implement show screen {{{1
416 function! s:NM_cmd_show(words)
417 let prev_bufnr = bufnr('%')
418 let data = s:NM_run(['show', '--entire-thread'] + a:words)
419 let lines = split(data, "\n")
421 let info = s:NM_cmd_show_parse(lines)
423 setlocal bufhidden=hide
424 call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
425 setlocal bufhidden=delete
426 let b:nm_search_words = a:words
427 let b:nm_raw_info = info
428 let b:nm_prev_bufnr = prev_bufnr
430 call <SID>NM_cmd_show_mkfolds()
431 call <SID>NM_cmd_show_mksyntax()
432 call <SID>NM_set_map('n', g:notmuch_show_maps)
433 setlocal foldtext=NM_cmd_show_foldtext()
435 setlocal foldcolumn=6
439 function! s:NM_show_previous(can_change_thread, find_matching)
440 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
441 let info = b:nm_raw_info
443 for msg in reverse(copy(info['msgs']))
444 if a:find_matching && msg['match'] == '0'
447 if lnum <= msg['start']
451 exec printf('norm %dGzt', msg['start'])
452 " TODO: try to fit the message on screen
455 if !a:can_change_thread
458 call <SID>NM_kill_this_buffer()
461 call <SID>NM_search_show_thread(everything)
463 call <SID>NM_show_previous(0, a:find_matching)
465 echo 'No more messages.'
469 function! s:NM_show_next(can_change_thread, find_matching)
470 let info = b:nm_raw_info
472 for msg in info['msgs']
473 if a:find_matching && msg['match'] == '0'
476 if lnum >= msg['start']
480 exec printf('norm %dGzt', msg['start'])
481 " TODO: try to fit the message on screen
484 if a:can_change_thread
485 call <SID>NM_show_next_thread()
489 function! s:NM_show_next_thread()
490 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
491 call <SID>NM_kill_this_buffer()
492 if line('.') != line('$')
494 call <SID>NM_search_show_thread(everything)
496 echo 'No more messages.'
500 function! s:NM_show_mark_read_thread()
501 call <SID>NM_tag(b:nm_search_words, ['-unread'])
502 call <SID>NM_show_next_thread()
505 function! s:NM_show_archive_thread()
506 call <SID>NM_tag(b:nm_search_words, ['-inbox'])
507 call <SID>NM_show_next_thread()
510 function! s:NM_show_mark_read_then_archive_thread()
511 call <SID>NM_tag(b:nm_search_words, ['-unread', '-inbox'])
512 call <SID>NM_show_next_thread()
515 function! s:NM_show_mark_read_then_next_open_message()
516 echo 'not implemented'
519 function! s:NM_show_previous_message()
520 echo 'not implemented'
523 function! s:NM_show_reply()
525 call add(cmd, <SID>NM_show_message_id())
527 call extend(cmd, <SID>NM_get_search_words())
529 let data = <SID>NM_run(cmd)
530 let lines = split(data, "\n")
531 call <SID>NM_newComposeBuffer(lines, 0)
534 function! s:NM_show_view_all_mime_parts()
535 echo 'not implemented'
538 function! s:NM_show_view_raw_message()
539 echo 'not implemented'
542 function! s:NM_show_add_tag()
543 echo 'not implemented'
546 function! s:NM_show_remove_tag()
547 echo 'not implemented'
550 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
551 " otherwise go to next message
552 " any message that is viewed entirely has inbox and unread tags removed
553 function! s:NM_show_advance_marking_read_and_archiving()
554 let advance_tags = ['unread', 'inbox']
556 let vis_top = line('w0')
557 let vis_bot = line('w$')
559 let msg_top = <SID>NM_show_get_message_for_line(vis_top)
560 if !has_key(msg_top,'id')
561 throw "No top visible message."
564 " if the top message is the last message, just expunge the entire thread and move on
565 if msg_top['end'] == line('$')
567 for msg in b:nm_raw_info['msgs']
568 if has_key(msg,'match') && msg['match'] != '0'
569 call add(ids, msg['id'])
572 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
574 \ + <SID>NM_combine_tags('', ids, 'OR', '()')
575 call map(advance_tags, '"+" . v:val')
576 call <SID>NM_tag(filter, advance_tags)
577 call <SID>NM_show_next(1, 1)
581 let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
582 if !has_key(msg_bot,'id')
583 throw "No bottom visible message."
586 " if entire message fits on the screen, read/archive it, move to the next one
587 if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
588 exec printf('norm %dG', vis_top)
589 call <SID>NM_show_next(0, 1)
590 if has_key(msg_top,'match') && msg_top['match'] != '0'
592 " do this last to hide the latency
593 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
594 \ + ['AND', msg_top['id']]
595 call map(advance_tags, '"-" . v:val')
596 call <SID>NM_tag(filter, advance_tags)
601 " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
602 let jmp = winheight(winnr()) / 2
603 let max = msg_bot['end'] - vis_bot
607 exec printf('norm %dGzt', vis_top + jmp)
611 function! s:NM_show_pipe_message()
612 echo 'not implemented'
615 function! s:NM_show_previous_fold()
616 echo 'not implemented'
619 function! s:NM_show_next_fold()
620 echo 'not implemented'
623 function! s:NM_show_toggle_fold()
624 echo 'not implemented'
628 " --- --- show screen helper functions {{{2
630 function! s:NM_show_get_message_for_line(line)
631 for msg in b:nm_raw_info['msgs']
632 if a:line > msg['end']
640 function! s:NM_show_message_id()
641 if !exists('b:nm_raw_info')
642 throw 'Eeek! no b:nm_raw_info'
644 let msg = <SID>NM_show_get_message_for_line(line('.'))
651 function! s:NM_show_fold_toggle(key, type, fold)
652 let info = b:nm_raw_info
657 for fld in info['folds']
662 "let msg = info['msgs'][idx]
663 "if has_key(msg,'match') && msg['match'] == '0'
666 let cls = foldclosed(fld[1])
667 if cls != -1 && cls != fld[1]
670 exec printf('%dfold%s', fld[1], act)
672 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
676 " s:NM_cmd_show_parse returns the following dictionary:
677 " 'disp': lines to display
678 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
679 " 'folds': fold info arrays [ type, start, end ]
680 " 'foldtext': fold text indexed by start line
681 function! s:NM_cmd_show_parse(inlines)
682 let info = { 'disp': [],
701 for line in a:inlines
702 let inlnum = inlnum + 1
708 if match(line, g:notmuch_show_part_end_regexp) != -1
709 let part_end = len(info['disp'])
711 call add(info['disp'], line)
714 if in_part == 'text/plain'
715 if !part_end && mode_type == ''
716 if match(line, g:notmuch_show_signature_regexp) != -1
717 let mode_type = 'sig'
718 let mode_start = len(info['disp'])
719 elseif match(line, g:notmuch_show_citation_regexp) != -1
720 let mode_type = 'cit'
721 let mode_start = len(info['disp'])
723 elseif mode_type == 'cit'
724 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
725 let outlnum = len(info['disp'])
726 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
727 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
730 elseif mode_type == 'sig'
731 let outlnum = len(info['disp'])
732 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
735 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
736 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
743 " FIXME: this is a hack for handling two folds being added for one line
744 " we should handle addinga fold in a function
745 if len(foldinfo) && foldinfo[1] < foldinfo[2]
746 call add(info['folds'], foldinfo[0:3])
747 let info['foldtext'][foldinfo[1]] = foldinfo[4]
750 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
751 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
753 call add(info['disp'], '')
757 if !has_key(msg,'body_start')
758 let msg['body_start'] = len(info['disp']) + 1
760 if match(line, g:notmuch_show_body_end_regexp) != -1
761 let body_end = len(info['disp'])
762 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
763 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
767 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
768 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
769 let in_part = 'unknown'
773 call add(info['disp'],
774 \ printf('--- %s ---', in_part))
775 let part_start = len(info['disp']) + 1
780 let msg['descr'] = line
781 call add(info['disp'], line)
783 let msg['hdr_start'] = len(info['disp']) + 1
786 if match(line, g:notmuch_show_header_end_regexp) != -1
787 let hdr_start = msg['hdr_start']+1
788 let hdr_end = len(info['disp'])
789 let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
790 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
791 let msg['header'] = hdr
795 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
798 if match(g:notmuch_show_headers, m[1]) != -1
799 call add(info['disp'], line)
806 if match(line, g:notmuch_show_message_end_regexp) != -1
807 let msg['end'] = len(info['disp'])
808 call add(info['disp'], '')
810 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
811 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
813 call add(info['msgs'], msg)
820 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
824 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
825 let body_start = len(info['disp']) + 1
831 if match(line, g:notmuch_show_message_begin_regexp) != -1
832 let msg['start'] = len(info['disp']) + 1
834 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
837 let msg['depth'] = m[2]
838 let msg['match'] = m[3]
839 let msg['filename'] = m[4]
846 if len(foldinfo) && foldinfo[1] < foldinfo[2]
847 call add(info['folds'], foldinfo[0:3])
848 let info['foldtext'][foldinfo[1]] = foldinfo[4]
854 function! s:NM_cmd_show_mkfolds()
855 let info = b:nm_raw_info
857 for afold in info['folds']
858 exec printf('%d,%dfold', afold[1], afold[2])
860 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
861 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
862 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
863 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
865 elseif afold[0] == 'msg'
867 let msg = info['msgs'][idx]
868 if has_key(msg,'match') && msg['match'] == '0'
872 exec printf('%dfold%s', afold[1], state)
876 function! s:NM_cmd_show_mksyntax()
877 let info = b:nm_raw_info
879 for msg in info['msgs']
881 let start = msg['start']
882 let hdr_start = msg['hdr_start']
883 let body_start = msg['body_start']
885 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
886 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
887 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
891 function! NM_cmd_show_foldtext()
892 let foldtext = b:nm_raw_info['foldtext']
893 return foldtext[v:foldstart]
897 " --- implement compose screen {{{1
899 function! s:NM_cmd_compose(words, body_lines)
901 let start_on_line = 0
905 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
907 throw 'Eeek! bad parameter ''' . string(word) . ''''
909 let key = substitute(m[1], '\<\w', '\U&', 'g')
910 if !has_key(hdrs, key)
914 call add(hdrs[key], m[2])
918 if !has_key(hdrs, 'From') || !len(hdrs['From'])
919 let me = <SID>NM_compose_get_user_email()
920 let hdrs['From'] = [ me ]
923 for key in g:notmuch_compose_headers
924 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
925 call add(lines, key . ': ' . text)
926 if !start_on_line && !strlen(text)
927 let start_on_line = len(lines)
931 for [key,val] in items(hdrs)
932 if match(g:notmuch_compose_headers, key) == -1
933 let line = key . ': ' . join(val, ', ')
934 call add(lines, line)
940 let start_on_line = len(lines) + 1
944 call extend(lines, a:body_lines)
946 call extend(lines, [ '', '' ])
949 call <SID>NM_newComposeBuffer(lines, start_on_line)
952 function! s:NM_compose_send()
953 call <SID>NM_assert_buffer_type('compose')
954 let fname = expand('%')
956 let line = getline(lnum)
958 while match(line, '^$') == -1
959 if !exists("hdr_starts") && match(line, '^Notmuch-Help:') == -1
960 let hdr_starts = lnum - 1
963 let line = getline(lnum)
965 let body_starts = lnum - 1
967 call append(body_starts, 'Date: ' . strftime('%a, %d %b %Y %H:%M:%S %z'))
968 exec printf(':0,%dd', hdr_starts)
971 let line = getline(1)
972 let m = matchlist(line, '^From:\s*\(.*\)\s*<\(.*\)>$')
976 let m = matchlist(line, '^From:\s*\(.*\)$')
980 let cmdtxt = g:notmuch_sendmail . ' -t -f ' . from . ' < ' . fname
981 let out = system(cmdtxt)
982 let err = v:shell_error
986 call <SID>NM_newBuffer('new', 'error',
987 \ "While running...\n" .
988 \ ' ' . cmdtxt . "\n" .
990 \ "Failed with...\n" .
991 \ substitute(out, '^', ' ', 'g'))
993 echo 'Eeek! unable to send mail'
998 if !exists('b:nm_prev_bufnr')
1001 let prev_bufnr = b:nm_prev_bufnr
1003 if prev_bufnr == bufnr('%')
1004 exec printf("buffer %d", prev_bufnr)
1008 echo 'Mail sent successfully.'
1011 function! s:NM_compose_attach()
1012 echo 'not implemented'
1015 function! s:NM_compose_next_entry_area()
1016 let lnum = line('.')
1017 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1020 let line = getline(lnum)
1021 if match(line, '^\([^:]\+\):\s*$') == -1
1022 call cursor(lnum, strlen(line) + 1)
1025 while match(getline(lnum+1), '^\s') != -1
1028 call cursor(lnum, strlen(getline(lnum)) + 1)
1031 elseif lnum == hdr_end
1032 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1036 if !getbufvar(bufnr('.'), '&et')
1040 let shiftwidth = a:shiftwidth
1041 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1042 " we assume no one has shiftwidth set to more than 40 :)
1043 return ' '[0:shiftwidth]
1047 " --- --- compose screen helper functions {{{2
1049 function! s:NM_compose_get_user_email()
1050 " TODO: do this properly (still), i.e., allow for multiple email accounts
1051 let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1055 function! s:NM_compose_find_line_match(start, pattern, failure)
1057 let lend = line('$')
1059 if match(getline(lnum), a:pattern) != -1
1068 " --- notmuch helper functions {{{1
1070 function! s:NM_newBuffer(how, type, content)
1076 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1077 silent put=a:content
1079 setlocal nomodifiable
1080 execute printf('set filetype=notmuch-%s', a:type)
1081 execute printf('set syntax=notmuch-%s', a:type)
1082 let b:nm_type = a:type
1085 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1086 let fdir = expand(a:fdir)
1087 if !isdirectory(fdir)
1088 call mkdir(fdir, 'p')
1090 let file_name = <SID>NM_mktemp(fdir, a:fname)
1091 if writefile(a:lines, file_name)
1092 throw 'Eeek! couldn''t write to temporary file ' . file_name
1094 exec printf('edit %s', file_name)
1095 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1096 execute printf('set filetype=notmuch-%s', a:type)
1097 execute printf('set syntax=notmuch-%s', a:type)
1098 let b:nm_type = a:type
1101 function! s:NM_newComposeBuffer(lines, start_on_line)
1103 let start_on_line = a:start_on_line
1104 let real_hdr_start = 1
1105 if g:notmuch_compose_header_help
1107 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1108 \ 'Notmuch-Help: ,a - attach a file',
1109 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
1110 \ 'Notmuch-Help: ,q - abort the message',
1111 \ 'Notmuch-Help: <Tab> - skip through header lines',
1113 call extend(lines, help_lines, 0)
1114 let real_hdr_start = len(help_lines)
1115 if start_on_line > 0
1116 let start_on_line = start_on_line + len(help_lines)
1119 call extend(lines, g:notmuch_signature)
1122 let prev_bufnr = bufnr('%')
1123 setlocal bufhidden=hide
1124 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1126 setlocal bufhidden=hide
1127 let b:nm_prev_bufnr = prev_bufnr
1129 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1130 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1132 if start_on_line > 0 && start_on_line <= len(lines)
1133 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1135 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1136 call <SID>NM_compose_next_entry_area()
1139 if g:notmuch_compose_insert_mode_start
1142 echo 'Type your message, use <TAB> to jump to next header and then body.'
1145 function! s:NM_assert_buffer_type(type)
1146 if !exists('b:nm_type') || b:nm_type != a:type
1147 throw printf('Eeek! expected type %s, but got %s.', a:type,
1148 \ exists(b:nm_type) ? b:nm_type : 'something else')
1152 function! s:NM_mktemp(dir, name)
1153 let time_stamp = strftime('%Y%m%d-%H%M%S')
1154 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1155 " TODO: check if it exists, try again
1159 function! s:NM_shell_escape(word)
1160 " TODO: use shellescape()
1161 let word = substitute(a:word, '''', '\\''', 'g')
1162 return '''' . word . ''''
1165 " this function was taken from git.vim, then fixed up
1166 " http://github.com/motemen/git-vim
1167 function! s:NM_shell_split(cmd)
1168 let l:split_cmd = []
1172 let t = match(cmd, '\S', iStart)
1178 let iSpace = match(cmd, '\v(\s|$)', iStart)
1183 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1184 if iQuote1 > iSpace || iQuote1 < iStart
1185 let iEnd = iSpace - 1
1186 let l:split_cmd += [ cmd[iStart : iEnd] ]
1188 let q = cmd[iQuote1]
1189 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1190 if iQuote2 < iQuote1
1191 throw 'No matching ' . q . ' quote'
1194 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1198 let iStart = iEnd + 1
1205 function! s:NM_run(args)
1207 call map(words, 's:NM_shell_escape(v:val)')
1208 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1210 if exists('g:notmuch_debug') && g:notmuch_debug
1211 let start = reltime()
1212 let out = system(cmd)
1213 let err = v:shell_error
1214 let delta = reltime(start)
1216 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1218 let out = system(cmd)
1219 let err = v:shell_error
1224 echo substitute(out, '\n*$', '', '')
1232 " --- external mail handling helpers {{{1
1234 function! s:NM_new_mail()
1235 call <SID>NM_cmd_compose([], [])
1238 " --- tag manipulation helpers {{{1
1240 " used to combine an array of words with prefixes and separators
1242 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1243 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1244 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1247 if len(res) && strlen(a:separator)
1248 call add(res, a:separator)
1250 call add(res, a:word_prefix . word)
1252 if len(res) > 1 && strlen(a:brackets)
1253 if strlen(a:brackets) != 2
1254 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1256 call insert(res, a:brackets[0])
1257 call add(res, a:brackets[1])
1262 " --- other helpers {{{1
1264 function! s:NM_get_search_words()
1265 if !exists('b:nm_search_words')
1266 throw 'Eeek! no b:nm_search_words'
1268 return b:nm_search_words
1271 function! s:NM_kill_this_buffer()
1272 if exists('b:nm_prev_bufnr')
1273 let prev_bufnr = b:nm_prev_bufnr
1275 exec printf("buffer %d", prev_bufnr)
1277 echo "This is the last buffer; use :q<CR> to quit."
1281 function! s:NM_search_expand(arg)
1282 let word = expand(a:arg)
1283 let prev_bufnr = bufnr('%')
1284 setlocal bufhidden=hide
1285 call <SID>NM_cmd_search([word])
1286 setlocal bufhidden=delete
1287 let b:nm_prev_bufnr = prev_bufnr
1290 function! s:NM_tag(filter, tags)
1291 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1293 throw 'Eeek! I couldn''t find the thead id!'
1296 call extend(args, a:tags)
1297 call add(args, '--')
1298 call extend(args, filter)
1299 " TODO: handle errors
1300 call <SID>NM_run(args)
1303 " --- process and set the defaults {{{1
1305 function! NM_set_defaults(force)
1306 for [key, dflt] in items(s:notmuch_defaults)
1308 if !a:force && exists(key) && type(dflt) == type(eval(key))
1310 elseif type(dflt) == type(0)
1311 let cmd = printf('let %s = %d', key, dflt)
1312 elseif type(dflt) == type('')
1313 let cmd = printf('let %s = ''%s''', key, dflt)
1314 " FIXME: not sure why this didn't work when dflt is an array
1315 "elseif type(dflt) == type([])
1316 " let cmd = printf('let %s = %s', key, string(dflt))
1318 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1319 \ a:force, key, string(dflt))
1325 call NM_set_defaults(0)
1327 " for some reason NM_set_defaults() didn't work for arrays...
1328 if !exists('g:notmuch_show_headers')
1329 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1331 if !exists('g:notmuch_initial_search_words')
1332 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1334 if !exists('g:notmuch_folders')
1335 let g:notmuch_folders = s:notmuch_folders_defaults
1338 if !exists('g:notmuch_signature')
1339 let g:notmuch_signature = s:notmuch_signature_defaults
1341 if !exists('g:notmuch_compose_headers')
1342 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1345 " --- assign keymaps {{{1
1347 function! s:NM_set_map(type, maps)
1349 for [key, code] in items(a:maps)
1350 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1352 " --- this is a hack for development :)
1353 nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1356 " --- command handler {{{1
1358 function! NotMuch(args)
1361 let args = 'folders'
1364 let words = <SID>NM_shell_split(args)
1365 if words[0] == 'folders' || words[0] == 'f'
1366 let words = words[1:]
1367 call <SID>NM_cmd_folders(words)
1369 elseif words[0] == 'search' || words[0] == 's'
1371 let words = words[1:]
1372 elseif exists('b:nm_search_words')
1373 let words = b:nm_search_words
1375 let words = g:notmuch_initial_search_words
1377 call <SID>NM_cmd_search(words)
1379 elseif words[0] == 'show'
1380 echoe 'show is not yet implemented.'
1382 elseif words[0] == 'new' || words[0] == 'compose'
1383 let words = words[1:]
1384 call <SID>NM_cmd_compose(words, [])
1387 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1394 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1395 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1397 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :