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': '/usr/sbin/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 \ 'I': ':call <SID>NM_search_mark_read_thread()<CR>',
124 \ 'a': ':call <SID>NM_search_archive_thread()<CR>',
125 \ 'A': ':call <SID>NM_search_mark_read_then_archive_thread()<CR>',
126 \ 'D': ':call <SID>NM_search_delete_thread()<CR>',
127 \ 'f': ':call <SID>NM_search_filter()<CR>',
128 \ 'm': ':call <SID>NM_new_mail()<CR>',
129 \ 'o': ':call <SID>NM_search_toggle_order()<CR>',
130 \ 'r': ':call <SID>NM_search_reply_to_thread()<CR>',
131 \ 's': ':call <SID>NM_search_prompt()<CR>',
132 \ ',s': ':call <SID>NM_search_edit()<CR>',
133 \ 't': ':call <SID>NM_search_filter_by_tag()<CR>',
134 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
135 \ '+': ':call <SID>NM_search_add_tags([])<CR>',
136 \ '-': ':call <SID>NM_search_remove_tags([])<CR>',
137 \ '=': ':call <SID>NM_search_refresh_view()<CR>',
138 \ '?': ':echo <SID>NM_search_thread_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
141 " --- --- bindings for show screen {{{2
142 let g:notmuch_show_maps = {
143 \ '<C-P>': ':call <SID>NM_show_previous(1, 0)<CR>',
144 \ '<C-N>': ':call <SID>NM_show_next(1, 0)<CR>',
145 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
146 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
147 \ 's': ':call <SID>NM_search_prompt()<CR>',
149 \ 'b': ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
150 \ 'c': ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
151 \ 'h': ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
152 \ 'i': ':call <SID>NM_show_fold_toggle(''i'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
154 \ 'I': ':call <SID>NM_show_mark_read_thread()<CR>',
155 \ 'a': ':call <SID>NM_show_archive_thread()<CR>',
156 \ 'A': ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
157 \ 'D': ':call <SID>NM_show_delete_thread()<CR>',
158 \ 'd': ':call <SID>NM_show_delete_message()<CR>',
159 \ 'N': ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
160 \ 'v': ':call <SID>NM_show_view_all_mime_parts()<CR>',
161 \ '+': ':call <SID>NM_show_add_tag()<CR>',
162 \ '-': ':call <SID>NM_show_remove_tag()<CR>',
163 \ '<Space>': ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
164 \ '\|': ':call <SID>NM_show_pipe_message()<CR>',
166 \ '<S-Tab>': ':call <SID>NM_show_previous_fold()<CR>',
167 \ '<Tab>': ':call <SID>NM_show_next_fold()<CR>',
168 \ '<Enter>': ':call <SID>NM_show_toggle_fold()<CR>',
170 \ 'r': ':call <SID>NM_show_reply()<CR>',
171 \ 'm': ':call <SID>NM_new_mail()<CR>',
172 \ '?': ':echo <SID>NM_show_message_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
175 " --- --- bindings for compose screen {{{2
176 let g:notmuch_compose_nmaps = {
177 \ ',s': ':call <SID>NM_compose_send()<CR>',
178 \ ',a': ':call <SID>NM_compose_attach()<CR>',
179 \ ',q': ':call <SID>NM_kill_this_buffer()<CR>',
180 \ '<Tab>': ':call <SID>NM_compose_next_entry_area()<CR>',
182 let g:notmuch_compose_imaps = {
183 \ '<Tab>': '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
186 " --- implement folders screen {{{1
188 function! s:NM_cmd_folders(words)
190 throw 'Not expecting any arguments for folders command.'
195 for entry in g:notmuch_folders
196 let [ name, search ] = entry
197 let data = s:NM_run(cmd + [search])
198 let cnt = matchlist(data, '\(\d\+\)')[1]
199 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
200 call add(searches, search)
203 call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
204 let b:nm_searches = searches
205 let b:nm_timestamp = reltime()
207 call <SID>NM_cmd_folders_mksyntax()
208 call <SID>NM_set_map('n', g:notmuch_folders_maps)
213 function! s:NM_cmd_folders_mksyntax()
216 " --- --- folders screen action functions {{{2
218 function! s:NM_folders_refresh_view()
220 setlocal bufhidden=delete
221 call s:NM_cmd_folders([])
222 exec printf('norm %dG', lno)
225 function! s:NM_folders_show_search()
227 let search = b:nm_searches[line-1]
229 let prev_bufnr = bufnr('%')
230 setlocal bufhidden=hide
231 call <SID>NM_cmd_search([search])
232 setlocal bufhidden=delete
233 let b:nm_prev_bufnr = prev_bufnr
237 " --- implement search screen {{{1
239 function! s:NM_cmd_search(words)
241 if g:notmuch_search_newest_first
242 let cmd = cmd + ['--sort=newest-first']
244 let cmd = cmd + ['--sort=oldest-first']
246 let data = s:NM_run(cmd + a:words)
247 let lines = split(data, "\n")
248 let disp = copy(lines)
249 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
251 call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
252 let b:nm_raw_lines = lines
253 let b:nm_search_words = a:words
255 call <SID>NM_set_map('n', g:notmuch_search_maps)
259 function! s:NM_cmd_search_fmtline(line)
260 let m = matchlist(a:line, '^\(thread:\S\+\)\s\(.\{12\}\) \[\(\d\+\)/\d\+\] \([^;]\+\); \%(\[[^\[]\+\] \)*\(.*\) (\([^(]*\))$')
262 return 'ERROR PARSING: ' . a:line
264 let max = g:notmuch_search_from_column_width
266 for at in split(m[4], '[|,] ')
267 let p = split(at, '[@.]')
270 let from = join(keys(flist), ", ")
271 return printf("%-12s %3s %-20.20s | %s (%s)", m[2], m[3], from, m[5], m[6])
274 " --- --- search screen action functions {{{2
276 function! s:NM_search_show_thread(everything)
277 let words = [ <SID>NM_search_thread_id() ]
278 if !a:everything && exists('b:nm_search_words')
279 call extend(words, ['AND', '('])
280 call extend(words, b:nm_search_words)
283 call <SID>NM_cmd_show(words)
284 let b:nm_show_everything = a:everything
287 function! s:NM_search_prompt()
288 " TODO: input() can support completion
289 let text = input('NotMuch Search: ')
291 let tags = split(text)
293 let tags = s:notmuch_initial_search_words_defaults
295 let prev_bufnr = bufnr('%')
296 if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
297 " TODO: we intend to replace the current buffer,
298 " ... maybe we could just clear it
299 let prev_bufnr = b:nm_prev_bufnr
300 setlocal bufhidden=delete
302 setlocal bufhidden=hide
304 call <SID>NM_cmd_search(tags)
305 setlocal bufhidden=delete
306 let b:nm_prev_bufnr = prev_bufnr
309 function! s:NM_search_edit()
310 " TODO: input() can support completion
311 let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
313 call <SID>NM_cmd_search(split(text))
317 function! s:NM_search_mark_read_thread()
318 call <SID>NM_tag([], ['-unread'])
322 function! s:NM_search_archive_thread()
323 call <SID>NM_tag([], ['-inbox'])
327 function! s:NM_search_mark_read_then_archive_thread()
328 call <SID>NM_tag([], ['-unread', '-inbox'])
332 function! s:NM_search_delete_thread()
333 call <SID>NM_tag([], ['+delete','-inbox','-unread'])
337 function! s:NM_search_filter()
338 call <SID>NM_search_filter_helper('Filter: ', '', '')
341 function! s:NM_search_filter_by_tag()
342 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
345 function! s:NM_search_filter_helper(prompt, prefix, joiner)
346 " TODO: input() can support completion
347 let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
352 let tags = b:nm_search_words + ['AND']
353 \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
355 let prev_bufnr = bufnr('%')
356 setlocal bufhidden=hide
357 call <SID>NM_cmd_search(tags)
358 setlocal bufhidden=delete
359 let b:nm_prev_bufnr = prev_bufnr
362 function! s:NM_search_toggle_order()
363 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
364 " FIXME: maybe this would be better done w/o reading re-reading the lines
365 " reversing the b:nm_raw_lines and the buffer lines would be better
366 call <SID>NM_search_refresh_view()
369 function! s:NM_search_reply_to_thread()
371 call add(cmd, <SID>NM_search_thread_id())
373 call extend(cmd, <SID>NM_get_search_words())
375 let data = <SID>NM_run(cmd)
376 let lines = split(data, "\n")
377 call <SID>NM_newComposeBuffer(lines, 0)
380 function! s:NM_search_add_tags(tags)
381 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
384 function! s:NM_search_remove_tags(tags)
385 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
388 function! s:NM_search_refresh_view()
390 let prev_bufnr = b:nm_prev_bufnr
391 setlocal bufhidden=delete
392 call <SID>NM_cmd_search(b:nm_search_words)
393 let b:nm_prev_bufnr = prev_bufnr
394 " FIXME: should find the line of the thread we were on if possible
395 exec printf('norm %dG', lno)
398 " --- --- search screen helper functions {{{2
400 function! s:NM_search_thread_id()
401 if !exists('b:nm_raw_lines')
402 throw 'Eeek! no b:nm_raw_lines'
404 let mnum = line('.') - 1
405 if len(b:nm_raw_lines) <= mnum
408 let info = b:nm_raw_lines[mnum]
409 let what = split(info, '\s\+')[0]
413 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
414 if type(a:intags) != type([]) || len(a:intags) == 0
415 " TODO: input() can support completion
416 let text = input(a:prompt)
420 let tags = split(text, ' ')
424 call map(tags, 'a:prefix . v:val')
425 call <SID>NM_tag([], tags)
428 " --- implement show screen {{{1
430 function! s:NM_cmd_show(words)
431 let prev_bufnr = bufnr('%')
432 let data = s:NM_run(['show', '--entire-thread'] + a:words)
433 let lines = split(data, "\n")
435 let info = s:NM_cmd_show_parse(lines)
437 setlocal bufhidden=hide
438 call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
439 setlocal bufhidden=delete
440 let b:nm_search_words = a:words
441 let b:nm_raw_info = info
442 let b:nm_prev_bufnr = prev_bufnr
444 call <SID>NM_cmd_show_mkfolds()
445 call <SID>NM_cmd_show_mksyntax()
446 call <SID>NM_set_map('n', g:notmuch_show_maps)
447 setlocal foldtext=NM_cmd_show_foldtext()
449 setlocal foldcolumn=6
453 function! s:NM_show_previous(can_change_thread, find_matching)
454 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
455 let info = b:nm_raw_info
457 for msg in reverse(copy(info['msgs']))
458 if a:find_matching && msg['match'] == '0'
461 if lnum <= msg['start']
465 exec printf('norm %dGzt', msg['start'])
466 " TODO: try to fit the message on screen
469 if !a:can_change_thread
472 call <SID>NM_kill_this_buffer()
475 call <SID>NM_search_show_thread(everything)
477 call <SID>NM_show_previous(0, a:find_matching)
479 echo 'No more messages.'
483 function! s:NM_show_next(can_change_thread, find_matching)
484 let info = b:nm_raw_info
486 for msg in info['msgs']
487 if a:find_matching && msg['match'] == '0'
490 if lnum >= msg['start']
494 exec printf('norm %dGzt', msg['start'])
495 " TODO: try to fit the message on screen
498 if a:can_change_thread
499 call <SID>NM_show_next_thread()
503 function! s:NM_show_next_thread()
504 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
505 call <SID>NM_kill_this_buffer()
506 if line('.') != line('$')
508 call <SID>NM_search_show_thread(everything)
510 echo 'No more messages.'
514 function! s:NM_show_mark_read_thread()
515 call <SID>NM_tag(b:nm_search_words, ['-unread'])
516 call <SID>NM_show_next_thread()
519 function! s:NM_show_archive_thread()
520 call <SID>NM_tag(b:nm_search_words, ['-inbox'])
521 call <SID>NM_show_next_thread()
524 function! s:NM_show_mark_read_then_archive_thread()
525 call <SID>NM_tag(b:nm_search_words, ['-unread', '-inbox'])
526 call <SID>NM_show_next_thread()
529 function! s:NM_show_delete_thread()
530 call <SID>NM_tag(b:nm_search_words, ['+delete', '-inbox', '-unread'])
531 call <SID>NM_show_next_thread()
534 function! s:NM_show_delete_message()
535 let msg = <SID>NM_show_get_message_for_line(line('.'))
536 call <SID>NM_tag([msg['id']], ['+delete', '-inbox', '-unread'])
539 function! s:NM_show_mark_read_then_next_open_message()
540 echo 'not implemented'
543 function! s:NM_show_previous_message()
544 echo 'not implemented'
547 function! s:NM_show_reply()
549 call add(cmd, <SID>NM_show_message_id())
551 call extend(cmd, <SID>NM_get_search_words())
553 let data = <SID>NM_run(cmd)
554 let lines = split(data, "\n")
555 call <SID>NM_newComposeBuffer(lines, 0)
558 function! s:NM_show_view_all_mime_parts()
559 echo 'not implemented'
562 function! s:NM_show_view_raw_message()
563 echo 'not implemented'
566 function! s:NM_show_add_tag()
567 echo 'not implemented'
570 function! s:NM_show_remove_tag()
571 echo 'not implemented'
574 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
575 " otherwise go to next message
576 " any message that is viewed entirely has inbox and unread tags removed
577 function! s:NM_show_advance_marking_read_and_archiving()
578 let advance_tags = ['unread', 'inbox']
580 let vis_top = line('w0')
581 let vis_bot = line('w$')
583 let msg_top = <SID>NM_show_get_message_for_line(vis_top)
584 if !has_key(msg_top,'id')
585 throw "No top visible message."
588 " if the top message is the last message, just expunge the entire thread and move on
589 if msg_top['end'] == line('$')
591 for msg in b:nm_raw_info['msgs']
592 if has_key(msg,'match') && msg['match'] != '0'
593 call add(ids, msg['id'])
596 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
598 \ + <SID>NM_combine_tags('', ids, 'OR', '()')
599 call map(advance_tags, '"-" . v:val')
600 call <SID>NM_tag(filter, advance_tags)
601 call <SID>NM_show_next(1, 1)
605 let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
606 if !has_key(msg_bot,'id')
607 throw "No bottom visible message."
610 " if entire message fits on the screen, read/archive it, move to the next one
611 if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
612 exec printf('norm %dG', vis_top)
613 call <SID>NM_show_next(0, 1)
614 if has_key(msg_top,'match') && msg_top['match'] != '0'
616 " do this last to hide the latency
617 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
618 \ + ['AND', msg_top['id']]
619 call map(advance_tags, '"-" . v:val')
620 call <SID>NM_tag(filter, advance_tags)
625 " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
626 let jmp = winheight(winnr()) / 2
627 let max = msg_bot['end'] - vis_bot
631 exec printf('norm %dGzt', vis_top + jmp)
635 function! s:NM_show_pipe_message()
636 echo 'not implemented'
639 function! s:NM_show_previous_fold()
640 echo 'not implemented'
643 function! s:NM_show_next_fold()
644 echo 'not implemented'
647 function! s:NM_show_toggle_fold()
648 echo 'not implemented'
652 " --- --- show screen helper functions {{{2
654 function! s:NM_show_get_message_for_line(line)
655 for msg in b:nm_raw_info['msgs']
656 if a:line > msg['end']
664 function! s:NM_show_message_id()
665 if !exists('b:nm_raw_info')
666 throw 'Eeek! no b:nm_raw_info'
668 let msg = <SID>NM_show_get_message_for_line(line('.'))
675 function! s:NM_show_fold_toggle(key, type, fold)
676 let info = b:nm_raw_info
681 for fld in info['folds']
686 "let msg = info['msgs'][idx]
687 "if has_key(msg,'match') && msg['match'] == '0'
690 let cls = foldclosed(fld[1])
691 if cls != -1 && cls != fld[1]
694 exec printf('%dfold%s', fld[1], act)
696 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
700 " s:NM_cmd_show_parse returns the following dictionary:
701 " 'disp': lines to display
702 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
703 " 'folds': fold info arrays [ type, start, end ]
704 " 'foldtext': fold text indexed by start line
705 function! s:NM_cmd_show_parse(inlines)
706 let info = { 'disp': [],
725 for line in a:inlines
726 let inlnum = inlnum + 1
732 if match(line, g:notmuch_show_part_end_regexp) != -1
733 let part_end = len(info['disp'])
735 call add(info['disp'], line)
738 if in_part == 'text/plain'
739 if !part_end && mode_type == ''
740 if match(line, g:notmuch_show_signature_regexp) != -1
741 let mode_type = 'sig'
742 let mode_start = len(info['disp'])
743 elseif match(line, g:notmuch_show_citation_regexp) != -1
744 let mode_type = 'cit'
745 let mode_start = len(info['disp'])
747 elseif mode_type == 'cit'
748 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
749 let outlnum = len(info['disp'])
751 let outlnum = outlnum - 1
753 let foldinfo = [ mode_type, mode_start, outlnum, len(info['msgs']),
754 \ printf('[ %d-line citation. Press "c" to show. ]', 1 + outlnum - mode_start) ]
757 elseif mode_type == 'sig'
758 let outlnum = len(info['disp'])
759 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
762 let foldinfo = [ mode_type, mode_start, outlnum, len(info['msgs']),
763 \ printf('[ %d-line signature. Press "i" to show. ]', 1 + outlnum - mode_start) ]
770 " FIXME: this is a hack for handling two folds being added for one line
771 " we should handle adding a fold in a function
772 if len(foldinfo) && foldinfo[1] < foldinfo[2]
773 call add(info['folds'], foldinfo[0:3])
774 let info['foldtext'][foldinfo[1]] = foldinfo[4]
777 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
778 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
780 call add(info['disp'], '')
784 if !has_key(msg,'body_start')
785 let msg['body_start'] = len(info['disp']) + 1
787 if match(line, g:notmuch_show_body_end_regexp) != -1
788 let body_end = len(info['disp'])
789 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
790 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
794 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
795 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
796 let in_part = 'unknown'
800 call add(info['disp'],
801 \ printf('--- %s ---', in_part))
802 " We don't yet handle nested parts, so pop
803 " multipart/* immediately so text/plain
804 " sub-parts are parsed properly
805 if match(in_part, '^multipart/') != -1
808 let part_start = len(info['disp']) + 1
814 let msg['descr'] = line
815 call add(info['disp'], line)
817 let msg['hdr_start'] = len(info['disp']) + 1
820 if match(line, g:notmuch_show_header_end_regexp) != -1
821 let hdr_start = msg['hdr_start']+1
822 let hdr_end = len(info['disp'])
823 let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
824 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
825 let msg['header'] = hdr
829 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
832 if match(g:notmuch_show_headers, m[1]) != -1
833 call add(info['disp'], line)
840 if match(line, g:notmuch_show_message_end_regexp) != -1
841 let msg['end'] = len(info['disp'])
842 call add(info['disp'], '')
844 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
845 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
847 call add(info['msgs'], msg)
854 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
858 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
859 let body_start = len(info['disp']) + 1
865 if match(line, g:notmuch_show_message_begin_regexp) != -1
866 let msg['start'] = len(info['disp']) + 1
868 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
871 let msg['depth'] = m[2]
872 let msg['match'] = m[3]
873 let msg['filename'] = m[4]
880 if len(foldinfo) && foldinfo[1] < foldinfo[2]
881 call add(info['folds'], foldinfo[0:3])
882 let info['foldtext'][foldinfo[1]] = foldinfo[4]
888 function! s:NM_cmd_show_mkfolds()
889 let info = b:nm_raw_info
891 for afold in info['folds']
892 exec printf('%d,%dfold', afold[1], afold[2])
894 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
895 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
896 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
897 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
899 elseif afold[0] == 'msg'
901 let msg = info['msgs'][idx]
902 if has_key(msg,'match') && msg['match'] == '0'
906 exec printf('%dfold%s', afold[1], state)
910 function! s:NM_cmd_show_mksyntax()
911 let info = b:nm_raw_info
913 for msg in info['msgs']
915 let start = msg['start']
916 let hdr_start = msg['hdr_start']
917 let body_start = msg['body_start']
919 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
920 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
921 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
925 function! NM_cmd_show_foldtext()
926 let foldtext = b:nm_raw_info['foldtext']
927 return foldtext[v:foldstart]
931 " --- implement compose screen {{{1
933 function! s:NM_cmd_compose(words, body_lines)
935 let start_on_line = 0
939 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
941 throw 'Eeek! bad parameter ''' . string(word) . ''''
943 let key = substitute(m[1], '\<\w', '\U&', 'g')
944 if !has_key(hdrs, key)
948 call add(hdrs[key], m[2])
952 if !has_key(hdrs, 'From') || !len(hdrs['From'])
953 let me = <SID>NM_compose_get_user_email()
954 let hdrs['From'] = [ me ]
957 for key in g:notmuch_compose_headers
958 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
959 call add(lines, key . ': ' . text)
960 if !start_on_line && !strlen(text)
961 let start_on_line = len(lines)
965 for [key,val] in items(hdrs)
966 if match(g:notmuch_compose_headers, key) == -1
967 let line = key . ': ' . join(val, ', ')
968 call add(lines, line)
974 let start_on_line = len(lines) + 1
978 call extend(lines, a:body_lines)
980 call extend(lines, [ '', '' ])
983 call <SID>NM_newComposeBuffer(lines, start_on_line)
986 function! s:NM_compose_send()
987 call <SID>NM_assert_buffer_type('compose')
988 let fname = expand('%')
990 let line = getline(lnum)
992 while match(line, '^$') == -1
993 if !exists("hdr_starts") && match(line, '^Notmuch-Help:') == -1
994 let hdr_starts = lnum - 1
997 let line = getline(lnum)
999 let body_starts = lnum - 1
1001 call append(body_starts, 'Date: ' . strftime('%a, %d %b %Y %H:%M:%S %z'))
1002 exec printf(':0,%dd', hdr_starts)
1005 let line = getline(1)
1006 let m = matchlist(line, '^From:\s*\(.*\)\s*<\(.*\)>$')
1010 let m = matchlist(line, '^From:\s*\(.*\)$')
1014 let cmdtxt = g:notmuch_sendmail . ' -t -f ' . from . ' < ' . fname
1015 let out = system(cmdtxt)
1016 let err = v:shell_error
1020 call <SID>NM_newBuffer('new', 'error',
1021 \ "While running...\n" .
1022 \ ' ' . cmdtxt . "\n" .
1024 \ "Failed with...\n" .
1025 \ substitute(out, '^', ' ', 'g'))
1027 echo 'Eeek! unable to send mail'
1032 if !exists('b:nm_prev_bufnr')
1035 let prev_bufnr = b:nm_prev_bufnr
1037 if prev_bufnr == bufnr('%')
1038 exec printf("buffer %d", prev_bufnr)
1042 echo 'Mail sent successfully.'
1045 function! s:NM_compose_attach()
1046 echo 'not implemented'
1049 function! s:NM_compose_next_entry_area()
1050 let lnum = line('.')
1051 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1054 let line = getline(lnum)
1055 if match(line, '^\([^:]\+\):\s*$') == -1
1056 call cursor(lnum, strlen(line) + 1)
1059 while match(getline(lnum+1), '^\s') != -1
1062 call cursor(lnum, strlen(getline(lnum)) + 1)
1065 elseif lnum == hdr_end
1066 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1070 if !getbufvar(bufnr('.'), '&et')
1074 let shiftwidth = a:shiftwidth
1075 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1076 " we assume no one has shiftwidth set to more than 40 :)
1077 return ' '[0:shiftwidth]
1081 " --- --- compose screen helper functions {{{2
1083 function! s:NM_compose_get_user_email()
1084 " TODO: do this properly (still), i.e., allow for multiple email accounts
1085 let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1089 function! s:NM_compose_find_line_match(start, pattern, failure)
1091 let lend = line('$')
1093 if match(getline(lnum), a:pattern) != -1
1102 " --- notmuch helper functions {{{1
1104 function! s:NM_newBuffer(how, type, content)
1110 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1111 silent put=a:content
1113 setlocal nomodifiable
1114 execute printf('set filetype=notmuch-%s', a:type)
1115 execute printf('set syntax=notmuch-%s', a:type)
1116 let b:nm_type = a:type
1119 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1120 let fdir = expand(a:fdir)
1121 if !isdirectory(fdir)
1122 call mkdir(fdir, 'p')
1124 let file_name = <SID>NM_mktemp(fdir, a:fname)
1125 if writefile(a:lines, file_name)
1126 throw 'Eeek! couldn''t write to temporary file ' . file_name
1128 exec printf('edit %s', file_name)
1129 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1130 execute printf('set filetype=notmuch-%s', a:type)
1131 execute printf('set syntax=notmuch-%s', a:type)
1132 let b:nm_type = a:type
1135 function! s:NM_newComposeBuffer(lines, start_on_line)
1137 let start_on_line = a:start_on_line
1138 let real_hdr_start = 1
1139 if g:notmuch_compose_header_help
1141 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1142 \ 'Notmuch-Help: ,a - attach a file',
1143 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
1144 \ 'Notmuch-Help: ,q - abort the message',
1145 \ 'Notmuch-Help: <Tab> - skip through header lines',
1147 call extend(lines, help_lines, 0)
1148 let real_hdr_start = len(help_lines)
1149 if start_on_line > 0
1150 let start_on_line = start_on_line + len(help_lines)
1153 call extend(lines, g:notmuch_signature)
1156 let prev_bufnr = bufnr('%')
1157 setlocal bufhidden=hide
1158 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1160 setlocal bufhidden=hide
1161 let b:nm_prev_bufnr = prev_bufnr
1163 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1164 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1166 if start_on_line > 0 && start_on_line <= len(lines)
1167 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1169 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1170 call <SID>NM_compose_next_entry_area()
1173 if g:notmuch_compose_insert_mode_start
1176 echo 'Type your message, use <TAB> to jump to next header and then body.'
1179 function! s:NM_assert_buffer_type(type)
1180 if !exists('b:nm_type') || b:nm_type != a:type
1181 throw printf('Eeek! expected type %s, but got %s.', a:type,
1182 \ exists(b:nm_type) ? b:nm_type : 'something else')
1186 function! s:NM_mktemp(dir, name)
1187 let time_stamp = strftime('%Y%m%d-%H%M%S')
1188 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1189 " TODO: check if it exists, try again
1193 function! s:NM_shell_escape(word)
1194 " TODO: use shellescape()
1195 let word = substitute(a:word, '''', '\\''', 'g')
1196 return '''' . word . ''''
1199 " this function was taken from git.vim, then fixed up
1200 " http://github.com/motemen/git-vim
1201 function! s:NM_shell_split(cmd)
1202 let l:split_cmd = []
1206 let t = match(cmd, '\S', iStart)
1212 let iSpace = match(cmd, '\v(\s|$)', iStart)
1217 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1218 if iQuote1 > iSpace || iQuote1 < iStart
1219 let iEnd = iSpace - 1
1220 let l:split_cmd += [ cmd[iStart : iEnd] ]
1222 let q = cmd[iQuote1]
1223 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1224 if iQuote2 < iQuote1
1225 throw 'No matching ' . q . ' quote'
1228 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1232 let iStart = iEnd + 1
1239 function! s:NM_run(args)
1241 call map(words, 's:NM_shell_escape(v:val)')
1242 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1244 if exists('g:notmuch_debug') && g:notmuch_debug
1245 let start = reltime()
1246 let out = system(cmd)
1247 let err = v:shell_error
1248 let delta = reltime(start)
1250 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1252 let out = system(cmd)
1253 let err = v:shell_error
1258 echo substitute(out, '\n*$', '', '')
1266 " --- external mail handling helpers {{{1
1268 function! s:NM_new_mail()
1269 call <SID>NM_cmd_compose([], [])
1272 " --- tag manipulation helpers {{{1
1274 " used to combine an array of words with prefixes and separators
1276 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1277 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1278 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1281 if len(res) && strlen(a:separator)
1282 call add(res, a:separator)
1284 call add(res, a:word_prefix . word)
1286 if len(res) > 1 && strlen(a:brackets)
1287 if strlen(a:brackets) != 2
1288 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1290 call insert(res, a:brackets[0])
1291 call add(res, a:brackets[1])
1296 " --- other helpers {{{1
1298 function! s:NM_get_search_words()
1299 if !exists('b:nm_search_words')
1300 throw 'Eeek! no b:nm_search_words'
1302 return b:nm_search_words
1305 function! s:NM_kill_this_buffer()
1306 if exists('b:nm_prev_bufnr')
1307 let prev_bufnr = b:nm_prev_bufnr
1309 exec printf("buffer %d", prev_bufnr)
1311 echo "This is the last buffer; use :q<CR> to quit."
1315 function! s:NM_search_expand(arg)
1316 let word = expand(a:arg)
1317 let prev_bufnr = bufnr('%')
1318 setlocal bufhidden=hide
1319 call <SID>NM_cmd_search([word])
1320 setlocal bufhidden=delete
1321 let b:nm_prev_bufnr = prev_bufnr
1324 function! s:NM_tag(filter, tags)
1325 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1327 throw 'Eeek! I couldn''t find the thread id!'
1330 call extend(args, a:tags)
1331 call add(args, '--')
1332 call extend(args, filter)
1333 " TODO: handle errors
1334 call <SID>NM_run(args)
1337 " --- process and set the defaults {{{1
1339 function! NM_set_defaults(force)
1340 for [key, dflt] in items(s:notmuch_defaults)
1342 if !a:force && exists(key) && type(dflt) == type(eval(key))
1344 elseif type(dflt) == type(0)
1345 let cmd = printf('let %s = %d', key, dflt)
1346 elseif type(dflt) == type('')
1347 let cmd = printf('let %s = ''%s''', key, dflt)
1348 " FIXME: not sure why this didn't work when dflt is an array
1349 "elseif type(dflt) == type([])
1350 " let cmd = printf('let %s = %s', key, string(dflt))
1352 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1353 \ a:force, key, string(dflt))
1359 call NM_set_defaults(0)
1361 " for some reason NM_set_defaults() didn't work for arrays...
1362 if !exists('g:notmuch_show_headers')
1363 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1365 if !exists('g:notmuch_initial_search_words')
1366 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1368 if !exists('g:notmuch_folders')
1369 let g:notmuch_folders = s:notmuch_folders_defaults
1372 if !exists('g:notmuch_signature')
1373 let g:notmuch_signature = s:notmuch_signature_defaults
1375 if !exists('g:notmuch_compose_headers')
1376 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1379 " --- assign keymaps {{{1
1381 function! s:NM_set_map(type, maps)
1383 for [key, code] in items(a:maps)
1384 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1386 " --- this is a hack for development :)
1387 nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1390 " --- command handler {{{1
1392 function! NotMuch(args)
1395 let args = 'folders'
1398 let words = <SID>NM_shell_split(args)
1399 if words[0] == 'folders' || words[0] == 'f'
1400 let words = words[1:]
1401 call <SID>NM_cmd_folders(words)
1403 elseif words[0] == 'search' || words[0] == 's'
1405 let words = words[1:]
1406 elseif exists('b:nm_search_words')
1407 let words = b:nm_search_words
1409 let words = g:notmuch_initial_search_words
1411 call <SID>NM_cmd_search(words)
1413 elseif words[0] == 'show'
1414 echoe 'show is not yet implemented.'
1416 elseif words[0] == 'new' || words[0] == 'compose'
1417 let words = words[1:]
1418 call <SID>NM_cmd_compose(words, [])
1421 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1428 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1429 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1431 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :