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>
22 " --- configuration defaults {{{1
24 let s:notmuch_defaults = {
25 \ 'g:notmuch_cmd': 'notmuch' ,
26 \ 'g:notmuch_debug': 0 ,
28 \ 'g:notmuch_search_newest_first': 1 ,
29 \ 'g:notmuch_search_from_column_width': 20 ,
31 \ 'g:notmuch_show_fold_signatures': 1 ,
32 \ 'g:notmuch_show_fold_citations': 1 ,
33 \ 'g:notmuch_show_fold_bodies': 0 ,
34 \ 'g:notmuch_show_fold_headers': 1 ,
36 \ 'g:notmuch_show_message_begin_regexp': '
\fmessage{' ,
37 \ 'g:notmuch_show_message_end_regexp': '
\fmessage}' ,
38 \ 'g:notmuch_show_header_begin_regexp': '
\fheader{' ,
39 \ 'g:notmuch_show_header_end_regexp': '
\fheader}' ,
40 \ 'g:notmuch_show_body_begin_regexp': '
\fbody{' ,
41 \ 'g:notmuch_show_body_end_regexp': '
\fbody}' ,
42 \ 'g:notmuch_show_attachment_begin_regexp': '
\fattachment{' ,
43 \ 'g:notmuch_show_attachment_end_regexp': '
\fattachment}' ,
44 \ 'g:notmuch_show_part_begin_regexp': '
\fpart{' ,
45 \ 'g:notmuch_show_part_end_regexp': '
\fpart}' ,
46 \ 'g:notmuch_show_marker_regexp': '
\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
48 \ 'g:notmuch_show_message_parse_regexp': '\(id:[^ ]*\) depth:\([0-9]*\) match:\([0-9]*\) filename:\(.*\)$',
49 \ 'g:notmuch_show_tags_regexp': '(\([^)]*\))$' ,
51 \ 'g:notmuch_show_signature_regexp': '^\(-- \?\|_\+\)$' ,
52 \ 'g:notmuch_show_signature_lines_max': 12 ,
54 \ 'g:notmuch_show_citation_regexp': '^\s*>' ,
56 \ 'g:notmuch_compose_insert_mode_start': 1 ,
57 \ 'g:notmuch_compose_header_help': 1 ,
58 \ 'g:notmuch_compose_temp_file_dir': '~/.notmuch/compose/' ,
61 " defaults for g:notmuch_initial_search_words
62 " override with: let g:notmuch_initial_search_words = [ ... ]
63 let s:notmuch_initial_search_words_defaults = [
64 \ 'tag:inbox and tag:unread',
67 " defaults for g:notmuch_show_headers
68 " override with: let g:notmuch_show_headers = [ ... ]
69 let s:notmuch_show_headers_defaults = [
77 " defaults for g:notmuch_folders
78 " override with: let g:notmuch_folders = [ ... ]
79 let s:notmuch_folders_defaults = [
80 \ [ 'new', 'tag:inbox and tag:unread' ],
81 \ [ 'inbox', 'tag:inbox' ],
82 \ [ 'unread', 'tag:unread' ],
85 " defaults for g:notmuch_signature
86 " override with: let g:notmuch_signature = [ ... ]
87 let s:notmuch_signature_defaults = [
90 \ 'email sent from notmuch.vim plugin'
93 " defaults for g:notmuch_compose_headers
94 " override with: let g:notmuch_compose_headers = [ ... ]
95 let s:notmuch_compose_headers_defaults = [
103 " --- keyboard mapping definitions {{{1
105 " --- --- bindings for folders mode {{{2
107 let g:notmuch_folders_maps = {
108 \ 's': ':call <SID>NM_search_prompt()<CR>',
109 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
110 \ '=': ':call <SID>NM_folders_refresh_view()<CR>',
111 \ '<Enter>': ':call <SID>NM_folders_show_search()<CR>',
114 " --- --- bindings for search screen {{{2
115 let g:notmuch_search_maps = {
116 \ '<Enter>': ':call <SID>NM_search_show_thread()<CR>',
117 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
118 \ 'a': ':call <SID>NM_search_archive_thread()<CR>',
119 \ 'f': ':call <SID>NM_search_filter()<CR>',
120 \ 'm': ':call <SID>NM_new_mail()<CR>',
121 \ 'o': ':call <SID>NM_search_toggle_order()<CR>',
122 \ 'r': ':call <SID>NM_search_reply_to_thread()<CR>',
123 \ 's': ':call <SID>NM_search_prompt()<CR>',
124 \ ',s': ':call <SID>NM_search_edit()<CR>',
125 \ 't': ':call <SID>NM_search_filter_by_tag()<CR>',
126 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
127 \ '+': ':call <SID>NM_search_add_tags([])<CR>',
128 \ '-': ':call <SID>NM_search_remove_tags([])<CR>',
129 \ '=': ':call <SID>NM_search_refresh_view()<CR>',
130 \ '?': ':echo <SID>NM_search_thread_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
133 " --- --- bindings for show screen {{{2
134 let g:notmuch_show_maps = {
135 \ '<C-P>': ':call <SID>NM_show_previous(1, 0)<CR>',
136 \ '<C-N>': ':call <SID>NM_show_next(1, 0)<CR>',
137 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
138 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
140 \ 'b': ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
141 \ 'c': ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
142 \ 'h': ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
143 \ 's': ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
145 \ 'a': ':call <SID>NM_show_archive_thread()<CR>',
146 \ 'A': ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
147 \ 'N': ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
148 \ 'v': ':call <SID>NM_show_view_all_mime_parts()<CR>',
149 \ '+': ':call <SID>NM_show_add_tag()<CR>',
150 \ '-': ':call <SID>NM_show_remove_tag()<CR>',
151 \ '<Space>': ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
152 \ '\|': ':call <SID>NM_show_pipe_message()<CR>',
154 \ '<S-Tab>': ':call <SID>NM_show_previous_fold()<CR>',
155 \ '<Tab>': ':call <SID>NM_show_next_fold()<CR>',
156 \ '<Enter>': ':call <SID>NM_show_toggle_fold()<CR>',
158 \ 'r': ':call <SID>NM_show_reply()<CR>',
159 \ 'm': ':call <SID>NM_new_mail()<CR>',
160 \ '?': ':echo <SID>NM_show_message_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
163 " --- --- bindings for compose screen {{{2
164 let g:notmuch_compose_nmaps = {
165 \ ',s': ':call <SID>NM_compose_send()<CR>',
166 \ ',a': ':call <SID>NM_compose_attach()<CR>',
167 \ ',q': ':call <SID>NM_kill_this_buffer()<CR>',
168 \ '<Tab>': ':call <SID>NM_compose_next_entry_area()<CR>',
170 let g:notmuch_compose_imaps = {
171 \ '<Tab>': '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
174 " --- implement folders screen {{{1
176 function! s:NM_cmd_folders(words)
178 throw 'Not exapecting any arguments for folders command.'
183 for entry in g:notmuch_folders
184 let [ name, search ] = entry
185 let data = s:NM_run(cmd + [search])
186 let cnt = matchlist(data, '\(\d\+\)')[1]
187 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
188 call add(searches, search)
191 call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
192 let b:nm_searches = searches
193 let b:nm_timestamp = reltime()
195 call <SID>NM_cmd_folders_mksyntax()
196 call <SID>NM_set_map('n', g:notmuch_folders_maps)
201 function! s:NM_cmd_folders_mksyntax()
204 " --- --- folders screen action functions {{{2
206 function! s:NM_folders_refresh_view()
208 setlocal bufhidden=delete
209 call s:NM_cmd_folders([])
210 exec printf('norm %dG', lno)
213 function! s:NM_folders_show_search()
215 let search = b:nm_searches[line-1]
217 let prev_bufnr = bufnr('%')
218 setlocal bufhidden=hide
219 call <SID>NM_cmd_search([search])
220 setlocal bufhidden=delete
221 let b:nm_prev_bufnr = prev_bufnr
225 " --- implement search screen {{{1
227 function! s:NM_cmd_search(words)
229 if g:notmuch_search_newest_first
230 let cmd = cmd + ['--sort=newest-first']
232 let cmd = cmd + ['--sort=oldest-first']
234 let data = s:NM_run(cmd + a:words)
235 let lines = split(data, "\n")
236 let disp = copy(lines)
237 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
239 call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
240 let b:nm_raw_lines = lines
241 let b:nm_search_words = a:words
243 call <SID>NM_cmd_search_mksyntax()
244 call <SID>NM_set_map('n', g:notmuch_search_maps)
248 function! s:NM_cmd_search_fmtline(line)
249 let m = matchlist(a:line, '^\(thread:\S\+\)\s\([^]]\+\]\) \([^;]\+\); \(.*\) (\([^(]*\))$')
251 return 'ERROR PARSING: ' . a:line
253 let max = g:notmuch_search_from_column_width
255 if strlen(from) >= max
256 let from = substitute(m[3][0:max-4], '[^A-Za-z1-9_]*$', '', '') . '...'
258 return printf('%-20s %-20s | %s (%s)', m[2], from, m[4], m[5])
260 function! s:NM_cmd_search_mksyntax()
261 syntax clear nmSearchFrom
262 exec printf('syntax match nmSearchFrom /\(\] \)\@<=.\{%d\}/ oneline contained', g:notmuch_search_from_column_width)
265 " --- --- search screen action functions {{{2
267 function! s:NM_search_show_thread()
268 let id = <SID>NM_search_thread_id()
271 if exists('b:nm_search_words')
272 let words = ['('] + b:nm_search_words + [')', 'AND', id]
275 call <SID>NM_cmd_show(words)
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_on_screen('', '-', ['inbox'])
312 call <SID>NM_add_remove_tags([], '-', ['inbox'])
316 function! s:NM_search_filter()
317 call <SID>NM_search_filter_helper('Filter: ', '', '')
320 function! s:NM_search_filter_by_tag()
321 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
324 function! s:NM_search_filter_helper(prompt, prefix, joiner)
325 " TODO: input() can support completion
326 let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
331 let tags = b:nm_search_words + ['AND']
332 \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
334 let prev_bufnr = bufnr('%')
335 setlocal bufhidden=hide
336 call <SID>NM_cmd_search(tags)
337 setlocal bufhidden=delete
338 let b:nm_prev_bufnr = prev_bufnr
341 function! s:NM_search_toggle_order()
342 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
343 " FIXME: maybe this would be better done w/o reading re-reading the lines
344 " reversing the b:nm_raw_lines and the buffer lines would be better
345 call <SID>NM_search_refresh_view()
348 function! s:NM_search_reply_to_thread()
349 echo 'not implemented'
352 function! s:NM_search_add_tags(tags)
353 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
356 function! s:NM_search_remove_tags(tags)
357 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
360 function! s:NM_search_refresh_view()
362 let prev_bufnr = b:nm_prev_bufnr
363 setlocal bufhidden=delete
364 call <SID>NM_cmd_search(b:nm_search_words)
365 let b:nm_prev_bufnr = prev_bufnr
366 " FIXME: should find the line of the thread we were on if possible
367 exec printf('norm %dG', lno)
370 " --- --- search screen helper functions {{{2
372 function! s:NM_search_thread_id()
373 if !exists('b:nm_raw_lines')
374 throw 'Eeek! no b:nm_raw_lines'
376 let mnum = line('.') - 1
377 if len(b:nm_raw_lines) <= mnum
380 let info = b:nm_raw_lines[mnum]
381 let what = split(info, '\s\+')[0]
385 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
386 if type(a:intags) != type([]) || len(a:intags) == 0
387 " TODO: input() can support completion
388 let text = input(a:prompt)
392 let tags = split(text, ' ')
396 call <SID>NM_add_remove_tags([], a:prefix, tags)
397 call <SID>NM_add_remove_tags_on_screen('', a:prefix, tags)
400 " --- implement show screen {{{1
402 function! s:NM_cmd_show(words)
403 let prev_bufnr = bufnr('%')
404 let data = s:NM_run(['show'] + a:words)
405 let lines = split(data, "\n")
407 let info = s:NM_cmd_show_parse(lines)
409 setlocal bufhidden=hide
410 call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
411 setlocal bufhidden=delete
412 let b:nm_search_words = a:words
413 let b:nm_raw_info = info
414 let b:nm_prev_bufnr = prev_bufnr
416 call <SID>NM_cmd_show_mkfolds()
417 call <SID>NM_cmd_show_mksyntax()
418 call <SID>NM_set_map('n', g:notmuch_show_maps)
419 setlocal foldtext=NM_cmd_show_foldtext()
421 setlocal foldcolumn=6
425 function! s:NM_show_previous(can_change_thread, find_matching)
426 let info = b:nm_raw_info
428 for msg in reverse(copy(info['msgs']))
429 if a:find_matching && msg['match'] == '0'
432 if lnum <= msg['start']
436 exec printf('norm %dGzt', msg['start'])
437 " TODO: try to fit the message on screen
440 if !a:can_change_thread
443 call <SID>NM_kill_this_buffer()
446 call <SID>NM_search_show_thread()
448 call <SID>NM_show_previous(0, a:find_matching)
450 echo 'No more messages.'
454 function! s:NM_show_next(can_change_thread, find_matching)
455 let info = b:nm_raw_info
457 for msg in info['msgs']
458 if a:find_matching && msg['match'] == '0'
461 if lnum >= msg['start']
465 exec printf('norm %dGzt', msg['start'])
466 " TODO: try to fit the message on screen
469 if a:can_change_thread
470 call <SID>NM_show_next_thread()
474 function! s:NM_show_next_thread()
475 call <SID>NM_kill_this_buffer()
476 if line('.') != line('$')
478 call <SID>NM_search_show_thread()
480 echo 'No more messages.'
484 function! s:NM_show_archive_thread()
485 echo 'not implemented'
488 function! s:NM_show_mark_read_then_archive_thread()
489 echo 'not implemented'
492 function! s:NM_show_mark_read_then_next_open_message()
493 echo 'not implemented'
496 function! s:NM_show_previous_message()
497 echo 'not implemented'
500 function! s:NM_show_reply()
501 echo 'not implemented'
504 function! s:NM_show_view_all_mime_parts()
505 echo 'not implemented'
508 function! s:NM_show_view_raw_message()
509 echo 'not implemented'
512 function! s:NM_show_add_tag()
513 echo 'not implemented'
516 function! s:NM_show_remove_tag()
517 echo 'not implemented'
520 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
521 " otherwise go to next message
522 " any message that is viewed entirely has inbox and unread tags removed
523 function! s:NM_show_advance_marking_read_and_archiving()
524 let advance_tags = ['unread', 'inbox']
526 let vis_top = line('w0')
527 let vis_bot = line('w$')
529 let msg_top = <SID>NM_show_get_message_for_line(vis_top)
530 if !has_key(msg_top,'id')
531 throw "No top visible message."
534 " if the top message is the last message, just expunge the entire thread and move on
535 if msg_top['end'] == line('$')
537 for msg in b:nm_raw_info['msgs']
538 if has_key(msg,'match') && msg['match'] != '0'
539 call add(ids, msg['id'])
542 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
544 \ + <SID>NM_combine_tags('', ids, 'OR', '()')
545 call <SID>NM_add_remove_tags(filter, '-', advance_tags)
546 call <SID>NM_show_next(1, 1)
550 let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
551 if !has_key(msg_bot,'id')
552 throw "No bottom visible message."
555 " if entire message fits on the screen, read/archive it, move to the next one
556 if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
557 call <SID>NM_add_remove_tags_on_screen(msg_top['start'], '-', advance_tags)
558 exec printf('norm %dG', vis_top)
559 call <SID>NM_show_next(0, 1)
560 if has_key(msg_top,'match') && msg_top['match'] != '0'
562 " do this last to hide the latency
563 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
564 \ + ['AND', msg_top['id']]
565 call <SID>NM_add_remove_tags(filter, '-', advance_tags)
570 " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
571 let jmp = winheight(winnr()) / 2
572 let max = msg_bot['end'] - vis_bot
576 exec printf('norm %dGzt', vis_top + jmp)
580 function! s:NM_show_pipe_message()
581 echo 'not implemented'
584 function! s:NM_show_previous_fold()
585 echo 'not implemented'
588 function! s:NM_show_next_fold()
589 echo 'not implemented'
592 function! s:NM_show_toggle_fold()
593 echo 'not implemented'
597 " --- --- show screen helper functions {{{2
599 function! s:NM_show_get_message_for_line(line)
600 for msg in b:nm_raw_info['msgs']
601 if a:line > msg['end']
609 function! s:NM_show_message_id()
610 if !exists('b:nm_raw_info')
611 throw 'Eeek! no b:nm_raw_info'
613 let msg = <SID>NM_show_get_message_for_line(line('.'))
620 function! s:NM_show_fold_toggle(key, type, fold)
621 let info = b:nm_raw_info
626 for fld in info['folds']
628 exec printf('%dfold%s', fld[1], act)
631 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
635 " s:NM_cmd_show_parse returns the following dictionary:
636 " 'disp': lines to display
637 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
638 " 'folds': fold info arrays [ type, start, end ]
639 " 'foldtext': fold text indexed by start line
640 function! s:NM_cmd_show_parse(inlines)
641 let info = { 'disp': [],
660 for line in a:inlines
661 let inlnum = inlnum + 1
667 if match(line, g:notmuch_show_part_end_regexp) != -1
668 let part_end = len(info['disp'])
670 call add(info['disp'], line)
673 if in_part == 'text/plain'
674 if !part_end && mode_type == ''
675 if match(line, g:notmuch_show_signature_regexp) != -1
676 let mode_type = 'sig'
677 let mode_start = len(info['disp'])
678 elseif match(line, g:notmuch_show_citation_regexp) != -1
679 let mode_type = 'cit'
680 let mode_start = len(info['disp'])
682 elseif mode_type == 'cit'
683 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
684 let outlnum = len(info['disp'])
685 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
686 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
689 elseif mode_type == 'sig'
690 let outlnum = len(info['disp'])
691 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
694 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
695 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
702 " FIXME: this is a hack for handling two folds being added for one line
703 " we should handle addinga fold in a function
704 if len(foldinfo) && foldinfo[1] < foldinfo[2]
705 call add(info['folds'], foldinfo[0:3])
706 let info['foldtext'][foldinfo[1]] = foldinfo[4]
709 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
710 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
712 call add(info['disp'], '')
716 if !has_key(msg,'body_start')
717 let msg['body_start'] = len(info['disp']) + 1
719 if match(line, g:notmuch_show_body_end_regexp) != -1
720 let body_end = len(info['disp'])
721 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
722 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
726 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
727 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
728 let in_part = 'unknown'
732 call add(info['disp'],
733 \ printf('--- %s ---', in_part))
734 let part_start = len(info['disp']) + 1
739 let msg['descr'] = line
740 call add(info['disp'], line)
742 let msg['hdr_start'] = len(info['disp']) + 1
745 if match(line, g:notmuch_show_header_end_regexp) != -1
746 let hdr_start = msg['hdr_start']+1
747 let hdr_end = len(info['disp'])
748 let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
749 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
750 let msg['header'] = hdr
754 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
757 if match(g:notmuch_show_headers, m[1]) != -1
758 call add(info['disp'], line)
765 if match(line, g:notmuch_show_message_end_regexp) != -1
766 let msg['end'] = len(info['disp'])
767 call add(info['disp'], '')
769 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
770 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
772 call add(info['msgs'], msg)
779 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
783 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
784 let body_start = len(info['disp']) + 1
790 if match(line, g:notmuch_show_message_begin_regexp) != -1
791 let msg['start'] = len(info['disp']) + 1
793 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
796 let msg['depth'] = m[2]
797 let msg['match'] = m[3]
798 let msg['filename'] = m[4]
805 if len(foldinfo) && foldinfo[1] < foldinfo[2]
806 call add(info['folds'], foldinfo[0:3])
807 let info['foldtext'][foldinfo[1]] = foldinfo[4]
813 function! s:NM_cmd_show_mkfolds()
814 let info = b:nm_raw_info
816 for afold in info['folds']
817 exec printf('%d,%dfold', afold[1], afold[2])
819 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
820 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
821 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
822 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
824 elseif afold[0] == 'msg'
826 let msg = info['msgs'][idx]
827 if has_key(msg,'match') && msg['match'] == '0'
831 exec printf('%dfold%s', afold[1], state)
835 function! s:NM_cmd_show_mksyntax()
836 let info = b:nm_raw_info
838 for msg in info['msgs']
840 let start = msg['start']
841 let hdr_start = msg['hdr_start']
842 let body_start = msg['body_start']
844 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
845 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
846 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
850 function! NM_cmd_show_foldtext()
851 let foldtext = b:nm_raw_info['foldtext']
852 return foldtext[v:foldstart]
856 " --- implement compose screen {{{1
858 function! s:NM_cmd_compose(words, body_lines)
859 let lines = !g:notmuch_compose_header_help ? [] : [
860 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
861 \ 'Notmuch-Help: ,a - attach a file',
862 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
863 \ 'Notmuch-Help: ,q - abort the message',
864 \ 'Notmuch-Help: <Tab> - skip through header lines',
866 let start_on_line = 0
870 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
872 throw 'Eeek! bad parameter ''' . string(word) . ''''
874 let key = substitute(m[1], '\<\w', '\U&', 'g')
875 if !has_key(hdrs, key)
879 call add(hdrs[key], m[2])
883 if !has_key(hdrs, 'From') || !len(hdrs['From'])
884 let me = <SID>NM_compose_get_user_email()
885 let hdrs['From'] = [ me ]
888 for key in g:notmuch_compose_headers
889 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
890 call add(lines, key . ': ' . text)
891 if !start_on_line && !strlen(text)
892 let start_on_line = len(lines)
896 for [key,val] in items(hdrs)
897 if match(g:notmuch_compose_headers, key) == -1
898 let line = key . ': ' . join(val, ', ')
899 call add(lines, line)
903 call extend(lines, [ '', '' ])
905 let start_on_line = len(lines) + 1
909 call extend(lines, a:body_lines)
913 call extend(lines, g:notmuch_signature)
915 let prev_bufnr = bufnr('%')
916 setlocal bufhidden=hide
917 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
919 setlocal bufhidden=hide
920 let b:nm_prev_bufnr = prev_bufnr
922 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
923 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
925 call cursor(start_on_line, strlen(start_on_line) + 1)
926 if g:notmuch_compose_insert_mode_start
929 echo 'Type your message, use <TAB> to jump to next header and then body.'
932 function! s:NM_compose_send()
933 call <SID>NM_assert_buffer_type('compose')
934 let fname = expand('%')
936 let line = getline(lnum)
939 while match(line, '^$') == -1
940 if match(line, '^Notmuch-Help:') != -1
942 elseif strlen(lst_hdr) && match(line, '^\s') != -1
943 let hdrs[lst_hdr][-1] = hdrs[lst_hdr][-1] . substitute(line, '^\s*', ' ', '')
945 let m = matchlist(line, '^\(\w[^:]*\):\s*\(.*\)\s*$')
948 throw printf('Eeek! invalid header on line %d', lnum)
950 let key = substitute(m[1], '\<\w', '\U&', 'g')
952 if !has_key(hdrs, key)
955 call add(hdrs[key], m[2])
960 let line = getline(lnum)
962 let body_starts = lnum + 1
963 exec printf('0,%dd', body_starts)
966 "[-a header] [-b bcc-addr] [-c cc-addr] [-s subject] to-addr
969 for [key, vals] in items(hdrs)
971 call extend(tos, vals)
982 elseif key == 'Subject'
990 call add(cmd, key . ': ' . val)
994 call extend(cmd, tos)
996 call map(cmd, 's:NM_shell_escape(v:val)')
997 let cmdtxt = join(cmd) . '< ' . fname
998 let out = system(cmdtxt)
999 let err = v:shell_error
1003 call <SID>NM_newBuffer('new', 'error',
1004 \ "While running...\n" .
1005 \ ' ' . cmdtxt . "\n" .
1007 \ "Failed with...\n" .
1008 \ substitute(out, '^', ' ', 'g'))
1010 echo 'Eeek! unable to send mail'
1015 if !exists('b:nm_prev_bufnr')
1018 let prev_bufnr = b:nm_prev_bufnr
1020 if prev_bufnr == bufnr('%')
1021 exec printf("buffer %d", prev_bufnr)
1025 echo 'Mail sent successfully.'
1028 function! s:NM_compose_attach()
1029 echo 'not implemented'
1032 function! s:NM_compose_next_entry_area()
1033 let lnum = line('.')
1034 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1037 let line = getline(lnum)
1038 if match(line, '^\([^:]\+\):\s*$') == -1
1039 call cursor(lnum, strlen(line) + 1)
1042 while match(getline(lnum+1), '^\s') != -1
1045 call cursor(lnum, strlen(getline(lnum)) + 1)
1048 elseif lnum == hdr_end
1049 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1053 if !getbufvar(bufnr('.'), '&et')
1057 let shiftwidth = a:shiftwidth
1058 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1059 " we assume no one has shiftwidth set to more than 40 :)
1060 return ' '[0:shiftwidth]
1064 " --- --- compose screen helper functions {{{2
1066 function! s:NM_compose_get_user_email()
1067 let name = substitute(system('id -u -n'), '\v(^\s*|\s*$|\n)', '', 'g')
1068 let fqdn = substitute(system('hostname -f'), '\v(^\s*|\s*$|\n)', '', 'g')
1070 " TODO: do this properly
1071 return name . '@' . fqdn
1074 function! s:NM_compose_find_line_match(start, pattern, failure)
1076 let lend = line('$')
1078 if match(getline(lnum), a:pattern) != -1
1087 " --- notmuch helper functions {{{1
1089 function! s:NM_newBuffer(how, type, content)
1095 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1096 silent put=a:content
1098 setlocal nomodifiable
1099 execute printf('set filetype=notmuch-%s', a:type)
1100 execute printf('set syntax=notmuch-%s', a:type)
1101 let b:nm_type = a:type
1104 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1105 let fdir = expand(a:fdir)
1106 if !isdirectory(fdir)
1107 call mkdir(fdir, 'p')
1109 let file_name = <SID>NM_mktemp(fdir, a:fname)
1110 if writefile(a:lines, file_name)
1111 throw 'Eeek! couldn''t write to temporary file ' . file_name
1113 exec printf('edit %s', file_name)
1114 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1115 execute printf('set filetype=notmuch-%s', a:type)
1116 execute printf('set syntax=notmuch-%s', a:type)
1117 let b:nm_type = a:type
1120 function! s:NM_assert_buffer_type(type)
1121 if !exists('b:nm_type') || b:nm_type != a:type
1122 throw printf('Eeek! expected type %s, but got %s.', a:type,
1123 \ exists(b:nm_type) ? b:nm_type : 'something else')
1127 function! s:NM_mktemp(dir, name)
1128 let time_stamp = strftime('%Y%m%d-%H%M%S')
1129 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1130 " TODO: check if it exists, try again
1134 function! s:NM_shell_escape(word)
1135 " TODO: use shellescape()
1136 let word = substitute(a:word, '''', '\\''', 'g')
1137 return '''' . word . ''''
1140 " this function was taken from git.vim, then fixed up
1141 " http://github.com/motemen/git-vim
1142 function! s:NM_shell_split(cmd)
1143 let l:split_cmd = []
1147 let t = match(cmd, '\S', iStart)
1153 let iSpace = match(cmd, '\v(\s|$)', iStart)
1158 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1159 if iQuote1 > iSpace || iQuote1 < iStart
1160 let iEnd = iSpace - 1
1161 let l:split_cmd += [ cmd[iStart : iEnd] ]
1163 let q = cmd[iQuote1]
1164 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1165 if iQuote2 < iQuote1
1166 throw 'No matching ' . q . ' quote'
1169 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1173 let iStart = iEnd + 1
1180 function! s:NM_run(args)
1182 call map(words, 's:NM_shell_escape(v:val)')
1183 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1185 let start = reltime()
1186 let out = system(cmd)
1187 let err = v:shell_error
1188 let delta = reltime(start)
1190 if exists('g:notmuch_debug') && g:notmuch_debug
1191 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1196 echo substitute(out, '\n*$', '', '')
1204 " --- external mail handling helpers {{{1
1206 function! s:NM_new_mail()
1207 echo 'not implemented'
1210 " --- tag manipulation helpers {{{1
1212 " used to combine an array of words with prefixes and separators
1214 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1215 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1216 function s:NM_combine_tags(word_prefix, words, separator, brackets)
1219 if len(res) && strlen(a:separator)
1220 call add(res, a:separator)
1222 call add(res, a:word_prefix . word)
1224 if len(res) > 1 && strlen(a:brackets)
1225 if strlen(a:brackets) != 2
1226 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1228 call insert(res, a:brackets[0])
1229 call add(res, a:brackets[1])
1234 " --- other helpers {{{1
1236 function! s:NM_get_search_words()
1237 if !exists('b:nm_search_words')
1238 throw 'Eeek! no b:nm_search_words'
1240 return b:nm_search_words
1243 function! s:NM_kill_this_buffer()
1244 if exists('b:nm_prev_bufnr')
1245 let prev_bufnr = b:nm_prev_bufnr
1247 exec printf("buffer %d", prev_bufnr)
1249 echo "This is the last buffer; use :q<CR> to quit."
1253 function! s:NM_search_expand(arg)
1254 let word = expand(a:arg)
1255 let prev_bufnr = bufnr('%')
1256 setlocal bufhidden=hide
1257 call <SID>NM_cmd_search([word])
1258 setlocal bufhidden=delete
1259 let b:nm_prev_bufnr = prev_bufnr
1262 function! s:NM_add_remove_tags(filter, prefix, tags)
1263 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1265 throw 'Eeek! I couldn''t find the thead id!'
1267 call map(a:tags, 'a:prefix . v:val')
1269 call extend(args, a:tags)
1270 call add(args, '--')
1271 call extend(args, filter)
1272 " TODO: handle errors
1273 call <SID>NM_run(args)
1276 function! s:NM_add_remove_tags_on_screen(online, prefix, tags)
1279 for tagname in a:tags
1280 exec printf('silent! %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', string(a:online), tagname)
1283 for tagname in a:tags
1284 exec printf('silent! %ss/(\([^)]*\))$/(\1 %s)/', string(a:online), tagname)
1287 setlocal nomodifiable
1290 " --- process and set the defaults {{{1
1292 function! NM_set_defaults(force)
1293 for [key, dflt] in items(s:notmuch_defaults)
1295 if !a:force && exists(key) && type(dflt) == type(eval(key))
1297 elseif type(dflt) == type(0)
1298 let cmd = printf('let %s = %d', key, dflt)
1299 elseif type(dflt) == type('')
1300 let cmd = printf('let %s = ''%s''', key, dflt)
1301 " FIXME: not sure why this didn't work when dflt is an array
1302 "elseif type(dflt) == type([])
1303 " let cmd = printf('let %s = %s', key, string(dflt))
1305 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1306 \ a:force, key, string(dflt))
1312 call NM_set_defaults(0)
1314 " for some reason NM_set_defaults() didn't work for arrays...
1315 if !exists('g:notmuch_show_headers')
1316 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1318 if !exists('g:notmuch_initial_search_words')
1319 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1321 if !exists('g:notmuch_folders')
1322 let g:notmuch_folders = s:notmuch_folders_defaults
1325 if !exists('g:notmuch_signature')
1326 let g:notmuch_signature = s:notmuch_signature_defaults
1328 if !exists('g:notmuch_compose_headers')
1329 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1332 " --- assign keymaps {{{1
1334 function! s:NM_set_map(type, maps)
1336 for [key, code] in items(a:maps)
1337 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1339 " --- this is a hack for development :)
1340 nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
1343 " --- command handler {{{1
1345 function! NotMuch(args)
1348 let args = 'folders'
1351 let words = <SID>NM_shell_split(args)
1352 if words[0] == 'folders' || words[0] == 'f'
1353 let words = words[1:]
1354 call <SID>NM_cmd_folders(words)
1356 elseif words[0] == 'search' || words[0] == 's'
1358 let words = words[1:]
1359 elseif exists('b:nm_search_words')
1360 let words = b:nm_search_words
1362 let words = g:notmuch_initial_search_words
1364 call <SID>NM_cmd_search(words)
1366 elseif words[0] == 'show'
1367 echoe 'show is not yet implemented.'
1369 elseif words[0] == 'new' || words[0] == 'compose'
1370 let words = words[1:]
1371 call <SID>NM_cmd_compose(words, [])
1374 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1381 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1382 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1384 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :