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: Peter Hartman <peterjohnhartman@gmail.com>
23 " --- configuration defaults {{{1
25 let s:notmuch_defaults = {
26 \ 'g:notmuch_cmd': 'notmuch' ,
27 \ 'g:notmuch_debug': 0 ,
29 \ 'g:notmuch_search_newest_first': 1 ,
30 \ 'g:notmuch_search_from_column_width': 20 ,
32 \ 'g:notmuch_show_fold_signatures': 1 ,
33 \ 'g:notmuch_show_fold_citations': 1 ,
34 \ 'g:notmuch_show_fold_bodies': 0 ,
35 \ 'g:notmuch_show_fold_headers': 1 ,
37 \ 'g:notmuch_show_message_begin_regexp': '
\fmessage{' ,
38 \ 'g:notmuch_show_message_end_regexp': '
\fmessage}' ,
39 \ 'g:notmuch_show_header_begin_regexp': '
\fheader{' ,
40 \ 'g:notmuch_show_header_end_regexp': '
\fheader}' ,
41 \ 'g:notmuch_show_body_begin_regexp': '
\fbody{' ,
42 \ 'g:notmuch_show_body_end_regexp': '
\fbody}' ,
43 \ 'g:notmuch_show_attachment_begin_regexp': '
\fattachment{' ,
44 \ 'g:notmuch_show_attachment_end_regexp': '
\fattachment}' ,
45 \ 'g:notmuch_show_part_begin_regexp': '
\fpart{' ,
46 \ 'g:notmuch_show_part_end_regexp': '
\fpart}' ,
47 \ 'g:notmuch_show_marker_regexp': '
\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
49 \ 'g:notmuch_show_message_parse_regexp': '\(id:[^ ]*\) depth:\([0-9]*\) match:\([0-9]*\) filename:\(.*\)$',
50 \ 'g:notmuch_show_tags_regexp': '(\([^)]*\))$' ,
52 \ 'g:notmuch_show_signature_regexp': '^\(-- \?\|_\+\)$' ,
53 \ 'g:notmuch_show_signature_lines_max': 12 ,
55 \ 'g:notmuch_show_citation_regexp': '^\s*>' ,
57 \ 'g:notmuch_compose_insert_mode_start': 1 ,
58 \ 'g:notmuch_compose_header_help': 1 ,
59 \ 'g:notmuch_compose_temp_file_dir': '~/.notmuch/compose/' ,
62 " defaults for g:notmuch_initial_search_words
63 " override with: let g:notmuch_initial_search_words = [ ... ]
64 let s:notmuch_initial_search_words_defaults = [
65 \ 'tag:inbox and tag:unread',
68 " defaults for g:notmuch_show_headers
69 " override with: let g:notmuch_show_headers = [ ... ]
70 let s:notmuch_show_headers_defaults = [
78 " defaults for g:notmuch_folders
79 " override with: let g:notmuch_folders = [ ... ]
80 let s:notmuch_folders_defaults = [
81 \ [ 'new', 'tag:inbox and tag:unread' ],
82 \ [ 'inbox', 'tag:inbox' ],
83 \ [ 'unread', 'tag:unread' ],
86 " defaults for g:notmuch_signature
87 " override with: let g:notmuch_signature = [ ... ]
88 let s:notmuch_signature_defaults = [
91 \ 'email sent from notmuch.vim plugin'
94 " defaults for g:notmuch_compose_headers
95 " override with: let g:notmuch_compose_headers = [ ... ]
96 let s:notmuch_compose_headers_defaults = [
104 " --- keyboard mapping definitions {{{1
106 " --- --- bindings for folders mode {{{2
108 let g:notmuch_folders_maps = {
109 \ 'm': ':call <SID>NM_new_mail()<CR>',
110 \ 's': ':call <SID>NM_search_prompt()<CR>',
111 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
112 \ '=': ':call <SID>NM_folders_refresh_view()<CR>',
113 \ '<Enter>': ':call <SID>NM_folders_show_search()<CR>',
116 " --- --- bindings for search screen {{{2
117 let g:notmuch_search_maps = {
118 \ '<Space>': ':call <SID>NM_search_show_thread(0)<CR>',
119 \ '<Enter>': ':call <SID>NM_search_show_thread(1)<CR>',
120 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
121 \ 'a': ':call <SID>NM_search_archive_thread()<CR>',
122 \ 'A': ':call <SID>NM_search_mark_read_then_archive_thread()<CR>',
123 \ 'f': ':call <SID>NM_search_filter()<CR>',
124 \ 'm': ':call <SID>NM_new_mail()<CR>',
125 \ 'o': ':call <SID>NM_search_toggle_order()<CR>',
126 \ 'r': ':call <SID>NM_search_reply_to_thread()<CR>',
127 \ 's': ':call <SID>NM_search_prompt()<CR>',
128 \ ',s': ':call <SID>NM_search_edit()<CR>',
129 \ 't': ':call <SID>NM_search_filter_by_tag()<CR>',
130 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
131 \ '+': ':call <SID>NM_search_add_tags([])<CR>',
132 \ '-': ':call <SID>NM_search_remove_tags([])<CR>',
133 \ '=': ':call <SID>NM_search_refresh_view()<CR>',
134 \ '?': ':echo <SID>NM_search_thread_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
137 " --- --- bindings for show screen {{{2
138 let g:notmuch_show_maps = {
139 \ '<C-P>': ':call <SID>NM_show_previous(1, 0)<CR>',
140 \ '<C-N>': ':call <SID>NM_show_next(1, 0)<CR>',
141 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
142 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
143 \ 's': ':call <SID>NM_search_prompt()<CR>',
145 \ 'b': ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
146 \ 'c': ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
147 \ 'h': ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
148 \ 'i': ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
150 \ 'a': ':call <SID>NM_show_archive_thread()<CR>',
151 \ 'A': ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
152 \ 'N': ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
153 \ 'v': ':call <SID>NM_show_view_all_mime_parts()<CR>',
154 \ '+': ':call <SID>NM_show_add_tag()<CR>',
155 \ '-': ':call <SID>NM_show_remove_tag()<CR>',
156 \ '<Space>': ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
157 \ '\|': ':call <SID>NM_show_pipe_message()<CR>',
159 \ '<S-Tab>': ':call <SID>NM_show_previous_fold()<CR>',
160 \ '<Tab>': ':call <SID>NM_show_next_fold()<CR>',
161 \ '<Enter>': ':call <SID>NM_show_toggle_fold()<CR>',
163 \ 'r': ':call <SID>NM_show_reply()<CR>',
164 \ 'm': ':call <SID>NM_new_mail()<CR>',
165 \ '?': ':echo <SID>NM_show_message_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
168 " --- --- bindings for compose screen {{{2
169 let g:notmuch_compose_nmaps = {
170 \ ',s': ':call <SID>NM_compose_send()<CR>',
171 \ ',a': ':call <SID>NM_compose_attach()<CR>',
172 \ ',q': ':call <SID>NM_kill_this_buffer()<CR>',
173 \ '<Tab>': ':call <SID>NM_compose_next_entry_area()<CR>',
175 let g:notmuch_compose_imaps = {
176 \ '<Tab>': '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
179 " --- implement folders screen {{{1
181 function! s:NM_cmd_folders(words)
183 throw 'Not expecting any arguments for folders command.'
188 for entry in g:notmuch_folders
189 let [ name, search ] = entry
190 let data = s:NM_run(cmd + [search])
191 let cnt = matchlist(data, '\(\d\+\)')[1]
192 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
193 call add(searches, search)
196 call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
197 let b:nm_searches = searches
198 let b:nm_timestamp = reltime()
200 call <SID>NM_cmd_folders_mksyntax()
201 call <SID>NM_set_map('n', g:notmuch_folders_maps)
206 function! s:NM_cmd_folders_mksyntax()
209 " --- --- folders screen action functions {{{2
211 function! s:NM_folders_refresh_view()
213 setlocal bufhidden=delete
214 call s:NM_cmd_folders([])
215 exec printf('norm %dG', lno)
218 function! s:NM_folders_show_search()
220 let search = b:nm_searches[line-1]
222 let prev_bufnr = bufnr('%')
223 setlocal bufhidden=hide
224 call <SID>NM_cmd_search([search])
225 setlocal bufhidden=delete
226 let b:nm_prev_bufnr = prev_bufnr
230 " --- implement search screen {{{1
232 function! s:NM_cmd_search(words)
234 if g:notmuch_search_newest_first
235 let cmd = cmd + ['--sort=newest-first']
237 let cmd = cmd + ['--sort=oldest-first']
239 let data = s:NM_run(cmd + a:words)
240 let lines = split(data, "\n")
241 let disp = copy(lines)
242 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
244 call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
245 let b:nm_raw_lines = lines
246 let b:nm_search_words = a:words
248 call <SID>NM_set_map('n', g:notmuch_search_maps)
252 function! s:NM_cmd_search_fmtline(line)
253 let m = matchlist(a:line, '^\(thread:\S\+\)\s\(.\{12\}\) \[\(\d\+\)/\d\+\] \([^;]\+\); \%(\[[^\[]\+\] \)*\(.*\) (\([^(]*\))$')
255 return 'ERROR PARSING: ' . a:line
257 let max = g:notmuch_search_from_column_width
259 for at in split(m[4], ", ")
260 let p = min([stridx(at, "."), stridx(at, "@")])
261 call insert(flist, tolower(at[0:p - 1]))
263 let from = join(flist, ", ")
264 return printf("%-12s %3s %-20.20s | %s (%s)", m[2], m[3], from, m[5], m[6])
267 " --- --- search screen action functions {{{2
269 function! s:NM_search_show_thread(everything)
270 let words = [ <SID>NM_search_thread_id() ]
271 if !a:everything && exists('b:nm_search_words')
272 call extend(words, ['AND', '('])
273 call extend(words, b:nm_search_words)
276 call <SID>NM_cmd_show(words)
277 let b:nm_show_everything = a:everything
280 function! s:NM_search_prompt()
281 " TODO: input() can support completion
282 let text = input('NotMuch Search: ')
284 let tags = split(text)
286 let tags = s:notmuch_initial_search_words_defaults
288 let prev_bufnr = bufnr('%')
289 if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
290 " TODO: we intend to replace the current buffer,
291 " ... maybe we could just clear it
292 let prev_bufnr = b:nm_prev_bufnr
293 setlocal bufhidden=delete
295 setlocal bufhidden=hide
297 call <SID>NM_cmd_search(tags)
298 setlocal bufhidden=delete
299 let b:nm_prev_bufnr = prev_bufnr
302 function! s:NM_search_edit()
303 " TODO: input() can support completion
304 let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
306 call <SID>NM_cmd_search(split(text))
310 function! s:NM_search_archive_thread()
311 call <SID>NM_tag([], ['-inbox'])
315 function! s:NM_search_mark_read_then_archive_thread()
316 call <SID>NM_tag([], ['-unread', '-inbox'])
320 function! s:NM_search_filter()
321 call <SID>NM_search_filter_helper('Filter: ', '', '')
324 function! s:NM_search_filter_by_tag()
325 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
328 function! s:NM_search_filter_helper(prompt, prefix, joiner)
329 " TODO: input() can support completion
330 let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
335 let tags = b:nm_search_words + ['AND']
336 \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
338 let prev_bufnr = bufnr('%')
339 setlocal bufhidden=hide
340 call <SID>NM_cmd_search(tags)
341 setlocal bufhidden=delete
342 let b:nm_prev_bufnr = prev_bufnr
345 function! s:NM_search_toggle_order()
346 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
347 " FIXME: maybe this would be better done w/o reading re-reading the lines
348 " reversing the b:nm_raw_lines and the buffer lines would be better
349 call <SID>NM_search_refresh_view()
352 function! s:NM_search_reply_to_thread()
354 call add(cmd, <SID>NM_search_thread_id())
356 call extend(cmd, <SID>NM_get_search_words())
358 let data = <SID>NM_run(cmd)
359 let lines = split(data, "\n")
360 call <SID>NM_newComposeBuffer(lines, 0)
363 function! s:NM_search_add_tags(tags)
364 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
367 function! s:NM_search_remove_tags(tags)
368 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
371 function! s:NM_search_refresh_view()
373 let prev_bufnr = b:nm_prev_bufnr
374 setlocal bufhidden=delete
375 call <SID>NM_cmd_search(b:nm_search_words)
376 let b:nm_prev_bufnr = prev_bufnr
377 " FIXME: should find the line of the thread we were on if possible
378 exec printf('norm %dG', lno)
381 " --- --- search screen helper functions {{{2
383 function! s:NM_search_thread_id()
384 if !exists('b:nm_raw_lines')
385 throw 'Eeek! no b:nm_raw_lines'
387 let mnum = line('.') - 1
388 if len(b:nm_raw_lines) <= mnum
391 let info = b:nm_raw_lines[mnum]
392 let what = split(info, '\s\+')[0]
396 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
397 if type(a:intags) != type([]) || len(a:intags) == 0
398 " TODO: input() can support completion
399 let text = input(a:prompt)
403 let tags = split(text, ' ')
407 call map(tags, 'a:prefix . v:val')
408 call <SID>NM_tag([], tags)
411 " --- implement show screen {{{1
413 function! s:NM_cmd_show(words)
414 let prev_bufnr = bufnr('%')
415 let data = s:NM_run(['show', '--entire-thread'] + a:words)
416 let lines = split(data, "\n")
418 let info = s:NM_cmd_show_parse(lines)
420 setlocal bufhidden=hide
421 call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
422 setlocal bufhidden=delete
423 let b:nm_search_words = a:words
424 let b:nm_raw_info = info
425 let b:nm_prev_bufnr = prev_bufnr
427 call <SID>NM_cmd_show_mkfolds()
428 call <SID>NM_cmd_show_mksyntax()
429 call <SID>NM_set_map('n', g:notmuch_show_maps)
430 setlocal foldtext=NM_cmd_show_foldtext()
432 setlocal foldcolumn=6
436 function! s:NM_show_previous(can_change_thread, find_matching)
437 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
438 let info = b:nm_raw_info
440 for msg in reverse(copy(info['msgs']))
441 if a:find_matching && msg['match'] == '0'
444 if lnum <= msg['start']
448 exec printf('norm %dGzt', msg['start'])
449 " TODO: try to fit the message on screen
452 if !a:can_change_thread
455 call <SID>NM_kill_this_buffer()
458 call <SID>NM_search_show_thread(everything)
460 call <SID>NM_show_previous(0, a:find_matching)
462 echo 'No more messages.'
466 function! s:NM_show_next(can_change_thread, find_matching)
467 let info = b:nm_raw_info
469 for msg in info['msgs']
470 if a:find_matching && msg['match'] == '0'
473 if lnum >= msg['start']
477 exec printf('norm %dGzt', msg['start'])
478 " TODO: try to fit the message on screen
481 if a:can_change_thread
482 call <SID>NM_show_next_thread()
486 function! s:NM_show_next_thread()
487 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
488 call <SID>NM_kill_this_buffer()
489 if line('.') != line('$')
491 call <SID>NM_search_show_thread(everything)
493 echo 'No more messages.'
497 function! s:NM_show_archive_thread()
498 call <SID>NM_tag(b:nm_search_words, ['-inbox'])
499 call <SID>NM_show_next_thread()
502 function! s:NM_show_mark_read_then_archive_thread()
503 call <SID>NM_tag(b:nm_search_words, ['-unread', '-inbox'])
504 call <SID>NM_show_next_thread()
507 function! s:NM_show_mark_read_then_next_open_message()
508 echo 'not implemented'
511 function! s:NM_show_previous_message()
512 echo 'not implemented'
515 function! s:NM_show_reply()
517 call add(cmd, <SID>NM_show_message_id())
519 call extend(cmd, <SID>NM_get_search_words())
521 let data = <SID>NM_run(cmd)
522 let lines = split(data, "\n")
523 call <SID>NM_newComposeBuffer(lines, 0)
526 function! s:NM_show_view_all_mime_parts()
527 echo 'not implemented'
530 function! s:NM_show_view_raw_message()
531 echo 'not implemented'
534 function! s:NM_show_add_tag()
535 echo 'not implemented'
538 function! s:NM_show_remove_tag()
539 echo 'not implemented'
542 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
543 " otherwise go to next message
544 " any message that is viewed entirely has inbox and unread tags removed
545 function! s:NM_show_advance_marking_read_and_archiving()
546 let advance_tags = ['unread', 'inbox']
548 let vis_top = line('w0')
549 let vis_bot = line('w$')
551 let msg_top = <SID>NM_show_get_message_for_line(vis_top)
552 if !has_key(msg_top,'id')
553 throw "No top visible message."
556 " if the top message is the last message, just expunge the entire thread and move on
557 if msg_top['end'] == line('$')
559 for msg in b:nm_raw_info['msgs']
560 if has_key(msg,'match') && msg['match'] != '0'
561 call add(ids, msg['id'])
564 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
566 \ + <SID>NM_combine_tags('', ids, 'OR', '()')
567 call map(advance_tags, '"+" . v:val')
568 call <SID>NM_tag(filter, advance_tags)
569 call <SID>NM_show_next(1, 1)
573 let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
574 if !has_key(msg_bot,'id')
575 throw "No bottom visible message."
578 " if entire message fits on the screen, read/archive it, move to the next one
579 if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
580 exec printf('norm %dG', vis_top)
581 call <SID>NM_show_next(0, 1)
582 if has_key(msg_top,'match') && msg_top['match'] != '0'
584 " do this last to hide the latency
585 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
586 \ + ['AND', msg_top['id']]
587 call map(advance_tags, '"-" . v:val')
588 call <SID>NM_tag(filter, advance_tags)
593 " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
594 let jmp = winheight(winnr()) / 2
595 let max = msg_bot['end'] - vis_bot
599 exec printf('norm %dGzt', vis_top + jmp)
603 function! s:NM_show_pipe_message()
604 echo 'not implemented'
607 function! s:NM_show_previous_fold()
608 echo 'not implemented'
611 function! s:NM_show_next_fold()
612 echo 'not implemented'
615 function! s:NM_show_toggle_fold()
616 echo 'not implemented'
620 " --- --- show screen helper functions {{{2
622 function! s:NM_show_get_message_for_line(line)
623 for msg in b:nm_raw_info['msgs']
624 if a:line > msg['end']
632 function! s:NM_show_message_id()
633 if !exists('b:nm_raw_info')
634 throw 'Eeek! no b:nm_raw_info'
636 let msg = <SID>NM_show_get_message_for_line(line('.'))
643 function! s:NM_show_fold_toggle(key, type, fold)
644 let info = b:nm_raw_info
649 for fld in info['folds']
654 "let msg = info['msgs'][idx]
655 "if has_key(msg,'match') && msg['match'] == '0'
658 let cls = foldclosed(fld[1])
659 if cls != -1 && cls != fld[1]
662 exec printf('%dfold%s', fld[1], act)
664 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
668 " s:NM_cmd_show_parse returns the following dictionary:
669 " 'disp': lines to display
670 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
671 " 'folds': fold info arrays [ type, start, end ]
672 " 'foldtext': fold text indexed by start line
673 function! s:NM_cmd_show_parse(inlines)
674 let info = { 'disp': [],
693 for line in a:inlines
694 let inlnum = inlnum + 1
700 if match(line, g:notmuch_show_part_end_regexp) != -1
701 let part_end = len(info['disp'])
703 call add(info['disp'], line)
706 if in_part == 'text/plain'
707 if !part_end && mode_type == ''
708 if match(line, g:notmuch_show_signature_regexp) != -1
709 let mode_type = 'sig'
710 let mode_start = len(info['disp'])
711 elseif match(line, g:notmuch_show_citation_regexp) != -1
712 let mode_type = 'cit'
713 let mode_start = len(info['disp'])
715 elseif mode_type == 'cit'
716 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
717 let outlnum = len(info['disp'])
718 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
719 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
722 elseif mode_type == 'sig'
723 let outlnum = len(info['disp'])
724 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
727 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
728 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
735 " FIXME: this is a hack for handling two folds being added for one line
736 " we should handle addinga fold in a function
737 if len(foldinfo) && foldinfo[1] < foldinfo[2]
738 call add(info['folds'], foldinfo[0:3])
739 let info['foldtext'][foldinfo[1]] = foldinfo[4]
742 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
743 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
745 call add(info['disp'], '')
749 if !has_key(msg,'body_start')
750 let msg['body_start'] = len(info['disp']) + 1
752 if match(line, g:notmuch_show_body_end_regexp) != -1
753 let body_end = len(info['disp'])
754 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
755 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
759 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
760 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
761 let in_part = 'unknown'
765 call add(info['disp'],
766 \ printf('--- %s ---', in_part))
767 let part_start = len(info['disp']) + 1
772 let msg['descr'] = line
773 call add(info['disp'], line)
775 let msg['hdr_start'] = len(info['disp']) + 1
778 if match(line, g:notmuch_show_header_end_regexp) != -1
779 let hdr_start = msg['hdr_start']+1
780 let hdr_end = len(info['disp'])
781 let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
782 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
783 let msg['header'] = hdr
787 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
790 if match(g:notmuch_show_headers, m[1]) != -1
791 call add(info['disp'], line)
798 if match(line, g:notmuch_show_message_end_regexp) != -1
799 let msg['end'] = len(info['disp'])
800 call add(info['disp'], '')
802 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
803 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
805 call add(info['msgs'], msg)
812 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
816 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
817 let body_start = len(info['disp']) + 1
823 if match(line, g:notmuch_show_message_begin_regexp) != -1
824 let msg['start'] = len(info['disp']) + 1
826 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
829 let msg['depth'] = m[2]
830 let msg['match'] = m[3]
831 let msg['filename'] = m[4]
838 if len(foldinfo) && foldinfo[1] < foldinfo[2]
839 call add(info['folds'], foldinfo[0:3])
840 let info['foldtext'][foldinfo[1]] = foldinfo[4]
846 function! s:NM_cmd_show_mkfolds()
847 let info = b:nm_raw_info
849 for afold in info['folds']
850 exec printf('%d,%dfold', afold[1], afold[2])
852 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
853 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
854 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
855 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
857 elseif afold[0] == 'msg'
859 let msg = info['msgs'][idx]
860 if has_key(msg,'match') && msg['match'] == '0'
864 exec printf('%dfold%s', afold[1], state)
868 function! s:NM_cmd_show_mksyntax()
869 let info = b:nm_raw_info
871 for msg in info['msgs']
873 let start = msg['start']
874 let hdr_start = msg['hdr_start']
875 let body_start = msg['body_start']
877 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
878 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
879 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
883 function! NM_cmd_show_foldtext()
884 let foldtext = b:nm_raw_info['foldtext']
885 return foldtext[v:foldstart]
889 " --- implement compose screen {{{1
891 function! s:NM_cmd_compose(words, body_lines)
893 let start_on_line = 0
897 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
899 throw 'Eeek! bad parameter ''' . string(word) . ''''
901 let key = substitute(m[1], '\<\w', '\U&', 'g')
902 if !has_key(hdrs, key)
906 call add(hdrs[key], m[2])
910 if !has_key(hdrs, 'From') || !len(hdrs['From'])
911 let me = <SID>NM_compose_get_user_email()
912 let hdrs['From'] = [ me ]
915 for key in g:notmuch_compose_headers
916 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
917 call add(lines, key . ': ' . text)
918 if !start_on_line && !strlen(text)
919 let start_on_line = len(lines)
923 for [key,val] in items(hdrs)
924 if match(g:notmuch_compose_headers, key) == -1
925 let line = key . ': ' . join(val, ', ')
926 call add(lines, line)
932 let start_on_line = len(lines) + 1
936 call extend(lines, a:body_lines)
938 call extend(lines, [ '', '' ])
941 call <SID>NM_newComposeBuffer(lines, start_on_line)
944 function! s:NM_compose_send()
945 call <SID>NM_assert_buffer_type('compose')
946 let fname = expand('%')
948 let line = getline(lnum)
950 while match(line, '^$') == -1
951 if match(line, '^Notmuch-Help:') == -1
952 let hdr_starts = lnum - 1
956 let line = getline(lnum)
959 exec printf(':0,%dd', hdr_starts)
962 let cmdtxt = 'mailx -t < ' . fname
963 let out = system(cmdtxt)
964 let err = v:shell_error
968 call <SID>NM_newBuffer('new', 'error',
969 \ "While running...\n" .
970 \ ' ' . cmdtxt . "\n" .
972 \ "Failed with...\n" .
973 \ substitute(out, '^', ' ', 'g'))
975 echo 'Eeek! unable to send mail'
980 if !exists('b:nm_prev_bufnr')
983 let prev_bufnr = b:nm_prev_bufnr
985 if prev_bufnr == bufnr('%')
986 exec printf("buffer %d", prev_bufnr)
990 echo 'Mail sent successfully.'
993 function! s:NM_compose_attach()
994 echo 'not implemented'
997 function! s:NM_compose_next_entry_area()
999 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1002 let line = getline(lnum)
1003 if match(line, '^\([^:]\+\):\s*$') == -1
1004 call cursor(lnum, strlen(line) + 1)
1007 while match(getline(lnum+1), '^\s') != -1
1010 call cursor(lnum, strlen(getline(lnum)) + 1)
1013 elseif lnum == hdr_end
1014 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1018 if !getbufvar(bufnr('.'), '&et')
1022 let shiftwidth = a:shiftwidth
1023 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1024 " we assume no one has shiftwidth set to more than 40 :)
1025 return ' '[0:shiftwidth]
1029 " --- --- compose screen helper functions {{{2
1031 function! s:NM_compose_get_user_email()
1032 " TODO: do this properly (still), i.e., allow for multiple email accounts
1033 let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1037 function! s:NM_compose_find_line_match(start, pattern, failure)
1039 let lend = line('$')
1041 if match(getline(lnum), a:pattern) != -1
1050 " --- notmuch helper functions {{{1
1052 function! s:NM_newBuffer(how, type, content)
1058 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1059 silent put=a:content
1061 setlocal nomodifiable
1062 execute printf('set filetype=notmuch-%s', a:type)
1063 execute printf('set syntax=notmuch-%s', a:type)
1064 let b:nm_type = a:type
1067 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1068 let fdir = expand(a:fdir)
1069 if !isdirectory(fdir)
1070 call mkdir(fdir, 'p')
1072 let file_name = <SID>NM_mktemp(fdir, a:fname)
1073 if writefile(a:lines, file_name)
1074 throw 'Eeek! couldn''t write to temporary file ' . file_name
1076 exec printf('edit %s', file_name)
1077 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1078 execute printf('set filetype=notmuch-%s', a:type)
1079 execute printf('set syntax=notmuch-%s', a:type)
1080 let b:nm_type = a:type
1083 function! s:NM_newComposeBuffer(lines, start_on_line)
1085 let start_on_line = a:start_on_line
1086 let real_hdr_start = 1
1087 if g:notmuch_compose_header_help
1089 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1090 \ 'Notmuch-Help: ,a - attach a file',
1091 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
1092 \ 'Notmuch-Help: ,q - abort the message',
1093 \ 'Notmuch-Help: <Tab> - skip through header lines',
1095 call extend(lines, help_lines, 0)
1096 let real_hdr_start = len(help_lines)
1097 if start_on_line > 0
1098 let start_on_line = start_on_line + len(help_lines)
1101 call extend(lines, g:notmuch_signature)
1104 let prev_bufnr = bufnr('%')
1105 setlocal bufhidden=hide
1106 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1108 setlocal bufhidden=hide
1109 let b:nm_prev_bufnr = prev_bufnr
1111 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1112 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1114 if start_on_line > 0 && start_on_line <= len(lines)
1115 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1117 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1118 call <SID>NM_compose_next_entry_area()
1121 if g:notmuch_compose_insert_mode_start
1124 echo 'Type your message, use <TAB> to jump to next header and then body.'
1127 function! s:NM_assert_buffer_type(type)
1128 if !exists('b:nm_type') || b:nm_type != a:type
1129 throw printf('Eeek! expected type %s, but got %s.', a:type,
1130 \ exists(b:nm_type) ? b:nm_type : 'something else')
1134 function! s:NM_mktemp(dir, name)
1135 let time_stamp = strftime('%Y%m%d-%H%M%S')
1136 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1137 " TODO: check if it exists, try again
1141 function! s:NM_shell_escape(word)
1142 " TODO: use shellescape()
1143 let word = substitute(a:word, '''', '\\''', 'g')
1144 return '''' . word . ''''
1147 " this function was taken from git.vim, then fixed up
1148 " http://github.com/motemen/git-vim
1149 function! s:NM_shell_split(cmd)
1150 let l:split_cmd = []
1154 let t = match(cmd, '\S', iStart)
1160 let iSpace = match(cmd, '\v(\s|$)', iStart)
1165 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1166 if iQuote1 > iSpace || iQuote1 < iStart
1167 let iEnd = iSpace - 1
1168 let l:split_cmd += [ cmd[iStart : iEnd] ]
1170 let q = cmd[iQuote1]
1171 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1172 if iQuote2 < iQuote1
1173 throw 'No matching ' . q . ' quote'
1176 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1180 let iStart = iEnd + 1
1187 function! s:NM_run(args)
1189 call map(words, 's:NM_shell_escape(v:val)')
1190 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1192 if exists('g:notmuch_debug') && g:notmuch_debug
1193 let start = reltime()
1194 let out = system(cmd)
1195 let err = v:shell_error
1196 let delta = reltime(start)
1198 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1200 let out = system(cmd)
1201 let err = v:shell_error
1206 echo substitute(out, '\n*$', '', '')
1214 " --- external mail handling helpers {{{1
1216 function! s:NM_new_mail()
1217 call <SID>NM_cmd_compose([], [])
1220 " --- tag manipulation helpers {{{1
1222 " used to combine an array of words with prefixes and separators
1224 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1225 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1226 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1229 if len(res) && strlen(a:separator)
1230 call add(res, a:separator)
1232 call add(res, a:word_prefix . word)
1234 if len(res) > 1 && strlen(a:brackets)
1235 if strlen(a:brackets) != 2
1236 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1238 call insert(res, a:brackets[0])
1239 call add(res, a:brackets[1])
1244 " --- other helpers {{{1
1246 function! s:NM_get_search_words()
1247 if !exists('b:nm_search_words')
1248 throw 'Eeek! no b:nm_search_words'
1250 return b:nm_search_words
1253 function! s:NM_kill_this_buffer()
1254 if exists('b:nm_prev_bufnr')
1255 let prev_bufnr = b:nm_prev_bufnr
1257 exec printf("buffer %d", prev_bufnr)
1259 echo "This is the last buffer; use :q<CR> to quit."
1263 function! s:NM_search_expand(arg)
1264 let word = expand(a:arg)
1265 let prev_bufnr = bufnr('%')
1266 setlocal bufhidden=hide
1267 call <SID>NM_cmd_search([word])
1268 setlocal bufhidden=delete
1269 let b:nm_prev_bufnr = prev_bufnr
1272 function! s:NM_tag(filter, tags)
1273 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1275 throw 'Eeek! I couldn''t find the thead id!'
1278 call extend(args, a:tags)
1279 call add(args, '--')
1280 call extend(args, filter)
1281 " TODO: handle errors
1282 call <SID>NM_run(args)
1285 " --- process and set the defaults {{{1
1287 function! NM_set_defaults(force)
1288 for [key, dflt] in items(s:notmuch_defaults)
1290 if !a:force && exists(key) && type(dflt) == type(eval(key))
1292 elseif type(dflt) == type(0)
1293 let cmd = printf('let %s = %d', key, dflt)
1294 elseif type(dflt) == type('')
1295 let cmd = printf('let %s = ''%s''', key, dflt)
1296 " FIXME: not sure why this didn't work when dflt is an array
1297 "elseif type(dflt) == type([])
1298 " let cmd = printf('let %s = %s', key, string(dflt))
1300 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1301 \ a:force, key, string(dflt))
1307 call NM_set_defaults(0)
1309 " for some reason NM_set_defaults() didn't work for arrays...
1310 if !exists('g:notmuch_show_headers')
1311 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1313 if !exists('g:notmuch_initial_search_words')
1314 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1316 if !exists('g:notmuch_folders')
1317 let g:notmuch_folders = s:notmuch_folders_defaults
1320 if !exists('g:notmuch_signature')
1321 let g:notmuch_signature = s:notmuch_signature_defaults
1323 if !exists('g:notmuch_compose_headers')
1324 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1327 " --- assign keymaps {{{1
1329 function! s:NM_set_map(type, maps)
1331 for [key, code] in items(a:maps)
1332 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1334 " --- this is a hack for development :)
1335 nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1338 " --- command handler {{{1
1340 function! NotMuch(args)
1343 let args = 'folders'
1346 let words = <SID>NM_shell_split(args)
1347 if words[0] == 'folders' || words[0] == 'f'
1348 let words = words[1:]
1349 call <SID>NM_cmd_folders(words)
1351 elseif words[0] == 'search' || words[0] == 's'
1353 let words = words[1:]
1354 elseif exists('b:nm_search_words')
1355 let words = b:nm_search_words
1357 let words = g:notmuch_initial_search_words
1359 call <SID>NM_cmd_search(words)
1361 elseif words[0] == 'show'
1362 echoe 'show is not yet implemented.'
1364 elseif words[0] == 'new' || words[0] == 'compose'
1365 let words = words[1:]
1366 call <SID>NM_cmd_compose(words, [])
1369 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1376 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1377 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1379 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :