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 \ 'm': ':call <SID>NM_new_mail()<CR>',
109 \ 's': ':call <SID>NM_search_prompt()<CR>',
110 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
111 \ '=': ':call <SID>NM_folders_refresh_view()<CR>',
112 \ '<Enter>': ':call <SID>NM_folders_show_search()<CR>',
115 " --- --- bindings for search screen {{{2
116 let g:notmuch_search_maps = {
117 \ '<Enter>': ':call <SID>NM_search_show_thread()<CR>',
118 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
119 \ 'a': ':call <SID>NM_search_archive_thread()<CR>',
120 \ 'f': ':call <SID>NM_search_filter()<CR>',
121 \ 'm': ':call <SID>NM_new_mail()<CR>',
122 \ 'o': ':call <SID>NM_search_toggle_order()<CR>',
123 \ 'r': ':call <SID>NM_search_reply_to_thread()<CR>',
124 \ 's': ':call <SID>NM_search_prompt()<CR>',
125 \ ',s': ':call <SID>NM_search_edit()<CR>',
126 \ 't': ':call <SID>NM_search_filter_by_tag()<CR>',
127 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
128 \ '+': ':call <SID>NM_search_add_tags([])<CR>',
129 \ '-': ':call <SID>NM_search_remove_tags([])<CR>',
130 \ '=': ':call <SID>NM_search_refresh_view()<CR>',
131 \ '?': ':echo <SID>NM_search_thread_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
134 " --- --- bindings for show screen {{{2
135 let g:notmuch_show_maps = {
136 \ '<C-P>': ':call <SID>NM_show_previous(1, 0)<CR>',
137 \ '<C-N>': ':call <SID>NM_show_next(1, 0)<CR>',
138 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
139 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
141 \ 'b': ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
142 \ 'c': ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
143 \ 'h': ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
144 \ 's': ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
146 \ 'a': ':call <SID>NM_show_archive_thread()<CR>',
147 \ 'A': ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
148 \ 'N': ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
149 \ 'v': ':call <SID>NM_show_view_all_mime_parts()<CR>',
150 \ '+': ':call <SID>NM_show_add_tag()<CR>',
151 \ '-': ':call <SID>NM_show_remove_tag()<CR>',
152 \ '<Space>': ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
153 \ '\|': ':call <SID>NM_show_pipe_message()<CR>',
155 \ '<S-Tab>': ':call <SID>NM_show_previous_fold()<CR>',
156 \ '<Tab>': ':call <SID>NM_show_next_fold()<CR>',
157 \ '<Enter>': ':call <SID>NM_show_toggle_fold()<CR>',
159 \ 'r': ':call <SID>NM_show_reply()<CR>',
160 \ 'm': ':call <SID>NM_new_mail()<CR>',
161 \ '?': ':echo <SID>NM_show_message_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
164 " --- --- bindings for compose screen {{{2
165 let g:notmuch_compose_nmaps = {
166 \ ',s': ':call <SID>NM_compose_send()<CR>',
167 \ ',a': ':call <SID>NM_compose_attach()<CR>',
168 \ ',q': ':call <SID>NM_kill_this_buffer()<CR>',
169 \ '<Tab>': ':call <SID>NM_compose_next_entry_area()<CR>',
171 let g:notmuch_compose_imaps = {
172 \ '<Tab>': '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
175 " --- implement folders screen {{{1
177 function! s:NM_cmd_folders(words)
179 throw 'Not exapecting any arguments for folders command.'
184 for entry in g:notmuch_folders
185 let [ name, search ] = entry
186 let data = s:NM_run(cmd + [search])
187 let cnt = matchlist(data, '\(\d\+\)')[1]
188 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
189 call add(searches, search)
192 call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
193 let b:nm_searches = searches
194 let b:nm_timestamp = reltime()
196 call <SID>NM_cmd_folders_mksyntax()
197 call <SID>NM_set_map('n', g:notmuch_folders_maps)
202 function! s:NM_cmd_folders_mksyntax()
205 " --- --- folders screen action functions {{{2
207 function! s:NM_folders_refresh_view()
209 setlocal bufhidden=delete
210 call s:NM_cmd_folders([])
211 exec printf('norm %dG', lno)
214 function! s:NM_folders_show_search()
216 let search = b:nm_searches[line-1]
218 let prev_bufnr = bufnr('%')
219 setlocal bufhidden=hide
220 call <SID>NM_cmd_search([search])
221 setlocal bufhidden=delete
222 let b:nm_prev_bufnr = prev_bufnr
226 " --- implement search screen {{{1
228 function! s:NM_cmd_search(words)
230 if g:notmuch_search_newest_first
231 let cmd = cmd + ['--sort=newest-first']
233 let cmd = cmd + ['--sort=oldest-first']
235 let data = s:NM_run(cmd + a:words)
236 let lines = split(data, "\n")
237 let disp = copy(lines)
238 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
240 call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
241 let b:nm_raw_lines = lines
242 let b:nm_search_words = a:words
244 call <SID>NM_cmd_search_mksyntax()
245 call <SID>NM_set_map('n', g:notmuch_search_maps)
249 function! s:NM_cmd_search_fmtline(line)
250 let m = matchlist(a:line, '^\(thread:\S\+\)\s\([^]]\+\]\) \([^;]\+\); \(.*\) (\([^(]*\))$')
252 return 'ERROR PARSING: ' . a:line
254 let max = g:notmuch_search_from_column_width
256 if strlen(from) >= max
257 let from = substitute(m[3][0:max-4], '[^A-Za-z1-9_]*$', '', '') . '...'
259 return printf('%-20s %-20s | %s (%s)', m[2], from, m[4], m[5])
261 function! s:NM_cmd_search_mksyntax()
262 syntax clear nmSearchFrom
263 exec printf('syntax match nmSearchFrom /\(\] \)\@<=.\{%d\}/ oneline contained', g:notmuch_search_from_column_width)
266 " --- --- search screen action functions {{{2
268 function! s:NM_search_show_thread()
269 let id = <SID>NM_search_thread_id()
272 if exists('b:nm_search_words')
273 let words = ['('] + b:nm_search_words + [')', 'AND', id]
276 call <SID>NM_cmd_show(words)
281 function! s:NM_search_prompt()
282 " TODO: input() can support completion
283 let text = input('NotMuch Search: ')
285 let tags = split(text)
287 let tags = s:notmuch_initial_search_words_defaults
289 let prev_bufnr = bufnr('%')
290 if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
291 " TODO: we intend to replace the current buffer,
292 " ... maybe we could just clear it
293 let prev_bufnr = b:nm_prev_bufnr
294 setlocal bufhidden=delete
296 setlocal bufhidden=hide
298 call <SID>NM_cmd_search(tags)
299 setlocal bufhidden=delete
300 let b:nm_prev_bufnr = prev_bufnr
303 function! s:NM_search_edit()
304 " TODO: input() can support completion
305 let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
307 call <SID>NM_cmd_search(split(text))
311 function! s:NM_search_archive_thread()
312 call <SID>NM_add_remove_tags_on_screen('', '-', ['inbox'])
313 call <SID>NM_add_remove_tags([], '-', ['inbox'])
317 function! s:NM_search_filter()
318 call <SID>NM_search_filter_helper('Filter: ', '', '')
321 function! s:NM_search_filter_by_tag()
322 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
325 function! s:NM_search_filter_helper(prompt, prefix, joiner)
326 " TODO: input() can support completion
327 let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
332 let tags = b:nm_search_words + ['AND']
333 \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
335 let prev_bufnr = bufnr('%')
336 setlocal bufhidden=hide
337 call <SID>NM_cmd_search(tags)
338 setlocal bufhidden=delete
339 let b:nm_prev_bufnr = prev_bufnr
342 function! s:NM_search_toggle_order()
343 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
344 " FIXME: maybe this would be better done w/o reading re-reading the lines
345 " reversing the b:nm_raw_lines and the buffer lines would be better
346 call <SID>NM_search_refresh_view()
349 function! s:NM_search_reply_to_thread()
350 echo 'not implemented'
353 function! s:NM_search_add_tags(tags)
354 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
357 function! s:NM_search_remove_tags(tags)
358 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
361 function! s:NM_search_refresh_view()
363 let prev_bufnr = b:nm_prev_bufnr
364 setlocal bufhidden=delete
365 call <SID>NM_cmd_search(b:nm_search_words)
366 let b:nm_prev_bufnr = prev_bufnr
367 " FIXME: should find the line of the thread we were on if possible
368 exec printf('norm %dG', lno)
371 " --- --- search screen helper functions {{{2
373 function! s:NM_search_thread_id()
374 if !exists('b:nm_raw_lines')
375 throw 'Eeek! no b:nm_raw_lines'
377 let mnum = line('.') - 1
378 if len(b:nm_raw_lines) <= mnum
381 let info = b:nm_raw_lines[mnum]
382 let what = split(info, '\s\+')[0]
386 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
387 if type(a:intags) != type([]) || len(a:intags) == 0
388 " TODO: input() can support completion
389 let text = input(a:prompt)
393 let tags = split(text, ' ')
397 call <SID>NM_add_remove_tags([], a:prefix, tags)
398 call <SID>NM_add_remove_tags_on_screen('', a:prefix, tags)
401 " --- implement show screen {{{1
403 function! s:NM_cmd_show(words)
404 let prev_bufnr = bufnr('%')
405 let data = s:NM_run(['show'] + a:words)
406 let lines = split(data, "\n")
408 let info = s:NM_cmd_show_parse(lines)
410 setlocal bufhidden=hide
411 call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
412 setlocal bufhidden=delete
413 let b:nm_search_words = a:words
414 let b:nm_raw_info = info
415 let b:nm_prev_bufnr = prev_bufnr
417 call <SID>NM_cmd_show_mkfolds()
418 call <SID>NM_cmd_show_mksyntax()
419 call <SID>NM_set_map('n', g:notmuch_show_maps)
420 setlocal foldtext=NM_cmd_show_foldtext()
422 setlocal foldcolumn=6
426 function! s:NM_show_previous(can_change_thread, find_matching)
427 let info = b:nm_raw_info
429 for msg in reverse(copy(info['msgs']))
430 if a:find_matching && msg['match'] == '0'
433 if lnum <= msg['start']
437 exec printf('norm %dGzt', msg['start'])
438 " TODO: try to fit the message on screen
441 if !a:can_change_thread
444 call <SID>NM_kill_this_buffer()
447 call <SID>NM_search_show_thread()
449 call <SID>NM_show_previous(0, a:find_matching)
451 echo 'No more messages.'
455 function! s:NM_show_next(can_change_thread, find_matching)
456 let info = b:nm_raw_info
458 for msg in info['msgs']
459 if a:find_matching && msg['match'] == '0'
462 if lnum >= msg['start']
466 exec printf('norm %dGzt', msg['start'])
467 " TODO: try to fit the message on screen
470 if a:can_change_thread
471 call <SID>NM_show_next_thread()
475 function! s:NM_show_next_thread()
476 call <SID>NM_kill_this_buffer()
477 if line('.') != line('$')
479 call <SID>NM_search_show_thread()
481 echo 'No more messages.'
485 function! s:NM_show_archive_thread()
486 echo 'not implemented'
489 function! s:NM_show_mark_read_then_archive_thread()
490 echo 'not implemented'
493 function! s:NM_show_mark_read_then_next_open_message()
494 echo 'not implemented'
497 function! s:NM_show_previous_message()
498 echo 'not implemented'
501 function! s:NM_show_reply()
502 echo 'not implemented'
505 function! s:NM_show_view_all_mime_parts()
506 echo 'not implemented'
509 function! s:NM_show_view_raw_message()
510 echo 'not implemented'
513 function! s:NM_show_add_tag()
514 echo 'not implemented'
517 function! s:NM_show_remove_tag()
518 echo 'not implemented'
521 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
522 " otherwise go to next message
523 " any message that is viewed entirely has inbox and unread tags removed
524 function! s:NM_show_advance_marking_read_and_archiving()
525 let advance_tags = ['unread', 'inbox']
527 let vis_top = line('w0')
528 let vis_bot = line('w$')
530 let msg_top = <SID>NM_show_get_message_for_line(vis_top)
531 if !has_key(msg_top,'id')
532 throw "No top visible message."
535 " if the top message is the last message, just expunge the entire thread and move on
536 if msg_top['end'] == line('$')
538 for msg in b:nm_raw_info['msgs']
539 if has_key(msg,'match') && msg['match'] != '0'
540 call add(ids, msg['id'])
543 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
545 \ + <SID>NM_combine_tags('', ids, 'OR', '()')
546 call <SID>NM_add_remove_tags(filter, '-', advance_tags)
547 call <SID>NM_show_next(1, 1)
551 let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
552 if !has_key(msg_bot,'id')
553 throw "No bottom visible message."
556 " if entire message fits on the screen, read/archive it, move to the next one
557 if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
558 call <SID>NM_add_remove_tags_on_screen(msg_top['start'], '-', advance_tags)
559 exec printf('norm %dG', vis_top)
560 call <SID>NM_show_next(0, 1)
561 if has_key(msg_top,'match') && msg_top['match'] != '0'
563 " do this last to hide the latency
564 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
565 \ + ['AND', msg_top['id']]
566 call <SID>NM_add_remove_tags(filter, '-', advance_tags)
571 " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
572 let jmp = winheight(winnr()) / 2
573 let max = msg_bot['end'] - vis_bot
577 exec printf('norm %dGzt', vis_top + jmp)
581 function! s:NM_show_pipe_message()
582 echo 'not implemented'
585 function! s:NM_show_previous_fold()
586 echo 'not implemented'
589 function! s:NM_show_next_fold()
590 echo 'not implemented'
593 function! s:NM_show_toggle_fold()
594 echo 'not implemented'
598 " --- --- show screen helper functions {{{2
600 function! s:NM_show_get_message_for_line(line)
601 for msg in b:nm_raw_info['msgs']
602 if a:line > msg['end']
610 function! s:NM_show_message_id()
611 if !exists('b:nm_raw_info')
612 throw 'Eeek! no b:nm_raw_info'
614 let msg = <SID>NM_show_get_message_for_line(line('.'))
621 function! s:NM_show_fold_toggle(key, type, fold)
622 let info = b:nm_raw_info
627 for fld in info['folds']
629 exec printf('%dfold%s', fld[1], act)
632 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
636 " s:NM_cmd_show_parse returns the following dictionary:
637 " 'disp': lines to display
638 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
639 " 'folds': fold info arrays [ type, start, end ]
640 " 'foldtext': fold text indexed by start line
641 function! s:NM_cmd_show_parse(inlines)
642 let info = { 'disp': [],
661 for line in a:inlines
662 let inlnum = inlnum + 1
668 if match(line, g:notmuch_show_part_end_regexp) != -1
669 let part_end = len(info['disp'])
671 call add(info['disp'], line)
674 if in_part == 'text/plain'
675 if !part_end && mode_type == ''
676 if match(line, g:notmuch_show_signature_regexp) != -1
677 let mode_type = 'sig'
678 let mode_start = len(info['disp'])
679 elseif match(line, g:notmuch_show_citation_regexp) != -1
680 let mode_type = 'cit'
681 let mode_start = len(info['disp'])
683 elseif mode_type == 'cit'
684 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
685 let outlnum = len(info['disp'])
686 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
687 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
690 elseif mode_type == 'sig'
691 let outlnum = len(info['disp'])
692 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
695 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
696 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
703 " FIXME: this is a hack for handling two folds being added for one line
704 " we should handle addinga fold in a function
705 if len(foldinfo) && foldinfo[1] < foldinfo[2]
706 call add(info['folds'], foldinfo[0:3])
707 let info['foldtext'][foldinfo[1]] = foldinfo[4]
710 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
711 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
713 call add(info['disp'], '')
717 if !has_key(msg,'body_start')
718 let msg['body_start'] = len(info['disp']) + 1
720 if match(line, g:notmuch_show_body_end_regexp) != -1
721 let body_end = len(info['disp'])
722 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
723 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
727 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
728 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
729 let in_part = 'unknown'
733 call add(info['disp'],
734 \ printf('--- %s ---', in_part))
735 let part_start = len(info['disp']) + 1
740 let msg['descr'] = line
741 call add(info['disp'], line)
743 let msg['hdr_start'] = len(info['disp']) + 1
746 if match(line, g:notmuch_show_header_end_regexp) != -1
747 let hdr_start = msg['hdr_start']+1
748 let hdr_end = len(info['disp'])
749 let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
750 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
751 let msg['header'] = hdr
755 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
758 if match(g:notmuch_show_headers, m[1]) != -1
759 call add(info['disp'], line)
766 if match(line, g:notmuch_show_message_end_regexp) != -1
767 let msg['end'] = len(info['disp'])
768 call add(info['disp'], '')
770 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
771 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
773 call add(info['msgs'], msg)
780 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
784 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
785 let body_start = len(info['disp']) + 1
791 if match(line, g:notmuch_show_message_begin_regexp) != -1
792 let msg['start'] = len(info['disp']) + 1
794 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
797 let msg['depth'] = m[2]
798 let msg['match'] = m[3]
799 let msg['filename'] = m[4]
806 if len(foldinfo) && foldinfo[1] < foldinfo[2]
807 call add(info['folds'], foldinfo[0:3])
808 let info['foldtext'][foldinfo[1]] = foldinfo[4]
814 function! s:NM_cmd_show_mkfolds()
815 let info = b:nm_raw_info
817 for afold in info['folds']
818 exec printf('%d,%dfold', afold[1], afold[2])
820 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
821 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
822 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
823 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
825 elseif afold[0] == 'msg'
827 let msg = info['msgs'][idx]
828 if has_key(msg,'match') && msg['match'] == '0'
832 exec printf('%dfold%s', afold[1], state)
836 function! s:NM_cmd_show_mksyntax()
837 let info = b:nm_raw_info
839 for msg in info['msgs']
841 let start = msg['start']
842 let hdr_start = msg['hdr_start']
843 let body_start = msg['body_start']
845 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
846 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
847 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
851 function! NM_cmd_show_foldtext()
852 let foldtext = b:nm_raw_info['foldtext']
853 return foldtext[v:foldstart]
857 " --- implement compose screen {{{1
859 function! s:NM_cmd_compose(words, body_lines)
861 let start_on_line = 0
865 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
867 throw 'Eeek! bad parameter ''' . string(word) . ''''
869 let key = substitute(m[1], '\<\w', '\U&', 'g')
870 if !has_key(hdrs, key)
874 call add(hdrs[key], m[2])
878 if !has_key(hdrs, 'From') || !len(hdrs['From'])
879 let me = <SID>NM_compose_get_user_email()
880 let hdrs['From'] = [ me ]
883 for key in g:notmuch_compose_headers
884 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
885 call add(lines, key . ': ' . text)
886 if !start_on_line && !strlen(text)
887 let start_on_line = len(lines)
891 for [key,val] in items(hdrs)
892 if match(g:notmuch_compose_headers, key) == -1
893 let line = key . ': ' . join(val, ', ')
894 call add(lines, line)
900 let start_on_line = len(lines) + 1
904 call extend(lines, a:body_lines)
906 call extend(lines, [ '', '' ])
909 call <SID>NM_newComposeBuffer(lines, start_on_line)
912 function! s:NM_compose_send()
913 call <SID>NM_assert_buffer_type('compose')
914 let fname = expand('%')
916 let line = getline(lnum)
919 while match(line, '^$') == -1
920 if match(line, '^Notmuch-Help:') != -1
922 elseif strlen(lst_hdr) && match(line, '^\s') != -1
923 let hdrs[lst_hdr][-1] = hdrs[lst_hdr][-1] . substitute(line, '^\s*', ' ', '')
925 let m = matchlist(line, '^\(\w[^:]*\):\s*\(.*\)\s*$')
928 throw printf('Eeek! invalid header on line %d', lnum)
930 let key = substitute(m[1], '\<\w', '\U&', 'g')
932 if !has_key(hdrs, key)
935 call add(hdrs[key], m[2])
940 let line = getline(lnum)
942 let body_starts = lnum
944 "[-a header] [-b bcc-addr] [-c cc-addr] [-s subject] to-addr
947 for [key, vals] in items(hdrs)
949 call extend(tos, vals)
960 elseif key == 'Subject'
968 call add(cmd, key . ': ' . val)
972 call extend(cmd, tos)
974 " TODO: make sure we have at least one target
975 " TODO: ask about empty jubject, etc
977 exec printf('0,%dd', body_starts)
980 call map(cmd, 's:NM_shell_escape(v:val)')
981 let cmdtxt = join(cmd) . '< ' . fname
982 let out = system(cmdtxt)
983 let err = v:shell_error
987 call <SID>NM_newBuffer('new', 'error',
988 \ "While running...\n" .
989 \ ' ' . cmdtxt . "\n" .
991 \ "Failed with...\n" .
992 \ substitute(out, '^', ' ', 'g'))
994 echo 'Eeek! unable to send mail'
999 if !exists('b:nm_prev_bufnr')
1002 let prev_bufnr = b:nm_prev_bufnr
1004 if prev_bufnr == bufnr('%')
1005 exec printf("buffer %d", prev_bufnr)
1009 echo 'Mail sent successfully.'
1012 function! s:NM_compose_attach()
1013 echo 'not implemented'
1016 function! s:NM_compose_next_entry_area()
1017 let lnum = line('.')
1018 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1021 let line = getline(lnum)
1022 if match(line, '^\([^:]\+\):\s*$') == -1
1023 call cursor(lnum, strlen(line) + 1)
1026 while match(getline(lnum+1), '^\s') != -1
1029 call cursor(lnum, strlen(getline(lnum)) + 1)
1032 elseif lnum == hdr_end
1033 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1037 if !getbufvar(bufnr('.'), '&et')
1041 let shiftwidth = a:shiftwidth
1042 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1043 " we assume no one has shiftwidth set to more than 40 :)
1044 return ' '[0:shiftwidth]
1048 " --- --- compose screen helper functions {{{2
1050 function! s:NM_compose_get_user_email()
1051 let name = substitute(system('id -u -n'), '\v(^\s*|\s*$|\n)', '', 'g')
1052 let fqdn = substitute(system('hostname -f'), '\v(^\s*|\s*$|\n)', '', 'g')
1054 " TODO: do this properly
1055 return name . '@' . fqdn
1058 function! s:NM_compose_find_line_match(start, pattern, failure)
1060 let lend = line('$')
1062 if match(getline(lnum), a:pattern) != -1
1071 " --- notmuch helper functions {{{1
1073 function! s:NM_newBuffer(how, type, content)
1079 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1080 silent put=a:content
1082 setlocal nomodifiable
1083 execute printf('set filetype=notmuch-%s', a:type)
1084 execute printf('set syntax=notmuch-%s', a:type)
1085 let b:nm_type = a:type
1088 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1089 let fdir = expand(a:fdir)
1090 if !isdirectory(fdir)
1091 call mkdir(fdir, 'p')
1093 let file_name = <SID>NM_mktemp(fdir, a:fname)
1094 if writefile(a:lines, file_name)
1095 throw 'Eeek! couldn''t write to temporary file ' . file_name
1097 exec printf('edit %s', file_name)
1098 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
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_newComposeBuffer(lines, start_on_line)
1106 let start_on_line = a:start_on_line
1107 let real_hdr_start = 1
1108 if g:notmuch_compose_header_help
1110 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1111 \ 'Notmuch-Help: ,a - attach a file',
1112 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
1113 \ 'Notmuch-Help: ,q - abort the message',
1114 \ 'Notmuch-Help: <Tab> - skip through header lines',
1116 call extend(lines, help_lines, 0)
1117 let real_hdr_start = len(help_lines)
1118 if start_on_line > 0
1119 let start_on_line = start_on_line + len(help_lines)
1122 call extend(lines, g:notmuch_signature)
1125 let prev_bufnr = bufnr('%')
1126 setlocal bufhidden=hide
1127 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1129 setlocal bufhidden=hide
1130 let b:nm_prev_bufnr = prev_bufnr
1132 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1133 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1135 if start_on_line > 0 && start_on_line <= len(lines)
1136 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1138 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1139 call <SID>NM_compose_next_entry_area()
1142 if g:notmuch_compose_insert_mode_start
1145 echo 'Type your message, use <TAB> to jump to next header and then body.'
1148 function! s:NM_assert_buffer_type(type)
1149 if !exists('b:nm_type') || b:nm_type != a:type
1150 throw printf('Eeek! expected type %s, but got %s.', a:type,
1151 \ exists(b:nm_type) ? b:nm_type : 'something else')
1155 function! s:NM_mktemp(dir, name)
1156 let time_stamp = strftime('%Y%m%d-%H%M%S')
1157 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1158 " TODO: check if it exists, try again
1162 function! s:NM_shell_escape(word)
1163 " TODO: use shellescape()
1164 let word = substitute(a:word, '''', '\\''', 'g')
1165 return '''' . word . ''''
1168 " this function was taken from git.vim, then fixed up
1169 " http://github.com/motemen/git-vim
1170 function! s:NM_shell_split(cmd)
1171 let l:split_cmd = []
1175 let t = match(cmd, '\S', iStart)
1181 let iSpace = match(cmd, '\v(\s|$)', iStart)
1186 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1187 if iQuote1 > iSpace || iQuote1 < iStart
1188 let iEnd = iSpace - 1
1189 let l:split_cmd += [ cmd[iStart : iEnd] ]
1191 let q = cmd[iQuote1]
1192 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1193 if iQuote2 < iQuote1
1194 throw 'No matching ' . q . ' quote'
1197 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1201 let iStart = iEnd + 1
1208 function! s:NM_run(args)
1210 call map(words, 's:NM_shell_escape(v:val)')
1211 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1213 let start = reltime()
1214 let out = system(cmd)
1215 let err = v:shell_error
1216 let delta = reltime(start)
1218 if exists('g:notmuch_debug') && g:notmuch_debug
1219 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1224 echo substitute(out, '\n*$', '', '')
1232 " --- external mail handling helpers {{{1
1234 function! s:NM_new_mail()
1235 call <SID>NM_cmd_compose([], [])
1238 " --- tag manipulation helpers {{{1
1240 " used to combine an array of words with prefixes and separators
1242 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1243 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1244 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1247 if len(res) && strlen(a:separator)
1248 call add(res, a:separator)
1250 call add(res, a:word_prefix . word)
1252 if len(res) > 1 && strlen(a:brackets)
1253 if strlen(a:brackets) != 2
1254 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1256 call insert(res, a:brackets[0])
1257 call add(res, a:brackets[1])
1262 " --- other helpers {{{1
1264 function! s:NM_get_search_words()
1265 if !exists('b:nm_search_words')
1266 throw 'Eeek! no b:nm_search_words'
1268 return b:nm_search_words
1271 function! s:NM_kill_this_buffer()
1272 if exists('b:nm_prev_bufnr')
1273 let prev_bufnr = b:nm_prev_bufnr
1275 exec printf("buffer %d", prev_bufnr)
1277 echo "This is the last buffer; use :q<CR> to quit."
1281 function! s:NM_search_expand(arg)
1282 let word = expand(a:arg)
1283 let prev_bufnr = bufnr('%')
1284 setlocal bufhidden=hide
1285 call <SID>NM_cmd_search([word])
1286 setlocal bufhidden=delete
1287 let b:nm_prev_bufnr = prev_bufnr
1290 function! s:NM_add_remove_tags(filter, prefix, tags)
1291 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1293 throw 'Eeek! I couldn''t find the thead id!'
1295 call map(a:tags, 'a:prefix . v:val')
1297 call extend(args, a:tags)
1298 call add(args, '--')
1299 call extend(args, filter)
1300 " TODO: handle errors
1301 call <SID>NM_run(args)
1304 function! s:NM_add_remove_tags_on_screen(online, prefix, tags)
1307 for tagname in a:tags
1308 exec printf('silent! %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', string(a:online), tagname)
1311 for tagname in a:tags
1312 exec printf('silent! %ss/(\([^)]*\))$/(\1 %s)/', string(a:online), tagname)
1315 setlocal nomodifiable
1318 " --- process and set the defaults {{{1
1320 function! NM_set_defaults(force)
1321 for [key, dflt] in items(s:notmuch_defaults)
1323 if !a:force && exists(key) && type(dflt) == type(eval(key))
1325 elseif type(dflt) == type(0)
1326 let cmd = printf('let %s = %d', key, dflt)
1327 elseif type(dflt) == type('')
1328 let cmd = printf('let %s = ''%s''', key, dflt)
1329 " FIXME: not sure why this didn't work when dflt is an array
1330 "elseif type(dflt) == type([])
1331 " let cmd = printf('let %s = %s', key, string(dflt))
1333 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1334 \ a:force, key, string(dflt))
1340 call NM_set_defaults(0)
1342 " for some reason NM_set_defaults() didn't work for arrays...
1343 if !exists('g:notmuch_show_headers')
1344 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1346 if !exists('g:notmuch_initial_search_words')
1347 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1349 if !exists('g:notmuch_folders')
1350 let g:notmuch_folders = s:notmuch_folders_defaults
1353 if !exists('g:notmuch_signature')
1354 let g:notmuch_signature = s:notmuch_signature_defaults
1356 if !exists('g:notmuch_compose_headers')
1357 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1360 " --- assign keymaps {{{1
1362 function! s:NM_set_map(type, maps)
1364 for [key, code] in items(a:maps)
1365 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1367 " --- this is a hack for development :)
1368 nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1371 " --- command handler {{{1
1373 function! NotMuch(args)
1376 let args = 'folders'
1379 let words = <SID>NM_shell_split(args)
1380 if words[0] == 'folders' || words[0] == 'f'
1381 let words = words[1:]
1382 call <SID>NM_cmd_folders(words)
1384 elseif words[0] == 'search' || words[0] == 's'
1386 let words = words[1:]
1387 elseif exists('b:nm_search_words')
1388 let words = b:nm_search_words
1390 let words = g:notmuch_initial_search_words
1392 call <SID>NM_cmd_search(words)
1394 elseif words[0] == 'show'
1395 echoe 'show is not yet implemented.'
1397 elseif words[0] == 'new' || words[0] == 'compose'
1398 let words = words[1:]
1399 call <SID>NM_cmd_compose(words, [])
1402 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1409 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1410 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1412 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :