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>',
140 \ 's': ':call <SID>NM_search_prompt()<CR>',
142 \ 'b': ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
143 \ 'c': ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
144 \ 'h': ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
145 \ 'i': ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
147 \ 'a': ':call <SID>NM_show_archive_thread()<CR>',
148 \ 'A': ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
149 \ 'N': ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
150 \ 'v': ':call <SID>NM_show_view_all_mime_parts()<CR>',
151 \ '+': ':call <SID>NM_show_add_tag()<CR>',
152 \ '-': ':call <SID>NM_show_remove_tag()<CR>',
153 \ '<Space>': ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
154 \ '\|': ':call <SID>NM_show_pipe_message()<CR>',
156 \ '<S-Tab>': ':call <SID>NM_show_previous_fold()<CR>',
157 \ '<Tab>': ':call <SID>NM_show_next_fold()<CR>',
158 \ '<Enter>': ':call <SID>NM_show_toggle_fold()<CR>',
160 \ 'r': ':call <SID>NM_show_reply()<CR>',
161 \ 'm': ':call <SID>NM_new_mail()<CR>',
162 \ '?': ':echo <SID>NM_show_message_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
165 " --- --- bindings for compose screen {{{2
166 let g:notmuch_compose_nmaps = {
167 \ ',s': ':call <SID>NM_compose_send()<CR>',
168 \ ',a': ':call <SID>NM_compose_attach()<CR>',
169 \ ',q': ':call <SID>NM_kill_this_buffer()<CR>',
170 \ '<Tab>': ':call <SID>NM_compose_next_entry_area()<CR>',
172 let g:notmuch_compose_imaps = {
173 \ '<Tab>': '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
176 " --- implement folders screen {{{1
178 function! s:NM_cmd_folders(words)
180 throw 'Not exapecting any arguments for folders command.'
185 for entry in g:notmuch_folders
186 let [ name, search ] = entry
187 let data = s:NM_run(cmd + [search])
188 let cnt = matchlist(data, '\(\d\+\)')[1]
189 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
190 call add(searches, search)
193 call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
194 let b:nm_searches = searches
195 let b:nm_timestamp = reltime()
197 call <SID>NM_cmd_folders_mksyntax()
198 call <SID>NM_set_map('n', g:notmuch_folders_maps)
203 function! s:NM_cmd_folders_mksyntax()
206 " --- --- folders screen action functions {{{2
208 function! s:NM_folders_refresh_view()
210 setlocal bufhidden=delete
211 call s:NM_cmd_folders([])
212 exec printf('norm %dG', lno)
215 function! s:NM_folders_show_search()
217 let search = b:nm_searches[line-1]
219 let prev_bufnr = bufnr('%')
220 setlocal bufhidden=hide
221 call <SID>NM_cmd_search([search])
222 setlocal bufhidden=delete
223 let b:nm_prev_bufnr = prev_bufnr
227 " --- implement search screen {{{1
229 function! s:NM_cmd_search(words)
231 if g:notmuch_search_newest_first
232 let cmd = cmd + ['--sort=newest-first']
234 let cmd = cmd + ['--sort=oldest-first']
236 let data = s:NM_run(cmd + a:words)
237 let lines = split(data, "\n")
238 let disp = copy(lines)
239 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
241 call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
242 let b:nm_raw_lines = lines
243 let b:nm_search_words = a:words
245 call <SID>NM_cmd_search_mksyntax()
246 call <SID>NM_set_map('n', g:notmuch_search_maps)
250 function! s:NM_cmd_search_fmtline(line)
251 let m = matchlist(a:line, '^\(thread:\S\+\)\s\([^]]\+\]\) \([^;]\+\); \(.*\) (\([^(]*\))$')
253 return 'ERROR PARSING: ' . a:line
255 let max = g:notmuch_search_from_column_width
257 if strlen(from) >= max
258 let from = substitute(m[3][0:max-4], '[^A-Za-z1-9_]*$', '', '') . '...'
260 return printf('%-20s %-20s | %s (%s)', m[2], from, m[4], m[5])
262 function! s:NM_cmd_search_mksyntax()
263 syntax clear nmSearchFrom
264 exec printf('syntax match nmSearchFrom /\(\] \)\@<=.\{%d\}/ oneline contained', g:notmuch_search_from_column_width)
267 " --- --- search screen action functions {{{2
269 function! s:NM_search_show_thread()
270 let id = <SID>NM_search_thread_id()
273 if exists('b:nm_search_words')
274 let words = ['('] + b:nm_search_words + [')', 'AND', id]
277 call <SID>NM_cmd_show(words)
282 function! s:NM_search_prompt()
283 " TODO: input() can support completion
284 let text = input('NotMuch Search: ')
286 let tags = split(text)
288 let tags = s:notmuch_initial_search_words_defaults
290 let prev_bufnr = bufnr('%')
291 if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
292 " TODO: we intend to replace the current buffer,
293 " ... maybe we could just clear it
294 let prev_bufnr = b:nm_prev_bufnr
295 setlocal bufhidden=delete
297 setlocal bufhidden=hide
299 call <SID>NM_cmd_search(tags)
300 setlocal bufhidden=delete
301 let b:nm_prev_bufnr = prev_bufnr
304 function! s:NM_search_edit()
305 " TODO: input() can support completion
306 let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
308 call <SID>NM_cmd_search(split(text))
312 function! s:NM_search_archive_thread()
313 call <SID>NM_add_remove_tags_on_screen('', '-', ['inbox'])
314 call <SID>NM_add_remove_tags([], '-', ['inbox'])
318 function! s:NM_search_filter()
319 call <SID>NM_search_filter_helper('Filter: ', '', '')
322 function! s:NM_search_filter_by_tag()
323 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
326 function! s:NM_search_filter_helper(prompt, prefix, joiner)
327 " TODO: input() can support completion
328 let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
333 let tags = b:nm_search_words + ['AND']
334 \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
336 let prev_bufnr = bufnr('%')
337 setlocal bufhidden=hide
338 call <SID>NM_cmd_search(tags)
339 setlocal bufhidden=delete
340 let b:nm_prev_bufnr = prev_bufnr
343 function! s:NM_search_toggle_order()
344 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
345 " FIXME: maybe this would be better done w/o reading re-reading the lines
346 " reversing the b:nm_raw_lines and the buffer lines would be better
347 call <SID>NM_search_refresh_view()
350 function! s:NM_search_reply_to_thread()
352 call add(cmd, <SID>NM_search_thread_id())
354 call extend(cmd, <SID>NM_get_search_words())
356 let data = <SID>NM_run(cmd)
357 let lines = split(data, "\n")
358 call <SID>NM_newComposeBuffer(lines, 0)
361 function! s:NM_search_add_tags(tags)
362 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
365 function! s:NM_search_remove_tags(tags)
366 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
369 function! s:NM_search_refresh_view()
371 let prev_bufnr = b:nm_prev_bufnr
372 setlocal bufhidden=delete
373 call <SID>NM_cmd_search(b:nm_search_words)
374 let b:nm_prev_bufnr = prev_bufnr
375 " FIXME: should find the line of the thread we were on if possible
376 exec printf('norm %dG', lno)
379 " --- --- search screen helper functions {{{2
381 function! s:NM_search_thread_id()
382 if !exists('b:nm_raw_lines')
383 throw 'Eeek! no b:nm_raw_lines'
385 let mnum = line('.') - 1
386 if len(b:nm_raw_lines) <= mnum
389 let info = b:nm_raw_lines[mnum]
390 let what = split(info, '\s\+')[0]
394 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
395 if type(a:intags) != type([]) || len(a:intags) == 0
396 " TODO: input() can support completion
397 let text = input(a:prompt)
401 let tags = split(text, ' ')
405 call <SID>NM_add_remove_tags([], a:prefix, tags)
406 call <SID>NM_add_remove_tags_on_screen('', a:prefix, tags)
409 " --- implement show screen {{{1
411 function! s:NM_cmd_show(words)
412 let prev_bufnr = bufnr('%')
413 let data = s:NM_run(['show'] + a:words)
414 let lines = split(data, "\n")
416 let info = s:NM_cmd_show_parse(lines)
418 setlocal bufhidden=hide
419 call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
420 setlocal bufhidden=delete
421 let b:nm_search_words = a:words
422 let b:nm_raw_info = info
423 let b:nm_prev_bufnr = prev_bufnr
425 call <SID>NM_cmd_show_mkfolds()
426 call <SID>NM_cmd_show_mksyntax()
427 call <SID>NM_set_map('n', g:notmuch_show_maps)
428 setlocal foldtext=NM_cmd_show_foldtext()
430 setlocal foldcolumn=6
434 function! s:NM_show_previous(can_change_thread, find_matching)
435 let info = b:nm_raw_info
437 for msg in reverse(copy(info['msgs']))
438 if a:find_matching && msg['match'] == '0'
441 if lnum <= msg['start']
445 exec printf('norm %dGzt', msg['start'])
446 " TODO: try to fit the message on screen
449 if !a:can_change_thread
452 call <SID>NM_kill_this_buffer()
455 call <SID>NM_search_show_thread()
457 call <SID>NM_show_previous(0, a:find_matching)
459 echo 'No more messages.'
463 function! s:NM_show_next(can_change_thread, find_matching)
464 let info = b:nm_raw_info
466 for msg in info['msgs']
467 if a:find_matching && msg['match'] == '0'
470 if lnum >= msg['start']
474 exec printf('norm %dGzt', msg['start'])
475 " TODO: try to fit the message on screen
478 if a:can_change_thread
479 call <SID>NM_show_next_thread()
483 function! s:NM_show_next_thread()
484 call <SID>NM_kill_this_buffer()
485 if line('.') != line('$')
487 call <SID>NM_search_show_thread()
489 echo 'No more messages.'
493 function! s:NM_show_archive_thread()
494 echo 'not implemented'
497 function! s:NM_show_mark_read_then_archive_thread()
498 echo 'not implemented'
501 function! s:NM_show_mark_read_then_next_open_message()
502 echo 'not implemented'
505 function! s:NM_show_previous_message()
506 echo 'not implemented'
509 function! s:NM_show_reply()
511 call add(cmd, <SID>NM_show_message_id())
513 call extend(cmd, <SID>NM_get_search_words())
515 let data = <SID>NM_run(cmd)
516 let lines = split(data, "\n")
517 call <SID>NM_newComposeBuffer(lines, 0)
520 function! s:NM_show_view_all_mime_parts()
521 echo 'not implemented'
524 function! s:NM_show_view_raw_message()
525 echo 'not implemented'
528 function! s:NM_show_add_tag()
529 echo 'not implemented'
532 function! s:NM_show_remove_tag()
533 echo 'not implemented'
536 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
537 " otherwise go to next message
538 " any message that is viewed entirely has inbox and unread tags removed
539 function! s:NM_show_advance_marking_read_and_archiving()
540 let advance_tags = ['unread', 'inbox']
542 let vis_top = line('w0')
543 let vis_bot = line('w$')
545 let msg_top = <SID>NM_show_get_message_for_line(vis_top)
546 if !has_key(msg_top,'id')
547 throw "No top visible message."
550 " if the top message is the last message, just expunge the entire thread and move on
551 if msg_top['end'] == line('$')
553 for msg in b:nm_raw_info['msgs']
554 if has_key(msg,'match') && msg['match'] != '0'
555 call add(ids, msg['id'])
558 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
560 \ + <SID>NM_combine_tags('', ids, 'OR', '()')
561 call <SID>NM_add_remove_tags(filter, '-', advance_tags)
562 call <SID>NM_show_next(1, 1)
566 let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
567 if !has_key(msg_bot,'id')
568 throw "No bottom visible message."
571 " if entire message fits on the screen, read/archive it, move to the next one
572 if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
573 call <SID>NM_add_remove_tags_on_screen(msg_top['start'], '-', advance_tags)
574 exec printf('norm %dG', vis_top)
575 call <SID>NM_show_next(0, 1)
576 if has_key(msg_top,'match') && msg_top['match'] != '0'
578 " do this last to hide the latency
579 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
580 \ + ['AND', msg_top['id']]
581 call <SID>NM_add_remove_tags(filter, '-', advance_tags)
586 " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
587 let jmp = winheight(winnr()) / 2
588 let max = msg_bot['end'] - vis_bot
592 exec printf('norm %dGzt', vis_top + jmp)
596 function! s:NM_show_pipe_message()
597 echo 'not implemented'
600 function! s:NM_show_previous_fold()
601 echo 'not implemented'
604 function! s:NM_show_next_fold()
605 echo 'not implemented'
608 function! s:NM_show_toggle_fold()
609 echo 'not implemented'
613 " --- --- show screen helper functions {{{2
615 function! s:NM_show_get_message_for_line(line)
616 for msg in b:nm_raw_info['msgs']
617 if a:line > msg['end']
625 function! s:NM_show_message_id()
626 if !exists('b:nm_raw_info')
627 throw 'Eeek! no b:nm_raw_info'
629 let msg = <SID>NM_show_get_message_for_line(line('.'))
636 function! s:NM_show_fold_toggle(key, type, fold)
637 let info = b:nm_raw_info
642 for fld in info['folds']
647 "let msg = info['msgs'][idx]
648 "if has_key(msg,'match') && msg['match'] == '0'
651 let cls = foldclosed(fld[1])
652 if cls != -1 && cls != fld[1]
655 exec printf('%dfold%s', fld[1], act)
657 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
661 " s:NM_cmd_show_parse returns the following dictionary:
662 " 'disp': lines to display
663 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
664 " 'folds': fold info arrays [ type, start, end ]
665 " 'foldtext': fold text indexed by start line
666 function! s:NM_cmd_show_parse(inlines)
667 let info = { 'disp': [],
686 for line in a:inlines
687 let inlnum = inlnum + 1
693 if match(line, g:notmuch_show_part_end_regexp) != -1
694 let part_end = len(info['disp'])
696 call add(info['disp'], line)
699 if in_part == 'text/plain'
700 if !part_end && mode_type == ''
701 if match(line, g:notmuch_show_signature_regexp) != -1
702 let mode_type = 'sig'
703 let mode_start = len(info['disp'])
704 elseif match(line, g:notmuch_show_citation_regexp) != -1
705 let mode_type = 'cit'
706 let mode_start = len(info['disp'])
708 elseif mode_type == 'cit'
709 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
710 let outlnum = len(info['disp'])
711 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
712 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
715 elseif mode_type == 'sig'
716 let outlnum = len(info['disp'])
717 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
720 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
721 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
728 " FIXME: this is a hack for handling two folds being added for one line
729 " we should handle addinga fold in a function
730 if len(foldinfo) && foldinfo[1] < foldinfo[2]
731 call add(info['folds'], foldinfo[0:3])
732 let info['foldtext'][foldinfo[1]] = foldinfo[4]
735 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
736 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
738 call add(info['disp'], '')
742 if !has_key(msg,'body_start')
743 let msg['body_start'] = len(info['disp']) + 1
745 if match(line, g:notmuch_show_body_end_regexp) != -1
746 let body_end = len(info['disp'])
747 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
748 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
752 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
753 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
754 let in_part = 'unknown'
758 call add(info['disp'],
759 \ printf('--- %s ---', in_part))
760 let part_start = len(info['disp']) + 1
765 let msg['descr'] = line
766 call add(info['disp'], line)
768 let msg['hdr_start'] = len(info['disp']) + 1
771 if match(line, g:notmuch_show_header_end_regexp) != -1
772 let hdr_start = msg['hdr_start']+1
773 let hdr_end = len(info['disp'])
774 let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
775 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
776 let msg['header'] = hdr
780 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
783 if match(g:notmuch_show_headers, m[1]) != -1
784 call add(info['disp'], line)
791 if match(line, g:notmuch_show_message_end_regexp) != -1
792 let msg['end'] = len(info['disp'])
793 call add(info['disp'], '')
795 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
796 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
798 call add(info['msgs'], msg)
805 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
809 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
810 let body_start = len(info['disp']) + 1
816 if match(line, g:notmuch_show_message_begin_regexp) != -1
817 let msg['start'] = len(info['disp']) + 1
819 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
822 let msg['depth'] = m[2]
823 let msg['match'] = m[3]
824 let msg['filename'] = m[4]
831 if len(foldinfo) && foldinfo[1] < foldinfo[2]
832 call add(info['folds'], foldinfo[0:3])
833 let info['foldtext'][foldinfo[1]] = foldinfo[4]
839 function! s:NM_cmd_show_mkfolds()
840 let info = b:nm_raw_info
842 for afold in info['folds']
843 exec printf('%d,%dfold', afold[1], afold[2])
845 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
846 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
847 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
848 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
850 elseif afold[0] == 'msg'
852 let msg = info['msgs'][idx]
853 if has_key(msg,'match') && msg['match'] == '0'
857 exec printf('%dfold%s', afold[1], state)
861 function! s:NM_cmd_show_mksyntax()
862 let info = b:nm_raw_info
864 for msg in info['msgs']
866 let start = msg['start']
867 let hdr_start = msg['hdr_start']
868 let body_start = msg['body_start']
870 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
871 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
872 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
876 function! NM_cmd_show_foldtext()
877 let foldtext = b:nm_raw_info['foldtext']
878 return foldtext[v:foldstart]
882 " --- implement compose screen {{{1
884 function! s:NM_cmd_compose(words, body_lines)
886 let start_on_line = 0
890 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
892 throw 'Eeek! bad parameter ''' . string(word) . ''''
894 let key = substitute(m[1], '\<\w', '\U&', 'g')
895 if !has_key(hdrs, key)
899 call add(hdrs[key], m[2])
903 if !has_key(hdrs, 'From') || !len(hdrs['From'])
904 let me = <SID>NM_compose_get_user_email()
905 let hdrs['From'] = [ me ]
908 for key in g:notmuch_compose_headers
909 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
910 call add(lines, key . ': ' . text)
911 if !start_on_line && !strlen(text)
912 let start_on_line = len(lines)
916 for [key,val] in items(hdrs)
917 if match(g:notmuch_compose_headers, key) == -1
918 let line = key . ': ' . join(val, ', ')
919 call add(lines, line)
925 let start_on_line = len(lines) + 1
929 call extend(lines, a:body_lines)
931 call extend(lines, [ '', '' ])
934 call <SID>NM_newComposeBuffer(lines, start_on_line)
937 function! s:NM_compose_send()
938 call <SID>NM_assert_buffer_type('compose')
939 let fname = expand('%')
941 let line = getline(lnum)
944 while match(line, '^$') == -1
945 if match(line, '^Notmuch-Help:') != -1
947 elseif strlen(lst_hdr) && match(line, '^\s') != -1
948 let hdrs[lst_hdr][-1] = hdrs[lst_hdr][-1] . substitute(line, '^\s*', ' ', '')
950 let m = matchlist(line, '^\(\w[^:]*\):\s*\(.*\)\s*$')
953 throw printf('Eeek! invalid header on line %d', lnum)
955 let key = substitute(m[1], '\<\w', '\U&', 'g')
957 if !has_key(hdrs, key)
960 call add(hdrs[key], m[2])
965 let line = getline(lnum)
967 let body_starts = lnum
969 "[-a header] [-b bcc-addr] [-c cc-addr] [-s subject] to-addr
972 for [key, vals] in items(hdrs)
974 call extend(tos, vals)
985 elseif key == 'Subject'
993 call add(cmd, key . ': ' . val)
997 call extend(cmd, tos)
999 " TODO: make sure we have at least one target
1000 " TODO: ask about empty jubject, etc
1002 exec printf('0,%dd', body_starts)
1005 call map(cmd, 's:NM_shell_escape(v:val)')
1006 let cmdtxt = join(cmd) . '< ' . fname
1007 let out = system(cmdtxt)
1008 let err = v:shell_error
1012 call <SID>NM_newBuffer('new', 'error',
1013 \ "While running...\n" .
1014 \ ' ' . cmdtxt . "\n" .
1016 \ "Failed with...\n" .
1017 \ substitute(out, '^', ' ', 'g'))
1019 echo 'Eeek! unable to send mail'
1024 if !exists('b:nm_prev_bufnr')
1027 let prev_bufnr = b:nm_prev_bufnr
1029 if prev_bufnr == bufnr('%')
1030 exec printf("buffer %d", prev_bufnr)
1034 echo 'Mail sent successfully.'
1037 function! s:NM_compose_attach()
1038 echo 'not implemented'
1041 function! s:NM_compose_next_entry_area()
1042 let lnum = line('.')
1043 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1046 let line = getline(lnum)
1047 if match(line, '^\([^:]\+\):\s*$') == -1
1048 call cursor(lnum, strlen(line) + 1)
1051 while match(getline(lnum+1), '^\s') != -1
1054 call cursor(lnum, strlen(getline(lnum)) + 1)
1057 elseif lnum == hdr_end
1058 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1062 if !getbufvar(bufnr('.'), '&et')
1066 let shiftwidth = a:shiftwidth
1067 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1068 " we assume no one has shiftwidth set to more than 40 :)
1069 return ' '[0:shiftwidth]
1073 " --- --- compose screen helper functions {{{2
1075 function! s:NM_compose_get_user_email()
1076 let name = substitute(system('id -u -n'), '\v(^\s*|\s*$|\n)', '', 'g')
1077 let fqdn = substitute(system('hostname -f'), '\v(^\s*|\s*$|\n)', '', 'g')
1079 " TODO: do this properly
1080 return name . '@' . fqdn
1083 function! s:NM_compose_find_line_match(start, pattern, failure)
1085 let lend = line('$')
1087 if match(getline(lnum), a:pattern) != -1
1096 " --- notmuch helper functions {{{1
1098 function! s:NM_newBuffer(how, type, content)
1104 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1105 silent put=a:content
1107 setlocal nomodifiable
1108 execute printf('set filetype=notmuch-%s', a:type)
1109 execute printf('set syntax=notmuch-%s', a:type)
1110 let b:nm_type = a:type
1113 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1114 let fdir = expand(a:fdir)
1115 if !isdirectory(fdir)
1116 call mkdir(fdir, 'p')
1118 let file_name = <SID>NM_mktemp(fdir, a:fname)
1119 if writefile(a:lines, file_name)
1120 throw 'Eeek! couldn''t write to temporary file ' . file_name
1122 exec printf('edit %s', file_name)
1123 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1124 execute printf('set filetype=notmuch-%s', a:type)
1125 execute printf('set syntax=notmuch-%s', a:type)
1126 let b:nm_type = a:type
1129 function! s:NM_newComposeBuffer(lines, start_on_line)
1131 let start_on_line = a:start_on_line
1132 let real_hdr_start = 1
1133 if g:notmuch_compose_header_help
1135 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1136 \ 'Notmuch-Help: ,a - attach a file',
1137 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
1138 \ 'Notmuch-Help: ,q - abort the message',
1139 \ 'Notmuch-Help: <Tab> - skip through header lines',
1141 call extend(lines, help_lines, 0)
1142 let real_hdr_start = len(help_lines)
1143 if start_on_line > 0
1144 let start_on_line = start_on_line + len(help_lines)
1147 call extend(lines, g:notmuch_signature)
1150 let prev_bufnr = bufnr('%')
1151 setlocal bufhidden=hide
1152 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1154 setlocal bufhidden=hide
1155 let b:nm_prev_bufnr = prev_bufnr
1157 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1158 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1160 if start_on_line > 0 && start_on_line <= len(lines)
1161 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1163 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1164 call <SID>NM_compose_next_entry_area()
1167 if g:notmuch_compose_insert_mode_start
1170 echo 'Type your message, use <TAB> to jump to next header and then body.'
1173 function! s:NM_assert_buffer_type(type)
1174 if !exists('b:nm_type') || b:nm_type != a:type
1175 throw printf('Eeek! expected type %s, but got %s.', a:type,
1176 \ exists(b:nm_type) ? b:nm_type : 'something else')
1180 function! s:NM_mktemp(dir, name)
1181 let time_stamp = strftime('%Y%m%d-%H%M%S')
1182 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1183 " TODO: check if it exists, try again
1187 function! s:NM_shell_escape(word)
1188 " TODO: use shellescape()
1189 let word = substitute(a:word, '''', '\\''', 'g')
1190 return '''' . word . ''''
1193 " this function was taken from git.vim, then fixed up
1194 " http://github.com/motemen/git-vim
1195 function! s:NM_shell_split(cmd)
1196 let l:split_cmd = []
1200 let t = match(cmd, '\S', iStart)
1206 let iSpace = match(cmd, '\v(\s|$)', iStart)
1211 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1212 if iQuote1 > iSpace || iQuote1 < iStart
1213 let iEnd = iSpace - 1
1214 let l:split_cmd += [ cmd[iStart : iEnd] ]
1216 let q = cmd[iQuote1]
1217 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1218 if iQuote2 < iQuote1
1219 throw 'No matching ' . q . ' quote'
1222 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1226 let iStart = iEnd + 1
1233 function! s:NM_run(args)
1235 call map(words, 's:NM_shell_escape(v:val)')
1236 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1238 let start = reltime()
1239 let out = system(cmd)
1240 let err = v:shell_error
1241 let delta = reltime(start)
1243 if exists('g:notmuch_debug') && g:notmuch_debug
1244 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1249 echo substitute(out, '\n*$', '', '')
1257 " --- external mail handling helpers {{{1
1259 function! s:NM_new_mail()
1260 call <SID>NM_cmd_compose([], [])
1263 " --- tag manipulation helpers {{{1
1265 " used to combine an array of words with prefixes and separators
1267 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1268 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1269 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1272 if len(res) && strlen(a:separator)
1273 call add(res, a:separator)
1275 call add(res, a:word_prefix . word)
1277 if len(res) > 1 && strlen(a:brackets)
1278 if strlen(a:brackets) != 2
1279 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1281 call insert(res, a:brackets[0])
1282 call add(res, a:brackets[1])
1287 " --- other helpers {{{1
1289 function! s:NM_get_search_words()
1290 if !exists('b:nm_search_words')
1291 throw 'Eeek! no b:nm_search_words'
1293 return b:nm_search_words
1296 function! s:NM_kill_this_buffer()
1297 if exists('b:nm_prev_bufnr')
1298 let prev_bufnr = b:nm_prev_bufnr
1300 exec printf("buffer %d", prev_bufnr)
1302 echo "This is the last buffer; use :q<CR> to quit."
1306 function! s:NM_search_expand(arg)
1307 let word = expand(a:arg)
1308 let prev_bufnr = bufnr('%')
1309 setlocal bufhidden=hide
1310 call <SID>NM_cmd_search([word])
1311 setlocal bufhidden=delete
1312 let b:nm_prev_bufnr = prev_bufnr
1315 function! s:NM_add_remove_tags(filter, prefix, tags)
1316 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1318 throw 'Eeek! I couldn''t find the thead id!'
1320 call map(a:tags, 'a:prefix . v:val')
1322 call extend(args, a:tags)
1323 call add(args, '--')
1324 call extend(args, filter)
1325 " TODO: handle errors
1326 call <SID>NM_run(args)
1329 function! s:NM_add_remove_tags_on_screen(online, prefix, tags)
1332 for tagname in a:tags
1333 exec printf('silent! %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', string(a:online), tagname)
1336 for tagname in a:tags
1337 exec printf('silent! %ss/(\([^)]*\))$/(\1 %s)/', string(a:online), tagname)
1340 setlocal nomodifiable
1343 " --- process and set the defaults {{{1
1345 function! NM_set_defaults(force)
1346 for [key, dflt] in items(s:notmuch_defaults)
1348 if !a:force && exists(key) && type(dflt) == type(eval(key))
1350 elseif type(dflt) == type(0)
1351 let cmd = printf('let %s = %d', key, dflt)
1352 elseif type(dflt) == type('')
1353 let cmd = printf('let %s = ''%s''', key, dflt)
1354 " FIXME: not sure why this didn't work when dflt is an array
1355 "elseif type(dflt) == type([])
1356 " let cmd = printf('let %s = %s', key, string(dflt))
1358 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1359 \ a:force, key, string(dflt))
1365 call NM_set_defaults(0)
1367 " for some reason NM_set_defaults() didn't work for arrays...
1368 if !exists('g:notmuch_show_headers')
1369 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1371 if !exists('g:notmuch_initial_search_words')
1372 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1374 if !exists('g:notmuch_folders')
1375 let g:notmuch_folders = s:notmuch_folders_defaults
1378 if !exists('g:notmuch_signature')
1379 let g:notmuch_signature = s:notmuch_signature_defaults
1381 if !exists('g:notmuch_compose_headers')
1382 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1385 " --- assign keymaps {{{1
1387 function! s:NM_set_map(type, maps)
1389 for [key, code] in items(a:maps)
1390 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1392 " --- this is a hack for development :)
1393 nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1396 " --- command handler {{{1
1398 function! NotMuch(args)
1401 let args = 'folders'
1404 let words = <SID>NM_shell_split(args)
1405 if words[0] == 'folders' || words[0] == 'f'
1406 let words = words[1:]
1407 call <SID>NM_cmd_folders(words)
1409 elseif words[0] == 'search' || words[0] == 's'
1411 let words = words[1:]
1412 elseif exists('b:nm_search_words')
1413 let words = b:nm_search_words
1415 let words = g:notmuch_initial_search_words
1417 call <SID>NM_cmd_search(words)
1419 elseif words[0] == 'show'
1420 echoe 'show is not yet implemented.'
1422 elseif words[0] == 'new' || words[0] == 'compose'
1423 let words = words[1:]
1424 call <SID>NM_cmd_compose(words, [])
1427 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1434 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1435 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1437 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :