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_add_remove_tags([], '-', ['inbox'])
315 function! s:NM_search_mark_read_then_archive_thread()
316 call <SID>NM_add_remove_tags([], '-', ['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 <SID>NM_add_remove_tags([], a:prefix, tags)
410 " --- implement show screen {{{1
412 function! s:NM_cmd_show(words)
413 let prev_bufnr = bufnr('%')
414 let data = s:NM_run(['show', '--entire-thread'] + a:words)
415 let lines = split(data, "\n")
417 let info = s:NM_cmd_show_parse(lines)
419 setlocal bufhidden=hide
420 call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
421 setlocal bufhidden=delete
422 let b:nm_search_words = a:words
423 let b:nm_raw_info = info
424 let b:nm_prev_bufnr = prev_bufnr
426 call <SID>NM_cmd_show_mkfolds()
427 call <SID>NM_cmd_show_mksyntax()
428 call <SID>NM_set_map('n', g:notmuch_show_maps)
429 setlocal foldtext=NM_cmd_show_foldtext()
431 setlocal foldcolumn=6
435 function! s:NM_show_previous(can_change_thread, find_matching)
436 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
437 let info = b:nm_raw_info
439 for msg in reverse(copy(info['msgs']))
440 if a:find_matching && msg['match'] == '0'
443 if lnum <= msg['start']
447 exec printf('norm %dGzt', msg['start'])
448 " TODO: try to fit the message on screen
451 if !a:can_change_thread
454 call <SID>NM_kill_this_buffer()
457 call <SID>NM_search_show_thread(everything)
459 call <SID>NM_show_previous(0, a:find_matching)
461 echo 'No more messages.'
465 function! s:NM_show_next(can_change_thread, find_matching)
466 let info = b:nm_raw_info
468 for msg in info['msgs']
469 if a:find_matching && msg['match'] == '0'
472 if lnum >= msg['start']
476 exec printf('norm %dGzt', msg['start'])
477 " TODO: try to fit the message on screen
480 if a:can_change_thread
481 call <SID>NM_show_next_thread()
485 function! s:NM_show_next_thread()
486 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
487 call <SID>NM_kill_this_buffer()
488 if line('.') != line('$')
490 call <SID>NM_search_show_thread(everything)
492 echo 'No more messages.'
496 function! s:NM_show_archive_thread()
497 echo 'not implemented'
500 function! s:NM_show_mark_read_then_archive_thread()
501 call <SID>NM_add_remove_tags(b:nm_search_words, '-', ['unread', 'inbox'])
502 call <SID>NM_show_next_thread()
505 function! s:NM_show_mark_read_then_next_open_message()
506 echo 'not implemented'
509 function! s:NM_show_previous_message()
510 echo 'not implemented'
513 function! s:NM_show_reply()
515 call add(cmd, <SID>NM_show_message_id())
517 call extend(cmd, <SID>NM_get_search_words())
519 let data = <SID>NM_run(cmd)
520 let lines = split(data, "\n")
521 call <SID>NM_newComposeBuffer(lines, 0)
524 function! s:NM_show_view_all_mime_parts()
525 echo 'not implemented'
528 function! s:NM_show_view_raw_message()
529 echo 'not implemented'
532 function! s:NM_show_add_tag()
533 echo 'not implemented'
536 function! s:NM_show_remove_tag()
537 echo 'not implemented'
540 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
541 " otherwise go to next message
542 " any message that is viewed entirely has inbox and unread tags removed
543 function! s:NM_show_advance_marking_read_and_archiving()
544 let advance_tags = ['unread', 'inbox']
546 let vis_top = line('w0')
547 let vis_bot = line('w$')
549 let msg_top = <SID>NM_show_get_message_for_line(vis_top)
550 if !has_key(msg_top,'id')
551 throw "No top visible message."
554 " if the top message is the last message, just expunge the entire thread and move on
555 if msg_top['end'] == line('$')
557 for msg in b:nm_raw_info['msgs']
558 if has_key(msg,'match') && msg['match'] != '0'
559 call add(ids, msg['id'])
562 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
564 \ + <SID>NM_combine_tags('', ids, 'OR', '()')
565 call <SID>NM_add_remove_tags(filter, '-', advance_tags)
566 call <SID>NM_show_next(1, 1)
570 let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
571 if !has_key(msg_bot,'id')
572 throw "No bottom visible message."
575 " if entire message fits on the screen, read/archive it, move to the next one
576 if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
577 exec printf('norm %dG', vis_top)
578 call <SID>NM_show_next(0, 1)
579 if has_key(msg_top,'match') && msg_top['match'] != '0'
581 " do this last to hide the latency
582 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
583 \ + ['AND', msg_top['id']]
584 call <SID>NM_add_remove_tags(filter, '-', advance_tags)
589 " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
590 let jmp = winheight(winnr()) / 2
591 let max = msg_bot['end'] - vis_bot
595 exec printf('norm %dGzt', vis_top + jmp)
599 function! s:NM_show_pipe_message()
600 echo 'not implemented'
603 function! s:NM_show_previous_fold()
604 echo 'not implemented'
607 function! s:NM_show_next_fold()
608 echo 'not implemented'
611 function! s:NM_show_toggle_fold()
612 echo 'not implemented'
616 " --- --- show screen helper functions {{{2
618 function! s:NM_show_get_message_for_line(line)
619 for msg in b:nm_raw_info['msgs']
620 if a:line > msg['end']
628 function! s:NM_show_message_id()
629 if !exists('b:nm_raw_info')
630 throw 'Eeek! no b:nm_raw_info'
632 let msg = <SID>NM_show_get_message_for_line(line('.'))
639 function! s:NM_show_fold_toggle(key, type, fold)
640 let info = b:nm_raw_info
645 for fld in info['folds']
650 "let msg = info['msgs'][idx]
651 "if has_key(msg,'match') && msg['match'] == '0'
654 let cls = foldclosed(fld[1])
655 if cls != -1 && cls != fld[1]
658 exec printf('%dfold%s', fld[1], act)
660 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
664 " s:NM_cmd_show_parse returns the following dictionary:
665 " 'disp': lines to display
666 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
667 " 'folds': fold info arrays [ type, start, end ]
668 " 'foldtext': fold text indexed by start line
669 function! s:NM_cmd_show_parse(inlines)
670 let info = { 'disp': [],
689 for line in a:inlines
690 let inlnum = inlnum + 1
696 if match(line, g:notmuch_show_part_end_regexp) != -1
697 let part_end = len(info['disp'])
699 call add(info['disp'], line)
702 if in_part == 'text/plain'
703 if !part_end && mode_type == ''
704 if match(line, g:notmuch_show_signature_regexp) != -1
705 let mode_type = 'sig'
706 let mode_start = len(info['disp'])
707 elseif match(line, g:notmuch_show_citation_regexp) != -1
708 let mode_type = 'cit'
709 let mode_start = len(info['disp'])
711 elseif mode_type == 'cit'
712 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
713 let outlnum = len(info['disp'])
714 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
715 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
718 elseif mode_type == 'sig'
719 let outlnum = len(info['disp'])
720 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
723 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
724 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
731 " FIXME: this is a hack for handling two folds being added for one line
732 " we should handle addinga fold in a function
733 if len(foldinfo) && foldinfo[1] < foldinfo[2]
734 call add(info['folds'], foldinfo[0:3])
735 let info['foldtext'][foldinfo[1]] = foldinfo[4]
738 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
739 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
741 call add(info['disp'], '')
745 if !has_key(msg,'body_start')
746 let msg['body_start'] = len(info['disp']) + 1
748 if match(line, g:notmuch_show_body_end_regexp) != -1
749 let body_end = len(info['disp'])
750 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
751 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
755 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
756 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
757 let in_part = 'unknown'
761 call add(info['disp'],
762 \ printf('--- %s ---', in_part))
763 let part_start = len(info['disp']) + 1
768 let msg['descr'] = line
769 call add(info['disp'], line)
771 let msg['hdr_start'] = len(info['disp']) + 1
774 if match(line, g:notmuch_show_header_end_regexp) != -1
775 let hdr_start = msg['hdr_start']+1
776 let hdr_end = len(info['disp'])
777 let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
778 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
779 let msg['header'] = hdr
783 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
786 if match(g:notmuch_show_headers, m[1]) != -1
787 call add(info['disp'], line)
794 if match(line, g:notmuch_show_message_end_regexp) != -1
795 let msg['end'] = len(info['disp'])
796 call add(info['disp'], '')
798 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
799 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
801 call add(info['msgs'], msg)
808 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
812 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
813 let body_start = len(info['disp']) + 1
819 if match(line, g:notmuch_show_message_begin_regexp) != -1
820 let msg['start'] = len(info['disp']) + 1
822 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
825 let msg['depth'] = m[2]
826 let msg['match'] = m[3]
827 let msg['filename'] = m[4]
834 if len(foldinfo) && foldinfo[1] < foldinfo[2]
835 call add(info['folds'], foldinfo[0:3])
836 let info['foldtext'][foldinfo[1]] = foldinfo[4]
842 function! s:NM_cmd_show_mkfolds()
843 let info = b:nm_raw_info
845 for afold in info['folds']
846 exec printf('%d,%dfold', afold[1], afold[2])
848 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
849 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
850 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
851 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
853 elseif afold[0] == 'msg'
855 let msg = info['msgs'][idx]
856 if has_key(msg,'match') && msg['match'] == '0'
860 exec printf('%dfold%s', afold[1], state)
864 function! s:NM_cmd_show_mksyntax()
865 let info = b:nm_raw_info
867 for msg in info['msgs']
869 let start = msg['start']
870 let hdr_start = msg['hdr_start']
871 let body_start = msg['body_start']
873 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
874 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
875 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
879 function! NM_cmd_show_foldtext()
880 let foldtext = b:nm_raw_info['foldtext']
881 return foldtext[v:foldstart]
885 " --- implement compose screen {{{1
887 function! s:NM_cmd_compose(words, body_lines)
889 let start_on_line = 0
893 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
895 throw 'Eeek! bad parameter ''' . string(word) . ''''
897 let key = substitute(m[1], '\<\w', '\U&', 'g')
898 if !has_key(hdrs, key)
902 call add(hdrs[key], m[2])
906 if !has_key(hdrs, 'From') || !len(hdrs['From'])
907 let me = <SID>NM_compose_get_user_email()
908 let hdrs['From'] = [ me ]
911 for key in g:notmuch_compose_headers
912 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
913 call add(lines, key . ': ' . text)
914 if !start_on_line && !strlen(text)
915 let start_on_line = len(lines)
919 for [key,val] in items(hdrs)
920 if match(g:notmuch_compose_headers, key) == -1
921 let line = key . ': ' . join(val, ', ')
922 call add(lines, line)
928 let start_on_line = len(lines) + 1
932 call extend(lines, a:body_lines)
934 call extend(lines, [ '', '' ])
937 call <SID>NM_newComposeBuffer(lines, start_on_line)
940 function! s:NM_compose_send()
941 call <SID>NM_assert_buffer_type('compose')
942 let fname = expand('%')
944 let line = getline(lnum)
946 while match(line, '^$') == -1
947 if match(line, '^Notmuch-Help:') == -1
948 let hdr_starts = lnum - 1
952 let line = getline(lnum)
955 exec printf(':0,%dd', hdr_starts)
958 let cmdtxt = 'mailx -t < ' . fname
959 let out = system(cmdtxt)
960 let err = v:shell_error
964 call <SID>NM_newBuffer('new', 'error',
965 \ "While running...\n" .
966 \ ' ' . cmdtxt . "\n" .
968 \ "Failed with...\n" .
969 \ substitute(out, '^', ' ', 'g'))
971 echo 'Eeek! unable to send mail'
976 if !exists('b:nm_prev_bufnr')
979 let prev_bufnr = b:nm_prev_bufnr
981 if prev_bufnr == bufnr('%')
982 exec printf("buffer %d", prev_bufnr)
986 echo 'Mail sent successfully.'
989 function! s:NM_compose_attach()
990 echo 'not implemented'
993 function! s:NM_compose_next_entry_area()
995 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
998 let line = getline(lnum)
999 if match(line, '^\([^:]\+\):\s*$') == -1
1000 call cursor(lnum, strlen(line) + 1)
1003 while match(getline(lnum+1), '^\s') != -1
1006 call cursor(lnum, strlen(getline(lnum)) + 1)
1009 elseif lnum == hdr_end
1010 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1014 if !getbufvar(bufnr('.'), '&et')
1018 let shiftwidth = a:shiftwidth
1019 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1020 " we assume no one has shiftwidth set to more than 40 :)
1021 return ' '[0:shiftwidth]
1025 " --- --- compose screen helper functions {{{2
1027 function! s:NM_compose_get_user_email()
1028 " TODO: do this properly (still), i.e., allow for multiple email accounts
1029 let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1033 function! s:NM_compose_find_line_match(start, pattern, failure)
1035 let lend = line('$')
1037 if match(getline(lnum), a:pattern) != -1
1046 " --- notmuch helper functions {{{1
1048 function! s:NM_newBuffer(how, type, content)
1054 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1055 silent put=a:content
1057 setlocal nomodifiable
1058 execute printf('set filetype=notmuch-%s', a:type)
1059 execute printf('set syntax=notmuch-%s', a:type)
1060 let b:nm_type = a:type
1063 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1064 let fdir = expand(a:fdir)
1065 if !isdirectory(fdir)
1066 call mkdir(fdir, 'p')
1068 let file_name = <SID>NM_mktemp(fdir, a:fname)
1069 if writefile(a:lines, file_name)
1070 throw 'Eeek! couldn''t write to temporary file ' . file_name
1072 exec printf('edit %s', file_name)
1073 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1074 execute printf('set filetype=notmuch-%s', a:type)
1075 execute printf('set syntax=notmuch-%s', a:type)
1076 let b:nm_type = a:type
1079 function! s:NM_newComposeBuffer(lines, start_on_line)
1081 let start_on_line = a:start_on_line
1082 let real_hdr_start = 1
1083 if g:notmuch_compose_header_help
1085 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1086 \ 'Notmuch-Help: ,a - attach a file',
1087 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
1088 \ 'Notmuch-Help: ,q - abort the message',
1089 \ 'Notmuch-Help: <Tab> - skip through header lines',
1091 call extend(lines, help_lines, 0)
1092 let real_hdr_start = len(help_lines)
1093 if start_on_line > 0
1094 let start_on_line = start_on_line + len(help_lines)
1097 call extend(lines, g:notmuch_signature)
1100 let prev_bufnr = bufnr('%')
1101 setlocal bufhidden=hide
1102 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1104 setlocal bufhidden=hide
1105 let b:nm_prev_bufnr = prev_bufnr
1107 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1108 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1110 if start_on_line > 0 && start_on_line <= len(lines)
1111 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1113 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1114 call <SID>NM_compose_next_entry_area()
1117 if g:notmuch_compose_insert_mode_start
1120 echo 'Type your message, use <TAB> to jump to next header and then body.'
1123 function! s:NM_assert_buffer_type(type)
1124 if !exists('b:nm_type') || b:nm_type != a:type
1125 throw printf('Eeek! expected type %s, but got %s.', a:type,
1126 \ exists(b:nm_type) ? b:nm_type : 'something else')
1130 function! s:NM_mktemp(dir, name)
1131 let time_stamp = strftime('%Y%m%d-%H%M%S')
1132 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1133 " TODO: check if it exists, try again
1137 function! s:NM_shell_escape(word)
1138 " TODO: use shellescape()
1139 let word = substitute(a:word, '''', '\\''', 'g')
1140 return '''' . word . ''''
1143 " this function was taken from git.vim, then fixed up
1144 " http://github.com/motemen/git-vim
1145 function! s:NM_shell_split(cmd)
1146 let l:split_cmd = []
1150 let t = match(cmd, '\S', iStart)
1156 let iSpace = match(cmd, '\v(\s|$)', iStart)
1161 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1162 if iQuote1 > iSpace || iQuote1 < iStart
1163 let iEnd = iSpace - 1
1164 let l:split_cmd += [ cmd[iStart : iEnd] ]
1166 let q = cmd[iQuote1]
1167 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1168 if iQuote2 < iQuote1
1169 throw 'No matching ' . q . ' quote'
1172 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1176 let iStart = iEnd + 1
1183 function! s:NM_run(args)
1185 call map(words, 's:NM_shell_escape(v:val)')
1186 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1188 if exists('g:notmuch_debug') && g:notmuch_debug
1189 let start = reltime()
1190 let out = system(cmd)
1191 let err = v:shell_error
1192 let delta = reltime(start)
1194 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1196 let out = system(cmd)
1197 let err = v:shell_error
1202 echo substitute(out, '\n*$', '', '')
1210 " --- external mail handling helpers {{{1
1212 function! s:NM_new_mail()
1213 call <SID>NM_cmd_compose([], [])
1216 " --- tag manipulation helpers {{{1
1218 " used to combine an array of words with prefixes and separators
1220 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1221 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1222 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1225 if len(res) && strlen(a:separator)
1226 call add(res, a:separator)
1228 call add(res, a:word_prefix . word)
1230 if len(res) > 1 && strlen(a:brackets)
1231 if strlen(a:brackets) != 2
1232 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1234 call insert(res, a:brackets[0])
1235 call add(res, a:brackets[1])
1240 " --- other helpers {{{1
1242 function! s:NM_get_search_words()
1243 if !exists('b:nm_search_words')
1244 throw 'Eeek! no b:nm_search_words'
1246 return b:nm_search_words
1249 function! s:NM_kill_this_buffer()
1250 if exists('b:nm_prev_bufnr')
1251 let prev_bufnr = b:nm_prev_bufnr
1253 exec printf("buffer %d", prev_bufnr)
1255 echo "This is the last buffer; use :q<CR> to quit."
1259 function! s:NM_search_expand(arg)
1260 let word = expand(a:arg)
1261 let prev_bufnr = bufnr('%')
1262 setlocal bufhidden=hide
1263 call <SID>NM_cmd_search([word])
1264 setlocal bufhidden=delete
1265 let b:nm_prev_bufnr = prev_bufnr
1268 function! s:NM_add_remove_tags(filter, prefix, tags)
1269 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1271 throw 'Eeek! I couldn''t find the thead id!'
1273 call map(a:tags, 'a:prefix . v:val')
1275 call extend(args, a:tags)
1276 call add(args, '--')
1277 call extend(args, filter)
1278 " TODO: handle errors
1279 call <SID>NM_run(args)
1282 " --- process and set the defaults {{{1
1284 function! NM_set_defaults(force)
1285 for [key, dflt] in items(s:notmuch_defaults)
1287 if !a:force && exists(key) && type(dflt) == type(eval(key))
1289 elseif type(dflt) == type(0)
1290 let cmd = printf('let %s = %d', key, dflt)
1291 elseif type(dflt) == type('')
1292 let cmd = printf('let %s = ''%s''', key, dflt)
1293 " FIXME: not sure why this didn't work when dflt is an array
1294 "elseif type(dflt) == type([])
1295 " let cmd = printf('let %s = %s', key, string(dflt))
1297 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1298 \ a:force, key, string(dflt))
1304 call NM_set_defaults(0)
1306 " for some reason NM_set_defaults() didn't work for arrays...
1307 if !exists('g:notmuch_show_headers')
1308 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1310 if !exists('g:notmuch_initial_search_words')
1311 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1313 if !exists('g:notmuch_folders')
1314 let g:notmuch_folders = s:notmuch_folders_defaults
1317 if !exists('g:notmuch_signature')
1318 let g:notmuch_signature = s:notmuch_signature_defaults
1320 if !exists('g:notmuch_compose_headers')
1321 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1324 " --- assign keymaps {{{1
1326 function! s:NM_set_map(type, maps)
1328 for [key, code] in items(a:maps)
1329 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1331 " --- this is a hack for development :)
1332 nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1335 " --- command handler {{{1
1337 function! NotMuch(args)
1340 let args = 'folders'
1343 let words = <SID>NM_shell_split(args)
1344 if words[0] == 'folders' || words[0] == 'f'
1345 let words = words[1:]
1346 call <SID>NM_cmd_folders(words)
1348 elseif words[0] == 'search' || words[0] == 's'
1350 let words = words[1:]
1351 elseif exists('b:nm_search_words')
1352 let words = b:nm_search_words
1354 let words = g:notmuch_initial_search_words
1356 call <SID>NM_cmd_search(words)
1358 elseif words[0] == 'show'
1359 echoe 'show is not yet implemented.'
1361 elseif words[0] == 'new' || words[0] == 'compose'
1362 let words = words[1:]
1363 call <SID>NM_cmd_compose(words, [])
1366 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1373 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1374 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1376 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :