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_debug': 0 ,
30 \ 'g:notmuch_search_newest_first': 1 ,
31 \ 'g:notmuch_search_from_column_width': 20 ,
33 \ 'g:notmuch_show_fold_signatures': 1 ,
34 \ 'g:notmuch_show_fold_citations': 1 ,
35 \ 'g:notmuch_show_fold_bodies': 0 ,
36 \ 'g:notmuch_show_fold_headers': 1 ,
38 \ 'g:notmuch_show_message_begin_regexp': '
\fmessage{' ,
39 \ 'g:notmuch_show_message_end_regexp': '
\fmessage}' ,
40 \ 'g:notmuch_show_header_begin_regexp': '
\fheader{' ,
41 \ 'g:notmuch_show_header_end_regexp': '
\fheader}' ,
42 \ 'g:notmuch_show_body_begin_regexp': '
\fbody{' ,
43 \ 'g:notmuch_show_body_end_regexp': '
\fbody}' ,
44 \ 'g:notmuch_show_attachment_begin_regexp': '
\fattachment{' ,
45 \ 'g:notmuch_show_attachment_end_regexp': '
\fattachment}' ,
46 \ 'g:notmuch_show_part_begin_regexp': '
\fpart{' ,
47 \ 'g:notmuch_show_part_end_regexp': '
\fpart}' ,
48 \ 'g:notmuch_show_marker_regexp': '
\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
50 \ 'g:notmuch_show_message_parse_regexp': '\(id:[^ ]*\) depth:\([0-9]*\) match:\([0-9]*\) filename:\(.*\)$',
51 \ 'g:notmuch_show_tags_regexp': '(\([^)]*\))$' ,
53 \ 'g:notmuch_show_signature_regexp': '^\(-- \?\|_\+\)$' ,
54 \ 'g:notmuch_show_signature_lines_max': 12 ,
56 \ 'g:notmuch_show_citation_regexp': '^\s*>' ,
58 \ 'g:notmuch_compose_insert_mode_start': 1 ,
59 \ 'g:notmuch_compose_header_help': 1 ,
60 \ 'g:notmuch_compose_temp_file_dir': '~/.notmuch/compose/' ,
63 " defaults for g:notmuch_initial_search_words
64 " override with: let g:notmuch_initial_search_words = [ ... ]
65 let s:notmuch_initial_search_words_defaults = [
66 \ 'tag:inbox and tag:unread',
69 " defaults for g:notmuch_show_headers
70 " override with: let g:notmuch_show_headers = [ ... ]
71 let s:notmuch_show_headers_defaults = [
79 " defaults for g:notmuch_folders
80 " override with: let g:notmuch_folders = [ ... ]
81 let s:notmuch_folders_defaults = [
82 \ [ 'new', 'tag:inbox and tag:unread' ],
83 \ [ 'inbox', 'tag:inbox' ],
84 \ [ 'unread', 'tag:unread' ],
87 " defaults for g:notmuch_signature
88 " override with: let g:notmuch_signature = [ ... ]
89 let s:notmuch_signature_defaults = [
92 \ 'email sent from notmuch.vim plugin'
95 " defaults for g:notmuch_compose_headers
96 " override with: let g:notmuch_compose_headers = [ ... ]
97 let s:notmuch_compose_headers_defaults = [
105 " --- keyboard mapping definitions {{{1
107 " --- --- bindings for folders mode {{{2
109 let g:notmuch_folders_maps = {
110 \ 'm': ':call <SID>NM_new_mail()<CR>',
111 \ 's': ':call <SID>NM_search_prompt()<CR>',
112 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
113 \ '=': ':call <SID>NM_folders_refresh_view()<CR>',
114 \ '<Enter>': ':call <SID>NM_folders_show_search()<CR>',
117 " --- --- bindings for search screen {{{2
118 let g:notmuch_search_maps = {
119 \ '<Space>': ':call <SID>NM_search_show_thread(0)<CR>',
120 \ '<Enter>': ':call <SID>NM_search_show_thread(1)<CR>',
121 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
122 \ 'a': ':call <SID>NM_search_archive_thread()<CR>',
123 \ 'A': ':call <SID>NM_search_mark_read_then_archive_thread()<CR>',
124 \ 'f': ':call <SID>NM_search_filter()<CR>',
125 \ 'm': ':call <SID>NM_new_mail()<CR>',
126 \ 'o': ':call <SID>NM_search_toggle_order()<CR>',
127 \ 'r': ':call <SID>NM_search_reply_to_thread()<CR>',
128 \ 's': ':call <SID>NM_search_prompt()<CR>',
129 \ ',s': ':call <SID>NM_search_edit()<CR>',
130 \ 't': ':call <SID>NM_search_filter_by_tag()<CR>',
131 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
132 \ '+': ':call <SID>NM_search_add_tags([])<CR>',
133 \ '-': ':call <SID>NM_search_remove_tags([])<CR>',
134 \ '=': ':call <SID>NM_search_refresh_view()<CR>',
135 \ '?': ':echo <SID>NM_search_thread_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
138 " --- --- bindings for show screen {{{2
139 let g:notmuch_show_maps = {
140 \ '<C-P>': ':call <SID>NM_show_previous(1, 0)<CR>',
141 \ '<C-N>': ':call <SID>NM_show_next(1, 0)<CR>',
142 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
143 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
144 \ 's': ':call <SID>NM_search_prompt()<CR>',
146 \ 'b': ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
147 \ 'c': ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
148 \ 'h': ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
149 \ 'i': ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
151 \ 'a': ':call <SID>NM_show_archive_thread()<CR>',
152 \ 'A': ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
153 \ 'N': ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
154 \ 'v': ':call <SID>NM_show_view_all_mime_parts()<CR>',
155 \ '+': ':call <SID>NM_show_add_tag()<CR>',
156 \ '-': ':call <SID>NM_show_remove_tag()<CR>',
157 \ '<Space>': ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
158 \ '\|': ':call <SID>NM_show_pipe_message()<CR>',
160 \ '<S-Tab>': ':call <SID>NM_show_previous_fold()<CR>',
161 \ '<Tab>': ':call <SID>NM_show_next_fold()<CR>',
162 \ '<Enter>': ':call <SID>NM_show_toggle_fold()<CR>',
164 \ 'r': ':call <SID>NM_show_reply()<CR>',
165 \ 'm': ':call <SID>NM_new_mail()<CR>',
166 \ '?': ':echo <SID>NM_show_message_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
169 " --- --- bindings for compose screen {{{2
170 let g:notmuch_compose_nmaps = {
171 \ ',s': ':call <SID>NM_compose_send()<CR>',
172 \ ',a': ':call <SID>NM_compose_attach()<CR>',
173 \ ',q': ':call <SID>NM_kill_this_buffer()<CR>',
174 \ '<Tab>': ':call <SID>NM_compose_next_entry_area()<CR>',
176 let g:notmuch_compose_imaps = {
177 \ '<Tab>': '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
180 " --- implement folders screen {{{1
182 function! s:NM_cmd_folders(words)
184 throw 'Not expecting any arguments for folders command.'
189 for entry in g:notmuch_folders
190 let [ name, search ] = entry
191 let data = s:NM_run(cmd + [search])
192 let cnt = matchlist(data, '\(\d\+\)')[1]
193 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
194 call add(searches, search)
197 call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
198 let b:nm_searches = searches
199 let b:nm_timestamp = reltime()
201 call <SID>NM_cmd_folders_mksyntax()
202 call <SID>NM_set_map('n', g:notmuch_folders_maps)
207 function! s:NM_cmd_folders_mksyntax()
210 " --- --- folders screen action functions {{{2
212 function! s:NM_folders_refresh_view()
214 setlocal bufhidden=delete
215 call s:NM_cmd_folders([])
216 exec printf('norm %dG', lno)
219 function! s:NM_folders_show_search()
221 let search = b:nm_searches[line-1]
223 let prev_bufnr = bufnr('%')
224 setlocal bufhidden=hide
225 call <SID>NM_cmd_search([search])
226 setlocal bufhidden=delete
227 let b:nm_prev_bufnr = prev_bufnr
231 " --- implement search screen {{{1
233 function! s:NM_cmd_search(words)
235 if g:notmuch_search_newest_first
236 let cmd = cmd + ['--sort=newest-first']
238 let cmd = cmd + ['--sort=oldest-first']
240 let data = s:NM_run(cmd + a:words)
241 let lines = split(data, "\n")
242 let disp = copy(lines)
243 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
245 call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
246 let b:nm_raw_lines = lines
247 let b:nm_search_words = a:words
249 call <SID>NM_set_map('n', g:notmuch_search_maps)
253 function! s:NM_cmd_search_fmtline(line)
254 let m = matchlist(a:line, '^\(thread:\S\+\)\s\(.\{12\}\) \[\(\d\+\)/\d\+\] \([^;]\+\); \%(\[[^\[]\+\] \)*\(.*\) (\([^(]*\))$')
256 return 'ERROR PARSING: ' . a:line
258 let max = g:notmuch_search_from_column_width
260 for at in split(m[4], ", ")
261 let p = min([stridx(at, "."), stridx(at, "@")])
262 call insert(flist, tolower(at[0:p - 1]))
264 let from = join(flist, ", ")
265 return printf("%-12s %3s %-20.20s | %s (%s)", m[2], m[3], from, m[5], m[6])
268 " --- --- search screen action functions {{{2
270 function! s:NM_search_show_thread(everything)
271 let words = [ <SID>NM_search_thread_id() ]
272 if !a:everything && exists('b:nm_search_words')
273 call extend(words, ['AND', '('])
274 call extend(words, b:nm_search_words)
277 call <SID>NM_cmd_show(words)
278 let b:nm_show_everything = a:everything
281 function! s:NM_search_prompt()
282 " TODO: input() can support completion
283 let text = input('NotMuch Search: ')
285 let tags = split(text)
287 let tags = s:notmuch_initial_search_words_defaults
289 let prev_bufnr = bufnr('%')
290 if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
291 " TODO: we intend to replace the current buffer,
292 " ... maybe we could just clear it
293 let prev_bufnr = b:nm_prev_bufnr
294 setlocal bufhidden=delete
296 setlocal bufhidden=hide
298 call <SID>NM_cmd_search(tags)
299 setlocal bufhidden=delete
300 let b:nm_prev_bufnr = prev_bufnr
303 function! s:NM_search_edit()
304 " TODO: input() can support completion
305 let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
307 call <SID>NM_cmd_search(split(text))
311 function! s:NM_search_archive_thread()
312 call <SID>NM_tag([], ['-inbox'])
316 function! s:NM_search_mark_read_then_archive_thread()
317 call <SID>NM_tag([], ['-unread', '-inbox'])
321 function! s:NM_search_filter()
322 call <SID>NM_search_filter_helper('Filter: ', '', '')
325 function! s:NM_search_filter_by_tag()
326 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
329 function! s:NM_search_filter_helper(prompt, prefix, joiner)
330 " TODO: input() can support completion
331 let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
336 let tags = b:nm_search_words + ['AND']
337 \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
339 let prev_bufnr = bufnr('%')
340 setlocal bufhidden=hide
341 call <SID>NM_cmd_search(tags)
342 setlocal bufhidden=delete
343 let b:nm_prev_bufnr = prev_bufnr
346 function! s:NM_search_toggle_order()
347 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
348 " FIXME: maybe this would be better done w/o reading re-reading the lines
349 " reversing the b:nm_raw_lines and the buffer lines would be better
350 call <SID>NM_search_refresh_view()
353 function! s:NM_search_reply_to_thread()
355 call add(cmd, <SID>NM_search_thread_id())
357 call extend(cmd, <SID>NM_get_search_words())
359 let data = <SID>NM_run(cmd)
360 let lines = split(data, "\n")
361 call <SID>NM_newComposeBuffer(lines, 0)
364 function! s:NM_search_add_tags(tags)
365 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
368 function! s:NM_search_remove_tags(tags)
369 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
372 function! s:NM_search_refresh_view()
374 let prev_bufnr = b:nm_prev_bufnr
375 setlocal bufhidden=delete
376 call <SID>NM_cmd_search(b:nm_search_words)
377 let b:nm_prev_bufnr = prev_bufnr
378 " FIXME: should find the line of the thread we were on if possible
379 exec printf('norm %dG', lno)
382 " --- --- search screen helper functions {{{2
384 function! s:NM_search_thread_id()
385 if !exists('b:nm_raw_lines')
386 throw 'Eeek! no b:nm_raw_lines'
388 let mnum = line('.') - 1
389 if len(b:nm_raw_lines) <= mnum
392 let info = b:nm_raw_lines[mnum]
393 let what = split(info, '\s\+')[0]
397 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
398 if type(a:intags) != type([]) || len(a:intags) == 0
399 " TODO: input() can support completion
400 let text = input(a:prompt)
404 let tags = split(text, ' ')
408 call map(tags, 'a:prefix . v:val')
409 call <SID>NM_tag([], tags)
412 " --- implement show screen {{{1
414 function! s:NM_cmd_show(words)
415 let prev_bufnr = bufnr('%')
416 let data = s:NM_run(['show', '--entire-thread'] + a:words)
417 let lines = split(data, "\n")
419 let info = s:NM_cmd_show_parse(lines)
421 setlocal bufhidden=hide
422 call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
423 setlocal bufhidden=delete
424 let b:nm_search_words = a:words
425 let b:nm_raw_info = info
426 let b:nm_prev_bufnr = prev_bufnr
428 call <SID>NM_cmd_show_mkfolds()
429 call <SID>NM_cmd_show_mksyntax()
430 call <SID>NM_set_map('n', g:notmuch_show_maps)
431 setlocal foldtext=NM_cmd_show_foldtext()
433 setlocal foldcolumn=6
437 function! s:NM_show_previous(can_change_thread, find_matching)
438 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
439 let info = b:nm_raw_info
441 for msg in reverse(copy(info['msgs']))
442 if a:find_matching && msg['match'] == '0'
445 if lnum <= msg['start']
449 exec printf('norm %dGzt', msg['start'])
450 " TODO: try to fit the message on screen
453 if !a:can_change_thread
456 call <SID>NM_kill_this_buffer()
459 call <SID>NM_search_show_thread(everything)
461 call <SID>NM_show_previous(0, a:find_matching)
463 echo 'No more messages.'
467 function! s:NM_show_next(can_change_thread, find_matching)
468 let info = b:nm_raw_info
470 for msg in info['msgs']
471 if a:find_matching && msg['match'] == '0'
474 if lnum >= msg['start']
478 exec printf('norm %dGzt', msg['start'])
479 " TODO: try to fit the message on screen
482 if a:can_change_thread
483 call <SID>NM_show_next_thread()
487 function! s:NM_show_next_thread()
488 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
489 call <SID>NM_kill_this_buffer()
490 if line('.') != line('$')
492 call <SID>NM_search_show_thread(everything)
494 echo 'No more messages.'
498 function! s:NM_show_archive_thread()
499 call <SID>NM_tag(b:nm_search_words, ['-inbox'])
500 call <SID>NM_show_next_thread()
503 function! s:NM_show_mark_read_then_archive_thread()
504 call <SID>NM_tag(b:nm_search_words, ['-unread', '-inbox'])
505 call <SID>NM_show_next_thread()
508 function! s:NM_show_mark_read_then_next_open_message()
509 echo 'not implemented'
512 function! s:NM_show_previous_message()
513 echo 'not implemented'
516 function! s:NM_show_reply()
518 call add(cmd, <SID>NM_show_message_id())
520 call extend(cmd, <SID>NM_get_search_words())
522 let data = <SID>NM_run(cmd)
523 let lines = split(data, "\n")
524 call <SID>NM_newComposeBuffer(lines, 0)
527 function! s:NM_show_view_all_mime_parts()
528 echo 'not implemented'
531 function! s:NM_show_view_raw_message()
532 echo 'not implemented'
535 function! s:NM_show_add_tag()
536 echo 'not implemented'
539 function! s:NM_show_remove_tag()
540 echo 'not implemented'
543 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
544 " otherwise go to next message
545 " any message that is viewed entirely has inbox and unread tags removed
546 function! s:NM_show_advance_marking_read_and_archiving()
547 let advance_tags = ['unread', 'inbox']
549 let vis_top = line('w0')
550 let vis_bot = line('w$')
552 let msg_top = <SID>NM_show_get_message_for_line(vis_top)
553 if !has_key(msg_top,'id')
554 throw "No top visible message."
557 " if the top message is the last message, just expunge the entire thread and move on
558 if msg_top['end'] == line('$')
560 for msg in b:nm_raw_info['msgs']
561 if has_key(msg,'match') && msg['match'] != '0'
562 call add(ids, msg['id'])
565 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
567 \ + <SID>NM_combine_tags('', ids, 'OR', '()')
568 call map(advance_tags, '"+" . v:val')
569 call <SID>NM_tag(filter, advance_tags)
570 call <SID>NM_show_next(1, 1)
574 let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
575 if !has_key(msg_bot,'id')
576 throw "No bottom visible message."
579 " if entire message fits on the screen, read/archive it, move to the next one
580 if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
581 exec printf('norm %dG', vis_top)
582 call <SID>NM_show_next(0, 1)
583 if has_key(msg_top,'match') && msg_top['match'] != '0'
585 " do this last to hide the latency
586 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
587 \ + ['AND', msg_top['id']]
588 call map(advance_tags, '"-" . v:val')
589 call <SID>NM_tag(filter, advance_tags)
594 " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
595 let jmp = winheight(winnr()) / 2
596 let max = msg_bot['end'] - vis_bot
600 exec printf('norm %dGzt', vis_top + jmp)
604 function! s:NM_show_pipe_message()
605 echo 'not implemented'
608 function! s:NM_show_previous_fold()
609 echo 'not implemented'
612 function! s:NM_show_next_fold()
613 echo 'not implemented'
616 function! s:NM_show_toggle_fold()
617 echo 'not implemented'
621 " --- --- show screen helper functions {{{2
623 function! s:NM_show_get_message_for_line(line)
624 for msg in b:nm_raw_info['msgs']
625 if a:line > msg['end']
633 function! s:NM_show_message_id()
634 if !exists('b:nm_raw_info')
635 throw 'Eeek! no b:nm_raw_info'
637 let msg = <SID>NM_show_get_message_for_line(line('.'))
644 function! s:NM_show_fold_toggle(key, type, fold)
645 let info = b:nm_raw_info
650 for fld in info['folds']
655 "let msg = info['msgs'][idx]
656 "if has_key(msg,'match') && msg['match'] == '0'
659 let cls = foldclosed(fld[1])
660 if cls != -1 && cls != fld[1]
663 exec printf('%dfold%s', fld[1], act)
665 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
669 " s:NM_cmd_show_parse returns the following dictionary:
670 " 'disp': lines to display
671 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
672 " 'folds': fold info arrays [ type, start, end ]
673 " 'foldtext': fold text indexed by start line
674 function! s:NM_cmd_show_parse(inlines)
675 let info = { 'disp': [],
694 for line in a:inlines
695 let inlnum = inlnum + 1
701 if match(line, g:notmuch_show_part_end_regexp) != -1
702 let part_end = len(info['disp'])
704 call add(info['disp'], line)
707 if in_part == 'text/plain'
708 if !part_end && mode_type == ''
709 if match(line, g:notmuch_show_signature_regexp) != -1
710 let mode_type = 'sig'
711 let mode_start = len(info['disp'])
712 elseif match(line, g:notmuch_show_citation_regexp) != -1
713 let mode_type = 'cit'
714 let mode_start = len(info['disp'])
716 elseif mode_type == 'cit'
717 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
718 let outlnum = len(info['disp'])
719 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
720 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
723 elseif mode_type == 'sig'
724 let outlnum = len(info['disp'])
725 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
728 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
729 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
736 " FIXME: this is a hack for handling two folds being added for one line
737 " we should handle addinga fold in a function
738 if len(foldinfo) && foldinfo[1] < foldinfo[2]
739 call add(info['folds'], foldinfo[0:3])
740 let info['foldtext'][foldinfo[1]] = foldinfo[4]
743 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
744 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
746 call add(info['disp'], '')
750 if !has_key(msg,'body_start')
751 let msg['body_start'] = len(info['disp']) + 1
753 if match(line, g:notmuch_show_body_end_regexp) != -1
754 let body_end = len(info['disp'])
755 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
756 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
760 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
761 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
762 let in_part = 'unknown'
766 call add(info['disp'],
767 \ printf('--- %s ---', in_part))
768 let part_start = len(info['disp']) + 1
773 let msg['descr'] = line
774 call add(info['disp'], line)
776 let msg['hdr_start'] = len(info['disp']) + 1
779 if match(line, g:notmuch_show_header_end_regexp) != -1
780 let hdr_start = msg['hdr_start']+1
781 let hdr_end = len(info['disp'])
782 let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
783 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
784 let msg['header'] = hdr
788 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
791 if match(g:notmuch_show_headers, m[1]) != -1
792 call add(info['disp'], line)
799 if match(line, g:notmuch_show_message_end_regexp) != -1
800 let msg['end'] = len(info['disp'])
801 call add(info['disp'], '')
803 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
804 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
806 call add(info['msgs'], msg)
813 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
817 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
818 let body_start = len(info['disp']) + 1
824 if match(line, g:notmuch_show_message_begin_regexp) != -1
825 let msg['start'] = len(info['disp']) + 1
827 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
830 let msg['depth'] = m[2]
831 let msg['match'] = m[3]
832 let msg['filename'] = m[4]
839 if len(foldinfo) && foldinfo[1] < foldinfo[2]
840 call add(info['folds'], foldinfo[0:3])
841 let info['foldtext'][foldinfo[1]] = foldinfo[4]
847 function! s:NM_cmd_show_mkfolds()
848 let info = b:nm_raw_info
850 for afold in info['folds']
851 exec printf('%d,%dfold', afold[1], afold[2])
853 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
854 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
855 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
856 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
858 elseif afold[0] == 'msg'
860 let msg = info['msgs'][idx]
861 if has_key(msg,'match') && msg['match'] == '0'
865 exec printf('%dfold%s', afold[1], state)
869 function! s:NM_cmd_show_mksyntax()
870 let info = b:nm_raw_info
872 for msg in info['msgs']
874 let start = msg['start']
875 let hdr_start = msg['hdr_start']
876 let body_start = msg['body_start']
878 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
879 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
880 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
884 function! NM_cmd_show_foldtext()
885 let foldtext = b:nm_raw_info['foldtext']
886 return foldtext[v:foldstart]
890 " --- implement compose screen {{{1
892 function! s:NM_cmd_compose(words, body_lines)
894 let start_on_line = 0
898 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
900 throw 'Eeek! bad parameter ''' . string(word) . ''''
902 let key = substitute(m[1], '\<\w', '\U&', 'g')
903 if !has_key(hdrs, key)
907 call add(hdrs[key], m[2])
911 if !has_key(hdrs, 'From') || !len(hdrs['From'])
912 let me = <SID>NM_compose_get_user_email()
913 let hdrs['From'] = [ me ]
916 for key in g:notmuch_compose_headers
917 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
918 call add(lines, key . ': ' . text)
919 if !start_on_line && !strlen(text)
920 let start_on_line = len(lines)
924 for [key,val] in items(hdrs)
925 if match(g:notmuch_compose_headers, key) == -1
926 let line = key . ': ' . join(val, ', ')
927 call add(lines, line)
933 let start_on_line = len(lines) + 1
937 call extend(lines, a:body_lines)
939 call extend(lines, [ '', '' ])
942 call <SID>NM_newComposeBuffer(lines, start_on_line)
945 function! s:NM_compose_send()
946 call <SID>NM_assert_buffer_type('compose')
947 let fname = expand('%')
949 let line = getline(lnum)
951 while match(line, '^$') == -1
952 if match(line, '^Notmuch-Help:') == -1
953 let hdr_starts = lnum - 1
957 let line = getline(lnum)
960 exec printf(':0,%dd', hdr_starts)
963 let cmdtxt = 'mailx -t < ' . fname
964 let out = system(cmdtxt)
965 let err = v:shell_error
969 call <SID>NM_newBuffer('new', 'error',
970 \ "While running...\n" .
971 \ ' ' . cmdtxt . "\n" .
973 \ "Failed with...\n" .
974 \ substitute(out, '^', ' ', 'g'))
976 echo 'Eeek! unable to send mail'
981 if !exists('b:nm_prev_bufnr')
984 let prev_bufnr = b:nm_prev_bufnr
986 if prev_bufnr == bufnr('%')
987 exec printf("buffer %d", prev_bufnr)
991 echo 'Mail sent successfully.'
994 function! s:NM_compose_attach()
995 echo 'not implemented'
998 function! s:NM_compose_next_entry_area()
1000 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1003 let line = getline(lnum)
1004 if match(line, '^\([^:]\+\):\s*$') == -1
1005 call cursor(lnum, strlen(line) + 1)
1008 while match(getline(lnum+1), '^\s') != -1
1011 call cursor(lnum, strlen(getline(lnum)) + 1)
1014 elseif lnum == hdr_end
1015 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1019 if !getbufvar(bufnr('.'), '&et')
1023 let shiftwidth = a:shiftwidth
1024 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1025 " we assume no one has shiftwidth set to more than 40 :)
1026 return ' '[0:shiftwidth]
1030 " --- --- compose screen helper functions {{{2
1032 function! s:NM_compose_get_user_email()
1033 " TODO: do this properly (still), i.e., allow for multiple email accounts
1034 let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1038 function! s:NM_compose_find_line_match(start, pattern, failure)
1040 let lend = line('$')
1042 if match(getline(lnum), a:pattern) != -1
1051 " --- notmuch helper functions {{{1
1053 function! s:NM_newBuffer(how, type, content)
1059 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1060 silent put=a:content
1062 setlocal nomodifiable
1063 execute printf('set filetype=notmuch-%s', a:type)
1064 execute printf('set syntax=notmuch-%s', a:type)
1065 let b:nm_type = a:type
1068 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1069 let fdir = expand(a:fdir)
1070 if !isdirectory(fdir)
1071 call mkdir(fdir, 'p')
1073 let file_name = <SID>NM_mktemp(fdir, a:fname)
1074 if writefile(a:lines, file_name)
1075 throw 'Eeek! couldn''t write to temporary file ' . file_name
1077 exec printf('edit %s', file_name)
1078 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1079 execute printf('set filetype=notmuch-%s', a:type)
1080 execute printf('set syntax=notmuch-%s', a:type)
1081 let b:nm_type = a:type
1084 function! s:NM_newComposeBuffer(lines, start_on_line)
1086 let start_on_line = a:start_on_line
1087 let real_hdr_start = 1
1088 if g:notmuch_compose_header_help
1090 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1091 \ 'Notmuch-Help: ,a - attach a file',
1092 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
1093 \ 'Notmuch-Help: ,q - abort the message',
1094 \ 'Notmuch-Help: <Tab> - skip through header lines',
1096 call extend(lines, help_lines, 0)
1097 let real_hdr_start = len(help_lines)
1098 if start_on_line > 0
1099 let start_on_line = start_on_line + len(help_lines)
1102 call extend(lines, g:notmuch_signature)
1105 let prev_bufnr = bufnr('%')
1106 setlocal bufhidden=hide
1107 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1109 setlocal bufhidden=hide
1110 let b:nm_prev_bufnr = prev_bufnr
1112 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1113 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1115 if start_on_line > 0 && start_on_line <= len(lines)
1116 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1118 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1119 call <SID>NM_compose_next_entry_area()
1122 if g:notmuch_compose_insert_mode_start
1125 echo 'Type your message, use <TAB> to jump to next header and then body.'
1128 function! s:NM_assert_buffer_type(type)
1129 if !exists('b:nm_type') || b:nm_type != a:type
1130 throw printf('Eeek! expected type %s, but got %s.', a:type,
1131 \ exists(b:nm_type) ? b:nm_type : 'something else')
1135 function! s:NM_mktemp(dir, name)
1136 let time_stamp = strftime('%Y%m%d-%H%M%S')
1137 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1138 " TODO: check if it exists, try again
1142 function! s:NM_shell_escape(word)
1143 " TODO: use shellescape()
1144 let word = substitute(a:word, '''', '\\''', 'g')
1145 return '''' . word . ''''
1148 " this function was taken from git.vim, then fixed up
1149 " http://github.com/motemen/git-vim
1150 function! s:NM_shell_split(cmd)
1151 let l:split_cmd = []
1155 let t = match(cmd, '\S', iStart)
1161 let iSpace = match(cmd, '\v(\s|$)', iStart)
1166 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1167 if iQuote1 > iSpace || iQuote1 < iStart
1168 let iEnd = iSpace - 1
1169 let l:split_cmd += [ cmd[iStart : iEnd] ]
1171 let q = cmd[iQuote1]
1172 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1173 if iQuote2 < iQuote1
1174 throw 'No matching ' . q . ' quote'
1177 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1181 let iStart = iEnd + 1
1188 function! s:NM_run(args)
1190 call map(words, 's:NM_shell_escape(v:val)')
1191 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1193 if exists('g:notmuch_debug') && g:notmuch_debug
1194 let start = reltime()
1195 let out = system(cmd)
1196 let err = v:shell_error
1197 let delta = reltime(start)
1199 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1201 let out = system(cmd)
1202 let err = v:shell_error
1207 echo substitute(out, '\n*$', '', '')
1215 " --- external mail handling helpers {{{1
1217 function! s:NM_new_mail()
1218 call <SID>NM_cmd_compose([], [])
1221 " --- tag manipulation helpers {{{1
1223 " used to combine an array of words with prefixes and separators
1225 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1226 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1227 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1230 if len(res) && strlen(a:separator)
1231 call add(res, a:separator)
1233 call add(res, a:word_prefix . word)
1235 if len(res) > 1 && strlen(a:brackets)
1236 if strlen(a:brackets) != 2
1237 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1239 call insert(res, a:brackets[0])
1240 call add(res, a:brackets[1])
1245 " --- other helpers {{{1
1247 function! s:NM_get_search_words()
1248 if !exists('b:nm_search_words')
1249 throw 'Eeek! no b:nm_search_words'
1251 return b:nm_search_words
1254 function! s:NM_kill_this_buffer()
1255 if exists('b:nm_prev_bufnr')
1256 let prev_bufnr = b:nm_prev_bufnr
1258 exec printf("buffer %d", prev_bufnr)
1260 echo "This is the last buffer; use :q<CR> to quit."
1264 function! s:NM_search_expand(arg)
1265 let word = expand(a:arg)
1266 let prev_bufnr = bufnr('%')
1267 setlocal bufhidden=hide
1268 call <SID>NM_cmd_search([word])
1269 setlocal bufhidden=delete
1270 let b:nm_prev_bufnr = prev_bufnr
1273 function! s:NM_tag(filter, tags)
1274 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1276 throw 'Eeek! I couldn''t find the thead id!'
1279 call extend(args, a:tags)
1280 call add(args, '--')
1281 call extend(args, filter)
1282 " TODO: handle errors
1283 call <SID>NM_run(args)
1286 " --- process and set the defaults {{{1
1288 function! NM_set_defaults(force)
1289 for [key, dflt] in items(s:notmuch_defaults)
1291 if !a:force && exists(key) && type(dflt) == type(eval(key))
1293 elseif type(dflt) == type(0)
1294 let cmd = printf('let %s = %d', key, dflt)
1295 elseif type(dflt) == type('')
1296 let cmd = printf('let %s = ''%s''', key, dflt)
1297 " FIXME: not sure why this didn't work when dflt is an array
1298 "elseif type(dflt) == type([])
1299 " let cmd = printf('let %s = %s', key, string(dflt))
1301 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1302 \ a:force, key, string(dflt))
1308 call NM_set_defaults(0)
1310 " for some reason NM_set_defaults() didn't work for arrays...
1311 if !exists('g:notmuch_show_headers')
1312 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1314 if !exists('g:notmuch_initial_search_words')
1315 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1317 if !exists('g:notmuch_folders')
1318 let g:notmuch_folders = s:notmuch_folders_defaults
1321 if !exists('g:notmuch_signature')
1322 let g:notmuch_signature = s:notmuch_signature_defaults
1324 if !exists('g:notmuch_compose_headers')
1325 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1328 " --- assign keymaps {{{1
1330 function! s:NM_set_map(type, maps)
1332 for [key, code] in items(a:maps)
1333 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1335 " --- this is a hack for development :)
1336 nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1339 " --- command handler {{{1
1341 function! NotMuch(args)
1344 let args = 'folders'
1347 let words = <SID>NM_shell_split(args)
1348 if words[0] == 'folders' || words[0] == 'f'
1349 let words = words[1:]
1350 call <SID>NM_cmd_folders(words)
1352 elseif words[0] == 'search' || words[0] == 's'
1354 let words = words[1:]
1355 elseif exists('b:nm_search_words')
1356 let words = b:nm_search_words
1358 let words = g:notmuch_initial_search_words
1360 call <SID>NM_cmd_search(words)
1362 elseif words[0] == 'show'
1363 echoe 'show is not yet implemented.'
1365 elseif words[0] == 'new' || words[0] == 'compose'
1366 let words = words[1:]
1367 call <SID>NM_cmd_compose(words, [])
1370 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1377 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1378 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1380 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :