1 " notmuch.vim plugin --- run notmuch within vim
3 " Copyright © Carl Worth
5 " This file is part of Notmuch.
7 " Notmuch is free software: you can redistribute it and/or modify it
8 " under the terms of the GNU General Public License as published by
9 " the Free Software Foundation, either version 3 of the License, or
10 " (at your option) any later version.
12 " Notmuch is distributed in the hope that it will be useful, but
13 " WITHOUT ANY WARRANTY; without even the implied warranty of
14 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 " General Public License for more details.
17 " You should have received a copy of the GNU General Public License
18 " along with Notmuch. If not, see <http://www.gnu.org/licenses/>.
20 " Authors: Bart Trojanowski <bart@jukie.net>
21 " Contributors: Peter Hartman <peterjohnhartman@gmail.com>
23 " --- configuration defaults {{{1
25 let s:notmuch_defaults = {
26 \ 'g:notmuch_cmd': 'notmuch' ,
27 \ 'g:notmuch_debug': 0 ,
29 \ 'g:notmuch_search_newest_first': 1 ,
30 \ 'g:notmuch_search_from_column_width': 20 ,
32 \ 'g:notmuch_show_fold_signatures': 1 ,
33 \ 'g:notmuch_show_fold_citations': 1 ,
34 \ 'g:notmuch_show_fold_bodies': 0 ,
35 \ 'g:notmuch_show_fold_headers': 1 ,
37 \ 'g:notmuch_show_message_begin_regexp': '
\fmessage{' ,
38 \ 'g:notmuch_show_message_end_regexp': '
\fmessage}' ,
39 \ 'g:notmuch_show_header_begin_regexp': '
\fheader{' ,
40 \ 'g:notmuch_show_header_end_regexp': '
\fheader}' ,
41 \ 'g:notmuch_show_body_begin_regexp': '
\fbody{' ,
42 \ 'g:notmuch_show_body_end_regexp': '
\fbody}' ,
43 \ 'g:notmuch_show_attachment_begin_regexp': '
\fattachment{' ,
44 \ 'g:notmuch_show_attachment_end_regexp': '
\fattachment}' ,
45 \ 'g:notmuch_show_part_begin_regexp': '
\fpart{' ,
46 \ 'g:notmuch_show_part_end_regexp': '
\fpart}' ,
47 \ 'g:notmuch_show_marker_regexp': '
\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
49 \ 'g:notmuch_show_message_parse_regexp': '\(id:[^ ]*\) depth:\([0-9]*\) match:\([0-9]*\) filename:\(.*\)$',
50 \ 'g:notmuch_show_tags_regexp': '(\([^)]*\))$' ,
52 \ 'g:notmuch_show_signature_regexp': '^\(-- \?\|_\+\)$' ,
53 \ 'g:notmuch_show_signature_lines_max': 12 ,
55 \ 'g:notmuch_show_citation_regexp': '^\s*>' ,
57 \ 'g:notmuch_compose_insert_mode_start': 1 ,
58 \ 'g:notmuch_compose_header_help': 1 ,
59 \ 'g:notmuch_compose_temp_file_dir': '~/.notmuch/compose/' ,
62 " defaults for g:notmuch_initial_search_words
63 " override with: let g:notmuch_initial_search_words = [ ... ]
64 let s:notmuch_initial_search_words_defaults = [
65 \ 'tag:inbox and tag:unread',
68 " defaults for g:notmuch_show_headers
69 " override with: let g:notmuch_show_headers = [ ... ]
70 let s:notmuch_show_headers_defaults = [
78 " defaults for g:notmuch_folders
79 " override with: let g:notmuch_folders = [ ... ]
80 let s:notmuch_folders_defaults = [
81 \ [ 'new', 'tag:inbox and tag:unread' ],
82 \ [ 'inbox', 'tag:inbox' ],
83 \ [ 'unread', 'tag:unread' ],
86 " defaults for g:notmuch_signature
87 " override with: let g:notmuch_signature = [ ... ]
88 let s:notmuch_signature_defaults = [
91 \ 'email sent from notmuch.vim plugin'
94 " defaults for g:notmuch_compose_headers
95 " override with: let g:notmuch_compose_headers = [ ... ]
96 let s:notmuch_compose_headers_defaults = [
104 " --- keyboard mapping definitions {{{1
106 " --- --- bindings for folders mode {{{2
108 let g:notmuch_folders_maps = {
109 \ 'm': ':call <SID>NM_new_mail()<CR>',
110 \ 's': ':call <SID>NM_search_prompt()<CR>',
111 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
112 \ '=': ':call <SID>NM_folders_refresh_view()<CR>',
113 \ '<Enter>': ':call <SID>NM_folders_show_search()<CR>',
116 " --- --- bindings for search screen {{{2
117 let g:notmuch_search_maps = {
118 \ '<Space>': ':call <SID>NM_search_show_thread(0)<CR>',
119 \ '<Enter>': ':call <SID>NM_search_show_thread(1)<CR>',
120 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
121 \ 'a': ':call <SID>NM_search_archive_thread()<CR>',
122 \ 'A': ':call <SID>NM_search_mark_read_then_archive_thread()<CR>',
123 \ 'f': ':call <SID>NM_search_filter()<CR>',
124 \ 'm': ':call <SID>NM_new_mail()<CR>',
125 \ 'o': ':call <SID>NM_search_toggle_order()<CR>',
126 \ 'r': ':call <SID>NM_search_reply_to_thread()<CR>',
127 \ 's': ':call <SID>NM_search_prompt()<CR>',
128 \ ',s': ':call <SID>NM_search_edit()<CR>',
129 \ 't': ':call <SID>NM_search_filter_by_tag()<CR>',
130 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
131 \ '+': ':call <SID>NM_search_add_tags([])<CR>',
132 \ '-': ':call <SID>NM_search_remove_tags([])<CR>',
133 \ '=': ':call <SID>NM_search_refresh_view()<CR>',
134 \ '?': ':echo <SID>NM_search_thread_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
137 " --- --- bindings for show screen {{{2
138 let g:notmuch_show_maps = {
139 \ '<C-P>': ':call <SID>NM_show_previous(1, 0)<CR>',
140 \ '<C-N>': ':call <SID>NM_show_next(1, 0)<CR>',
141 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
142 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
143 \ 's': ':call <SID>NM_search_prompt()<CR>',
145 \ 'b': ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
146 \ 'c': ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
147 \ 'h': ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
148 \ 'i': ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
150 \ 'a': ':call <SID>NM_show_archive_thread()<CR>',
151 \ 'A': ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
152 \ 'N': ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
153 \ 'v': ':call <SID>NM_show_view_all_mime_parts()<CR>',
154 \ '+': ':call <SID>NM_show_add_tag()<CR>',
155 \ '-': ':call <SID>NM_show_remove_tag()<CR>',
156 \ '<Space>': ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
157 \ '\|': ':call <SID>NM_show_pipe_message()<CR>',
159 \ '<S-Tab>': ':call <SID>NM_show_previous_fold()<CR>',
160 \ '<Tab>': ':call <SID>NM_show_next_fold()<CR>',
161 \ '<Enter>': ':call <SID>NM_show_toggle_fold()<CR>',
163 \ 'r': ':call <SID>NM_show_reply()<CR>',
164 \ 'm': ':call <SID>NM_new_mail()<CR>',
165 \ '?': ':echo <SID>NM_show_message_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
168 " --- --- bindings for compose screen {{{2
169 let g:notmuch_compose_nmaps = {
170 \ ',s': ':call <SID>NM_compose_send()<CR>',
171 \ ',a': ':call <SID>NM_compose_attach()<CR>',
172 \ ',q': ':call <SID>NM_kill_this_buffer()<CR>',
173 \ '<Tab>': ':call <SID>NM_compose_next_entry_area()<CR>',
175 let g:notmuch_compose_imaps = {
176 \ '<Tab>': '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
179 " --- implement folders screen {{{1
181 function! s:NM_cmd_folders(words)
183 throw 'Not expecting any arguments for folders command.'
188 for entry in g:notmuch_folders
189 let [ name, search ] = entry
190 let data = s:NM_run(cmd + [search])
191 let cnt = matchlist(data, '\(\d\+\)')[1]
192 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
193 call add(searches, search)
196 call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
197 let b:nm_searches = searches
198 let b:nm_timestamp = reltime()
200 call <SID>NM_cmd_folders_mksyntax()
201 call <SID>NM_set_map('n', g:notmuch_folders_maps)
206 function! s:NM_cmd_folders_mksyntax()
209 " --- --- folders screen action functions {{{2
211 function! s:NM_folders_refresh_view()
213 setlocal bufhidden=delete
214 call s:NM_cmd_folders([])
215 exec printf('norm %dG', lno)
218 function! s:NM_folders_show_search()
220 let search = b:nm_searches[line-1]
222 let prev_bufnr = bufnr('%')
223 setlocal bufhidden=hide
224 call <SID>NM_cmd_search([search])
225 setlocal bufhidden=delete
226 let b:nm_prev_bufnr = prev_bufnr
230 " --- implement search screen {{{1
232 function! s:NM_cmd_search(words)
234 if g:notmuch_search_newest_first
235 let cmd = cmd + ['--sort=newest-first']
237 let cmd = cmd + ['--sort=oldest-first']
239 let data = s:NM_run(cmd + a:words)
240 let lines = split(data, "\n")
241 let disp = copy(lines)
242 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
244 call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
245 let b:nm_raw_lines = lines
246 let b:nm_search_words = a:words
248 call <SID>NM_set_map('n', g:notmuch_search_maps)
252 function! s:NM_cmd_search_fmtline(line)
253 let m = matchlist(a:line, '^\(thread:\S\+\)\s\(.\{12\}\) \[\(\d\+\)/\d\+\] \([^;]\+\); \%(\[[^\[]\+\] \)*\(.*\) (\([^(]*\))$')
255 return 'ERROR PARSING: ' . a:line
257 let max = g:notmuch_search_from_column_width
259 for at in split(m[4], ", ")
260 let p = min([stridx(at, "."), stridx(at, "@")])
261 call insert(flist, tolower(at[0:p - 1]))
263 let from = join(flist, ", ")
264 return printf("%-12s %3s %-20.20s | %s (%s)", m[2], m[3], from, m[5], m[6])
267 " --- --- search screen action functions {{{2
269 function! s:NM_search_show_thread(everything)
270 let words = [ <SID>NM_search_thread_id() ]
271 if !a:everything && exists('b:nm_search_words')
272 call extend(words, ['AND', '('])
273 call extend(words, b:nm_search_words)
276 call <SID>NM_cmd_show(words)
277 let b:nm_show_everything = a:everything
280 function! s:NM_search_prompt()
281 " TODO: input() can support completion
282 let text = input('NotMuch Search: ')
284 let tags = split(text)
286 let tags = s:notmuch_initial_search_words_defaults
288 let prev_bufnr = bufnr('%')
289 if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
290 " TODO: we intend to replace the current buffer,
291 " ... maybe we could just clear it
292 let prev_bufnr = b:nm_prev_bufnr
293 setlocal bufhidden=delete
295 setlocal bufhidden=hide
297 call <SID>NM_cmd_search(tags)
298 setlocal bufhidden=delete
299 let b:nm_prev_bufnr = prev_bufnr
302 function! s:NM_search_edit()
303 " TODO: input() can support completion
304 let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
306 call <SID>NM_cmd_search(split(text))
310 function! s:NM_search_archive_thread()
311 call <SID>NM_tag([], ['-inbox'])
315 function! s:NM_search_mark_read_then_archive_thread()
316 call <SID>NM_tag([], ['-unread', '-inbox'])
320 function! s:NM_search_filter()
321 call <SID>NM_search_filter_helper('Filter: ', '', '')
324 function! s:NM_search_filter_by_tag()
325 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
328 function! s:NM_search_filter_helper(prompt, prefix, joiner)
329 " TODO: input() can support completion
330 let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
335 let tags = b:nm_search_words + ['AND']
336 \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
338 let prev_bufnr = bufnr('%')
339 setlocal bufhidden=hide
340 call <SID>NM_cmd_search(tags)
341 setlocal bufhidden=delete
342 let b:nm_prev_bufnr = prev_bufnr
345 function! s:NM_search_toggle_order()
346 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
347 " FIXME: maybe this would be better done w/o reading re-reading the lines
348 " reversing the b:nm_raw_lines and the buffer lines would be better
349 call <SID>NM_search_refresh_view()
352 function! s:NM_search_reply_to_thread()
354 call add(cmd, <SID>NM_search_thread_id())
356 call extend(cmd, <SID>NM_get_search_words())
358 let data = <SID>NM_run(cmd)
359 let lines = split(data, "\n")
360 call <SID>NM_newComposeBuffer(lines, 0)
363 function! s:NM_search_add_tags(tags)
364 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
367 function! s:NM_search_remove_tags(tags)
368 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
371 function! s:NM_search_refresh_view()
373 let prev_bufnr = b:nm_prev_bufnr
374 setlocal bufhidden=delete
375 call <SID>NM_cmd_search(b:nm_search_words)
376 let b:nm_prev_bufnr = prev_bufnr
377 " FIXME: should find the line of the thread we were on if possible
378 exec printf('norm %dG', lno)
381 " --- --- search screen helper functions {{{2
383 function! s:NM_search_thread_id()
384 if !exists('b:nm_raw_lines')
385 throw 'Eeek! no b:nm_raw_lines'
387 let mnum = line('.') - 1
388 if len(b:nm_raw_lines) <= mnum
391 let info = b:nm_raw_lines[mnum]
392 let what = split(info, '\s\+')[0]
396 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
397 if type(a:intags) != type([]) || len(a:intags) == 0
398 " TODO: input() can support completion
399 let text = input(a:prompt)
403 let tags = split(text, ' ')
407 call map(tags, 'a:prefix . v:val')
408 call <SID>NM_tag([], tags)
411 " --- implement show screen {{{1
413 function! s:NM_cmd_show(words)
414 let prev_bufnr = bufnr('%')
415 let data = s:NM_run(['show', '--entire-thread'] + a:words)
416 let lines = split(data, "\n")
418 let info = s:NM_cmd_show_parse(lines)
420 setlocal bufhidden=hide
421 call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
422 setlocal bufhidden=delete
423 let b:nm_search_words = a:words
424 let b:nm_raw_info = info
425 let b:nm_prev_bufnr = prev_bufnr
427 call <SID>NM_cmd_show_mkfolds()
428 call <SID>NM_cmd_show_mksyntax()
429 call <SID>NM_set_map('n', g:notmuch_show_maps)
430 setlocal foldtext=NM_cmd_show_foldtext()
432 setlocal foldcolumn=6
436 function! s:NM_show_previous(can_change_thread, find_matching)
437 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
438 let info = b:nm_raw_info
440 for msg in reverse(copy(info['msgs']))
441 if a:find_matching && msg['match'] == '0'
444 if lnum <= msg['start']
448 exec printf('norm %dGzt', msg['start'])
449 " TODO: try to fit the message on screen
452 if !a:can_change_thread
455 call <SID>NM_kill_this_buffer()
458 call <SID>NM_search_show_thread(everything)
460 call <SID>NM_show_previous(0, a:find_matching)
462 echo 'No more messages.'
466 function! s:NM_show_next(can_change_thread, find_matching)
467 let info = b:nm_raw_info
469 for msg in info['msgs']
470 if a:find_matching && msg['match'] == '0'
473 if lnum >= msg['start']
477 exec printf('norm %dGzt', msg['start'])
478 " TODO: try to fit the message on screen
481 if a:can_change_thread
482 call <SID>NM_show_next_thread()
486 function! s:NM_show_next_thread()
487 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
488 call <SID>NM_kill_this_buffer()
489 if line('.') != line('$')
491 call <SID>NM_search_show_thread(everything)
493 echo 'No more messages.'
497 function! s:NM_show_archive_thread()
498 echo 'not implemented'
501 function! s:NM_show_mark_read_then_archive_thread()
502 call <SID>NM_tag(b:nm_search_words, ['-unread', '-inbox'])
503 call <SID>NM_show_next_thread()
506 function! s:NM_show_mark_read_then_next_open_message()
507 echo 'not implemented'
510 function! s:NM_show_previous_message()
511 echo 'not implemented'
514 function! s:NM_show_reply()
516 call add(cmd, <SID>NM_show_message_id())
518 call extend(cmd, <SID>NM_get_search_words())
520 let data = <SID>NM_run(cmd)
521 let lines = split(data, "\n")
522 call <SID>NM_newComposeBuffer(lines, 0)
525 function! s:NM_show_view_all_mime_parts()
526 echo 'not implemented'
529 function! s:NM_show_view_raw_message()
530 echo 'not implemented'
533 function! s:NM_show_add_tag()
534 echo 'not implemented'
537 function! s:NM_show_remove_tag()
538 echo 'not implemented'
541 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
542 " otherwise go to next message
543 " any message that is viewed entirely has inbox and unread tags removed
544 function! s:NM_show_advance_marking_read_and_archiving()
545 let advance_tags = ['unread', 'inbox']
547 let vis_top = line('w0')
548 let vis_bot = line('w$')
550 let msg_top = <SID>NM_show_get_message_for_line(vis_top)
551 if !has_key(msg_top,'id')
552 throw "No top visible message."
555 " if the top message is the last message, just expunge the entire thread and move on
556 if msg_top['end'] == line('$')
558 for msg in b:nm_raw_info['msgs']
559 if has_key(msg,'match') && msg['match'] != '0'
560 call add(ids, msg['id'])
563 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
565 \ + <SID>NM_combine_tags('', ids, 'OR', '()')
566 call map(advance_tags, '"+" . v:val')
567 call <SID>NM_tag(filter, advance_tags)
568 call <SID>NM_show_next(1, 1)
572 let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
573 if !has_key(msg_bot,'id')
574 throw "No bottom visible message."
577 " if entire message fits on the screen, read/archive it, move to the next one
578 if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
579 exec printf('norm %dG', vis_top)
580 call <SID>NM_show_next(0, 1)
581 if has_key(msg_top,'match') && msg_top['match'] != '0'
583 " do this last to hide the latency
584 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
585 \ + ['AND', msg_top['id']]
586 call map(advance_tags, '"-" . v:val')
587 call <SID>NM_tag(filter, advance_tags)
592 " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
593 let jmp = winheight(winnr()) / 2
594 let max = msg_bot['end'] - vis_bot
598 exec printf('norm %dGzt', vis_top + jmp)
602 function! s:NM_show_pipe_message()
603 echo 'not implemented'
606 function! s:NM_show_previous_fold()
607 echo 'not implemented'
610 function! s:NM_show_next_fold()
611 echo 'not implemented'
614 function! s:NM_show_toggle_fold()
615 echo 'not implemented'
619 " --- --- show screen helper functions {{{2
621 function! s:NM_show_get_message_for_line(line)
622 for msg in b:nm_raw_info['msgs']
623 if a:line > msg['end']
631 function! s:NM_show_message_id()
632 if !exists('b:nm_raw_info')
633 throw 'Eeek! no b:nm_raw_info'
635 let msg = <SID>NM_show_get_message_for_line(line('.'))
642 function! s:NM_show_fold_toggle(key, type, fold)
643 let info = b:nm_raw_info
648 for fld in info['folds']
653 "let msg = info['msgs'][idx]
654 "if has_key(msg,'match') && msg['match'] == '0'
657 let cls = foldclosed(fld[1])
658 if cls != -1 && cls != fld[1]
661 exec printf('%dfold%s', fld[1], act)
663 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
667 " s:NM_cmd_show_parse returns the following dictionary:
668 " 'disp': lines to display
669 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
670 " 'folds': fold info arrays [ type, start, end ]
671 " 'foldtext': fold text indexed by start line
672 function! s:NM_cmd_show_parse(inlines)
673 let info = { 'disp': [],
692 for line in a:inlines
693 let inlnum = inlnum + 1
699 if match(line, g:notmuch_show_part_end_regexp) != -1
700 let part_end = len(info['disp'])
702 call add(info['disp'], line)
705 if in_part == 'text/plain'
706 if !part_end && mode_type == ''
707 if match(line, g:notmuch_show_signature_regexp) != -1
708 let mode_type = 'sig'
709 let mode_start = len(info['disp'])
710 elseif match(line, g:notmuch_show_citation_regexp) != -1
711 let mode_type = 'cit'
712 let mode_start = len(info['disp'])
714 elseif mode_type == 'cit'
715 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
716 let outlnum = len(info['disp'])
717 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
718 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
721 elseif mode_type == 'sig'
722 let outlnum = len(info['disp'])
723 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
726 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
727 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
734 " FIXME: this is a hack for handling two folds being added for one line
735 " we should handle addinga fold in a function
736 if len(foldinfo) && foldinfo[1] < foldinfo[2]
737 call add(info['folds'], foldinfo[0:3])
738 let info['foldtext'][foldinfo[1]] = foldinfo[4]
741 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
742 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
744 call add(info['disp'], '')
748 if !has_key(msg,'body_start')
749 let msg['body_start'] = len(info['disp']) + 1
751 if match(line, g:notmuch_show_body_end_regexp) != -1
752 let body_end = len(info['disp'])
753 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
754 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
758 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
759 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
760 let in_part = 'unknown'
764 call add(info['disp'],
765 \ printf('--- %s ---', in_part))
766 let part_start = len(info['disp']) + 1
771 let msg['descr'] = line
772 call add(info['disp'], line)
774 let msg['hdr_start'] = len(info['disp']) + 1
777 if match(line, g:notmuch_show_header_end_regexp) != -1
778 let hdr_start = msg['hdr_start']+1
779 let hdr_end = len(info['disp'])
780 let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
781 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
782 let msg['header'] = hdr
786 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
789 if match(g:notmuch_show_headers, m[1]) != -1
790 call add(info['disp'], line)
797 if match(line, g:notmuch_show_message_end_regexp) != -1
798 let msg['end'] = len(info['disp'])
799 call add(info['disp'], '')
801 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
802 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
804 call add(info['msgs'], msg)
811 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
815 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
816 let body_start = len(info['disp']) + 1
822 if match(line, g:notmuch_show_message_begin_regexp) != -1
823 let msg['start'] = len(info['disp']) + 1
825 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
828 let msg['depth'] = m[2]
829 let msg['match'] = m[3]
830 let msg['filename'] = m[4]
837 if len(foldinfo) && foldinfo[1] < foldinfo[2]
838 call add(info['folds'], foldinfo[0:3])
839 let info['foldtext'][foldinfo[1]] = foldinfo[4]
845 function! s:NM_cmd_show_mkfolds()
846 let info = b:nm_raw_info
848 for afold in info['folds']
849 exec printf('%d,%dfold', afold[1], afold[2])
851 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
852 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
853 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
854 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
856 elseif afold[0] == 'msg'
858 let msg = info['msgs'][idx]
859 if has_key(msg,'match') && msg['match'] == '0'
863 exec printf('%dfold%s', afold[1], state)
867 function! s:NM_cmd_show_mksyntax()
868 let info = b:nm_raw_info
870 for msg in info['msgs']
872 let start = msg['start']
873 let hdr_start = msg['hdr_start']
874 let body_start = msg['body_start']
876 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
877 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
878 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
882 function! NM_cmd_show_foldtext()
883 let foldtext = b:nm_raw_info['foldtext']
884 return foldtext[v:foldstart]
888 " --- implement compose screen {{{1
890 function! s:NM_cmd_compose(words, body_lines)
892 let start_on_line = 0
896 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
898 throw 'Eeek! bad parameter ''' . string(word) . ''''
900 let key = substitute(m[1], '\<\w', '\U&', 'g')
901 if !has_key(hdrs, key)
905 call add(hdrs[key], m[2])
909 if !has_key(hdrs, 'From') || !len(hdrs['From'])
910 let me = <SID>NM_compose_get_user_email()
911 let hdrs['From'] = [ me ]
914 for key in g:notmuch_compose_headers
915 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
916 call add(lines, key . ': ' . text)
917 if !start_on_line && !strlen(text)
918 let start_on_line = len(lines)
922 for [key,val] in items(hdrs)
923 if match(g:notmuch_compose_headers, key) == -1
924 let line = key . ': ' . join(val, ', ')
925 call add(lines, line)
931 let start_on_line = len(lines) + 1
935 call extend(lines, a:body_lines)
937 call extend(lines, [ '', '' ])
940 call <SID>NM_newComposeBuffer(lines, start_on_line)
943 function! s:NM_compose_send()
944 call <SID>NM_assert_buffer_type('compose')
945 let fname = expand('%')
947 let line = getline(lnum)
949 while match(line, '^$') == -1
950 if match(line, '^Notmuch-Help:') == -1
951 let hdr_starts = lnum - 1
955 let line = getline(lnum)
958 exec printf(':0,%dd', hdr_starts)
961 let cmdtxt = 'mailx -t < ' . fname
962 let out = system(cmdtxt)
963 let err = v:shell_error
967 call <SID>NM_newBuffer('new', 'error',
968 \ "While running...\n" .
969 \ ' ' . cmdtxt . "\n" .
971 \ "Failed with...\n" .
972 \ substitute(out, '^', ' ', 'g'))
974 echo 'Eeek! unable to send mail'
979 if !exists('b:nm_prev_bufnr')
982 let prev_bufnr = b:nm_prev_bufnr
984 if prev_bufnr == bufnr('%')
985 exec printf("buffer %d", prev_bufnr)
989 echo 'Mail sent successfully.'
992 function! s:NM_compose_attach()
993 echo 'not implemented'
996 function! s:NM_compose_next_entry_area()
998 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1001 let line = getline(lnum)
1002 if match(line, '^\([^:]\+\):\s*$') == -1
1003 call cursor(lnum, strlen(line) + 1)
1006 while match(getline(lnum+1), '^\s') != -1
1009 call cursor(lnum, strlen(getline(lnum)) + 1)
1012 elseif lnum == hdr_end
1013 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1017 if !getbufvar(bufnr('.'), '&et')
1021 let shiftwidth = a:shiftwidth
1022 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1023 " we assume no one has shiftwidth set to more than 40 :)
1024 return ' '[0:shiftwidth]
1028 " --- --- compose screen helper functions {{{2
1030 function! s:NM_compose_get_user_email()
1031 " TODO: do this properly (still), i.e., allow for multiple email accounts
1032 let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1036 function! s:NM_compose_find_line_match(start, pattern, failure)
1038 let lend = line('$')
1040 if match(getline(lnum), a:pattern) != -1
1049 " --- notmuch helper functions {{{1
1051 function! s:NM_newBuffer(how, type, content)
1057 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1058 silent put=a:content
1060 setlocal nomodifiable
1061 execute printf('set filetype=notmuch-%s', a:type)
1062 execute printf('set syntax=notmuch-%s', a:type)
1063 let b:nm_type = a:type
1066 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1067 let fdir = expand(a:fdir)
1068 if !isdirectory(fdir)
1069 call mkdir(fdir, 'p')
1071 let file_name = <SID>NM_mktemp(fdir, a:fname)
1072 if writefile(a:lines, file_name)
1073 throw 'Eeek! couldn''t write to temporary file ' . file_name
1075 exec printf('edit %s', file_name)
1076 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1077 execute printf('set filetype=notmuch-%s', a:type)
1078 execute printf('set syntax=notmuch-%s', a:type)
1079 let b:nm_type = a:type
1082 function! s:NM_newComposeBuffer(lines, start_on_line)
1084 let start_on_line = a:start_on_line
1085 let real_hdr_start = 1
1086 if g:notmuch_compose_header_help
1088 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1089 \ 'Notmuch-Help: ,a - attach a file',
1090 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
1091 \ 'Notmuch-Help: ,q - abort the message',
1092 \ 'Notmuch-Help: <Tab> - skip through header lines',
1094 call extend(lines, help_lines, 0)
1095 let real_hdr_start = len(help_lines)
1096 if start_on_line > 0
1097 let start_on_line = start_on_line + len(help_lines)
1100 call extend(lines, g:notmuch_signature)
1103 let prev_bufnr = bufnr('%')
1104 setlocal bufhidden=hide
1105 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1107 setlocal bufhidden=hide
1108 let b:nm_prev_bufnr = prev_bufnr
1110 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1111 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1113 if start_on_line > 0 && start_on_line <= len(lines)
1114 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1116 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1117 call <SID>NM_compose_next_entry_area()
1120 if g:notmuch_compose_insert_mode_start
1123 echo 'Type your message, use <TAB> to jump to next header and then body.'
1126 function! s:NM_assert_buffer_type(type)
1127 if !exists('b:nm_type') || b:nm_type != a:type
1128 throw printf('Eeek! expected type %s, but got %s.', a:type,
1129 \ exists(b:nm_type) ? b:nm_type : 'something else')
1133 function! s:NM_mktemp(dir, name)
1134 let time_stamp = strftime('%Y%m%d-%H%M%S')
1135 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1136 " TODO: check if it exists, try again
1140 function! s:NM_shell_escape(word)
1141 " TODO: use shellescape()
1142 let word = substitute(a:word, '''', '\\''', 'g')
1143 return '''' . word . ''''
1146 " this function was taken from git.vim, then fixed up
1147 " http://github.com/motemen/git-vim
1148 function! s:NM_shell_split(cmd)
1149 let l:split_cmd = []
1153 let t = match(cmd, '\S', iStart)
1159 let iSpace = match(cmd, '\v(\s|$)', iStart)
1164 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1165 if iQuote1 > iSpace || iQuote1 < iStart
1166 let iEnd = iSpace - 1
1167 let l:split_cmd += [ cmd[iStart : iEnd] ]
1169 let q = cmd[iQuote1]
1170 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1171 if iQuote2 < iQuote1
1172 throw 'No matching ' . q . ' quote'
1175 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1179 let iStart = iEnd + 1
1186 function! s:NM_run(args)
1188 call map(words, 's:NM_shell_escape(v:val)')
1189 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1191 if exists('g:notmuch_debug') && g:notmuch_debug
1192 let start = reltime()
1193 let out = system(cmd)
1194 let err = v:shell_error
1195 let delta = reltime(start)
1197 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1199 let out = system(cmd)
1200 let err = v:shell_error
1205 echo substitute(out, '\n*$', '', '')
1213 " --- external mail handling helpers {{{1
1215 function! s:NM_new_mail()
1216 call <SID>NM_cmd_compose([], [])
1219 " --- tag manipulation helpers {{{1
1221 " used to combine an array of words with prefixes and separators
1223 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1224 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1225 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1228 if len(res) && strlen(a:separator)
1229 call add(res, a:separator)
1231 call add(res, a:word_prefix . word)
1233 if len(res) > 1 && strlen(a:brackets)
1234 if strlen(a:brackets) != 2
1235 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1237 call insert(res, a:brackets[0])
1238 call add(res, a:brackets[1])
1243 " --- other helpers {{{1
1245 function! s:NM_get_search_words()
1246 if !exists('b:nm_search_words')
1247 throw 'Eeek! no b:nm_search_words'
1249 return b:nm_search_words
1252 function! s:NM_kill_this_buffer()
1253 if exists('b:nm_prev_bufnr')
1254 let prev_bufnr = b:nm_prev_bufnr
1256 exec printf("buffer %d", prev_bufnr)
1258 echo "This is the last buffer; use :q<CR> to quit."
1262 function! s:NM_search_expand(arg)
1263 let word = expand(a:arg)
1264 let prev_bufnr = bufnr('%')
1265 setlocal bufhidden=hide
1266 call <SID>NM_cmd_search([word])
1267 setlocal bufhidden=delete
1268 let b:nm_prev_bufnr = prev_bufnr
1271 function! s:NM_tag(filter, tags)
1272 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1274 throw 'Eeek! I couldn''t find the thead id!'
1277 call extend(args, a:tags)
1278 call add(args, '--')
1279 call extend(args, filter)
1280 " TODO: handle errors
1281 call <SID>NM_run(args)
1284 " --- process and set the defaults {{{1
1286 function! NM_set_defaults(force)
1287 for [key, dflt] in items(s:notmuch_defaults)
1289 if !a:force && exists(key) && type(dflt) == type(eval(key))
1291 elseif type(dflt) == type(0)
1292 let cmd = printf('let %s = %d', key, dflt)
1293 elseif type(dflt) == type('')
1294 let cmd = printf('let %s = ''%s''', key, dflt)
1295 " FIXME: not sure why this didn't work when dflt is an array
1296 "elseif type(dflt) == type([])
1297 " let cmd = printf('let %s = %s', key, string(dflt))
1299 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1300 \ a:force, key, string(dflt))
1306 call NM_set_defaults(0)
1308 " for some reason NM_set_defaults() didn't work for arrays...
1309 if !exists('g:notmuch_show_headers')
1310 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1312 if !exists('g:notmuch_initial_search_words')
1313 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1315 if !exists('g:notmuch_folders')
1316 let g:notmuch_folders = s:notmuch_folders_defaults
1319 if !exists('g:notmuch_signature')
1320 let g:notmuch_signature = s:notmuch_signature_defaults
1322 if !exists('g:notmuch_compose_headers')
1323 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1326 " --- assign keymaps {{{1
1328 function! s:NM_set_map(type, maps)
1330 for [key, code] in items(a:maps)
1331 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1333 " --- this is a hack for development :)
1334 nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1337 " --- command handler {{{1
1339 function! NotMuch(args)
1342 let args = 'folders'
1345 let words = <SID>NM_shell_split(args)
1346 if words[0] == 'folders' || words[0] == 'f'
1347 let words = words[1:]
1348 call <SID>NM_cmd_folders(words)
1350 elseif words[0] == 'search' || words[0] == 's'
1352 let words = words[1:]
1353 elseif exists('b:nm_search_words')
1354 let words = b:nm_search_words
1356 let words = g:notmuch_initial_search_words
1358 call <SID>NM_cmd_search(words)
1360 elseif words[0] == 'show'
1361 echoe 'show is not yet implemented.'
1363 elseif words[0] == 'new' || words[0] == 'compose'
1364 let words = words[1:]
1365 call <SID>NM_cmd_compose(words, [])
1368 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1375 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1376 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1378 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :