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]*\) excluded:\([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['excluded'] = m[4]
874 let msg['filename'] = m[5]
881 if len(foldinfo) && foldinfo[1] < foldinfo[2]
882 call add(info['folds'], foldinfo[0:3])
883 let info['foldtext'][foldinfo[1]] = foldinfo[4]
889 function! s:NM_cmd_show_mkfolds()
890 let info = b:nm_raw_info
892 for afold in info['folds']
893 exec printf('%d,%dfold', afold[1], afold[2])
895 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
896 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
897 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
898 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
900 elseif afold[0] == 'msg'
902 let msg = info['msgs'][idx]
903 if has_key(msg,'match') && msg['match'] == '0'
907 exec printf('%dfold%s', afold[1], state)
911 function! s:NM_cmd_show_mksyntax()
912 let info = b:nm_raw_info
914 for msg in info['msgs']
916 let start = msg['start']
917 let hdr_start = msg['hdr_start']
918 let body_start = msg['body_start']
920 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
921 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
922 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
926 function! NM_cmd_show_foldtext()
927 let foldtext = b:nm_raw_info['foldtext']
928 return foldtext[v:foldstart]
932 " --- implement compose screen {{{1
934 function! s:NM_cmd_compose(words, body_lines)
936 let start_on_line = 0
940 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
942 throw 'Eeek! bad parameter ''' . string(word) . ''''
944 let key = substitute(m[1], '\<\w', '\U&', 'g')
945 if !has_key(hdrs, key)
949 call add(hdrs[key], m[2])
953 if !has_key(hdrs, 'From') || !len(hdrs['From'])
954 let me = <SID>NM_compose_get_user_email()
955 let hdrs['From'] = [ me ]
958 for key in g:notmuch_compose_headers
959 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
960 call add(lines, key . ': ' . text)
961 if !start_on_line && !strlen(text)
962 let start_on_line = len(lines)
966 for [key,val] in items(hdrs)
967 if match(g:notmuch_compose_headers, key) == -1
968 let line = key . ': ' . join(val, ', ')
969 call add(lines, line)
975 let start_on_line = len(lines) + 1
979 call extend(lines, a:body_lines)
981 call extend(lines, [ '', '' ])
984 call <SID>NM_newComposeBuffer(lines, start_on_line)
987 function! s:NM_compose_send()
988 call <SID>NM_assert_buffer_type('compose')
989 let fname = expand('%')
991 let line = getline(lnum)
993 while match(line, '^$') == -1
994 if !exists("hdr_starts") && match(line, '^Notmuch-Help:') == -1
995 let hdr_starts = lnum - 1
998 let line = getline(lnum)
1000 let body_starts = lnum - 1
1002 call append(body_starts, 'Date: ' . strftime('%a, %d %b %Y %H:%M:%S %z'))
1003 exec printf(':0,%dd', hdr_starts)
1006 let line = getline(1)
1007 let m = matchlist(line, '^From:\s*\(.*\)\s*<\(.*\)>$')
1011 let m = matchlist(line, '^From:\s*\(.*\)$')
1015 let cmdtxt = g:notmuch_sendmail . ' -t -f ' . from . ' < ' . fname
1016 let out = system(cmdtxt)
1017 let err = v:shell_error
1021 call <SID>NM_newBuffer('new', 'error',
1022 \ "While running...\n" .
1023 \ ' ' . cmdtxt . "\n" .
1025 \ "Failed with...\n" .
1026 \ substitute(out, '^', ' ', 'g'))
1028 echo 'Eeek! unable to send mail'
1033 if !exists('b:nm_prev_bufnr')
1036 let prev_bufnr = b:nm_prev_bufnr
1038 if prev_bufnr == bufnr('%')
1039 exec printf("buffer %d", prev_bufnr)
1043 echo 'Mail sent successfully.'
1046 function! s:NM_compose_attach()
1047 echo 'not implemented'
1050 function! s:NM_compose_next_entry_area()
1051 let lnum = line('.')
1052 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1055 let line = getline(lnum)
1056 if match(line, '^\([^:]\+\):\s*$') == -1
1057 call cursor(lnum, strlen(line) + 1)
1060 while match(getline(lnum+1), '^\s') != -1
1063 call cursor(lnum, strlen(getline(lnum)) + 1)
1066 elseif lnum == hdr_end
1067 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1071 if !getbufvar(bufnr('.'), '&et')
1075 let shiftwidth = a:shiftwidth
1076 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1077 " we assume no one has shiftwidth set to more than 40 :)
1078 return ' '[0:shiftwidth]
1082 " --- --- compose screen helper functions {{{2
1084 function! s:NM_compose_get_user_email()
1085 " TODO: do this properly (still), i.e., allow for multiple email accounts
1086 let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1090 function! s:NM_compose_find_line_match(start, pattern, failure)
1092 let lend = line('$')
1094 if match(getline(lnum), a:pattern) != -1
1103 " --- notmuch helper functions {{{1
1105 function! s:NM_newBuffer(how, type, content)
1111 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1112 silent put=a:content
1114 setlocal nomodifiable
1115 execute printf('set filetype=notmuch-%s', a:type)
1116 execute printf('set syntax=notmuch-%s', a:type)
1117 let b:nm_type = a:type
1120 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1121 let fdir = expand(a:fdir)
1122 if !isdirectory(fdir)
1123 call mkdir(fdir, 'p')
1125 let file_name = <SID>NM_mktemp(fdir, a:fname)
1126 if writefile(a:lines, file_name)
1127 throw 'Eeek! couldn''t write to temporary file ' . file_name
1129 exec printf('edit %s', file_name)
1130 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1131 execute printf('set filetype=notmuch-%s', a:type)
1132 execute printf('set syntax=notmuch-%s', a:type)
1133 let b:nm_type = a:type
1136 function! s:NM_newComposeBuffer(lines, start_on_line)
1138 let start_on_line = a:start_on_line
1139 let real_hdr_start = 1
1140 if g:notmuch_compose_header_help
1142 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1143 \ 'Notmuch-Help: ,a - attach a file',
1144 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
1145 \ 'Notmuch-Help: ,q - abort the message',
1146 \ 'Notmuch-Help: <Tab> - skip through header lines',
1148 call extend(lines, help_lines, 0)
1149 let real_hdr_start = len(help_lines)
1150 if start_on_line > 0
1151 let start_on_line = start_on_line + len(help_lines)
1154 call extend(lines, g:notmuch_signature)
1157 let prev_bufnr = bufnr('%')
1158 setlocal bufhidden=hide
1159 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1161 setlocal bufhidden=hide
1162 let b:nm_prev_bufnr = prev_bufnr
1164 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1165 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1167 if start_on_line > 0 && start_on_line <= len(lines)
1168 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1170 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1171 call <SID>NM_compose_next_entry_area()
1174 if g:notmuch_compose_insert_mode_start
1177 echo 'Type your message, use <TAB> to jump to next header and then body.'
1180 function! s:NM_assert_buffer_type(type)
1181 if !exists('b:nm_type') || b:nm_type != a:type
1182 throw printf('Eeek! expected type %s, but got %s.', a:type,
1183 \ exists(b:nm_type) ? b:nm_type : 'something else')
1187 function! s:NM_mktemp(dir, name)
1188 let time_stamp = strftime('%Y%m%d-%H%M%S')
1189 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1190 " TODO: check if it exists, try again
1194 function! s:NM_shell_escape(word)
1195 " TODO: use shellescape()
1196 let word = substitute(a:word, '''', '\\''', 'g')
1197 return '''' . word . ''''
1200 " this function was taken from git.vim, then fixed up
1201 " http://github.com/motemen/git-vim
1202 function! s:NM_shell_split(cmd)
1203 let l:split_cmd = []
1207 let t = match(cmd, '\S', iStart)
1213 let iSpace = match(cmd, '\v(\s|$)', iStart)
1218 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1219 if iQuote1 > iSpace || iQuote1 < iStart
1220 let iEnd = iSpace - 1
1221 let l:split_cmd += [ cmd[iStart : iEnd] ]
1223 let q = cmd[iQuote1]
1224 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1225 if iQuote2 < iQuote1
1226 throw 'No matching ' . q . ' quote'
1229 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1233 let iStart = iEnd + 1
1240 function! s:NM_run(args)
1242 call map(words, 's:NM_shell_escape(v:val)')
1243 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1245 if exists('g:notmuch_debug') && g:notmuch_debug
1246 let start = reltime()
1247 let out = system(cmd)
1248 let err = v:shell_error
1249 let delta = reltime(start)
1251 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1253 let out = system(cmd)
1254 let err = v:shell_error
1259 echo substitute(out, '\n*$', '', '')
1267 " --- external mail handling helpers {{{1
1269 function! s:NM_new_mail()
1270 call <SID>NM_cmd_compose([], [])
1273 " --- tag manipulation helpers {{{1
1275 " used to combine an array of words with prefixes and separators
1277 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1278 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1279 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1282 if len(res) && strlen(a:separator)
1283 call add(res, a:separator)
1285 call add(res, a:word_prefix . word)
1287 if len(res) > 1 && strlen(a:brackets)
1288 if strlen(a:brackets) != 2
1289 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1291 call insert(res, a:brackets[0])
1292 call add(res, a:brackets[1])
1297 " --- other helpers {{{1
1299 function! s:NM_get_search_words()
1300 if !exists('b:nm_search_words')
1301 throw 'Eeek! no b:nm_search_words'
1303 return b:nm_search_words
1306 function! s:NM_kill_this_buffer()
1307 if exists('b:nm_prev_bufnr')
1308 let prev_bufnr = b:nm_prev_bufnr
1310 exec printf("buffer %d", prev_bufnr)
1312 echo "This is the last buffer; use :q<CR> to quit."
1316 function! s:NM_search_expand(arg)
1317 let word = expand(a:arg)
1318 let prev_bufnr = bufnr('%')
1319 setlocal bufhidden=hide
1320 call <SID>NM_cmd_search([word])
1321 setlocal bufhidden=delete
1322 let b:nm_prev_bufnr = prev_bufnr
1325 function! s:NM_tag(filter, tags)
1326 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1328 throw 'Eeek! I couldn''t find the thread id!'
1331 call extend(args, a:tags)
1332 call add(args, '--')
1333 call extend(args, filter)
1334 " TODO: handle errors
1335 call <SID>NM_run(args)
1338 " --- process and set the defaults {{{1
1340 function! NM_set_defaults(force)
1341 for [key, dflt] in items(s:notmuch_defaults)
1343 if !a:force && exists(key) && type(dflt) == type(eval(key))
1345 elseif type(dflt) == type(0)
1346 let cmd = printf('let %s = %d', key, dflt)
1347 elseif type(dflt) == type('')
1348 let cmd = printf('let %s = ''%s''', key, dflt)
1349 " FIXME: not sure why this didn't work when dflt is an array
1350 "elseif type(dflt) == type([])
1351 " let cmd = printf('let %s = %s', key, string(dflt))
1353 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1354 \ a:force, key, string(dflt))
1360 call NM_set_defaults(0)
1362 " for some reason NM_set_defaults() didn't work for arrays...
1363 if !exists('g:notmuch_show_headers')
1364 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1366 if !exists('g:notmuch_initial_search_words')
1367 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1369 if !exists('g:notmuch_folders')
1370 let g:notmuch_folders = s:notmuch_folders_defaults
1373 if !exists('g:notmuch_signature')
1374 let g:notmuch_signature = s:notmuch_signature_defaults
1376 if !exists('g:notmuch_compose_headers')
1377 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1380 " --- assign keymaps {{{1
1382 function! s:NM_set_map(type, maps)
1384 for [key, code] in items(a:maps)
1385 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1387 " --- this is a hack for development :)
1388 nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1391 " --- command handler {{{1
1393 function! NotMuch(args)
1396 let args = 'folders'
1399 let words = <SID>NM_shell_split(args)
1400 if words[0] == 'folders' || words[0] == 'f'
1401 let words = words[1:]
1402 call <SID>NM_cmd_folders(words)
1404 elseif words[0] == 'search' || words[0] == 's'
1406 let words = words[1:]
1407 elseif exists('b:nm_search_words')
1408 let words = b:nm_search_words
1410 let words = g:notmuch_initial_search_words
1412 call <SID>NM_cmd_search(words)
1414 elseif words[0] == 'show'
1415 echoe 'show is not yet implemented.'
1417 elseif words[0] == 'new' || words[0] == 'compose'
1418 let words = words[1:]
1419 call <SID>NM_cmd_compose(words, [])
1422 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1429 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1430 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1432 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :