1 " notmuch.vim plugin --- run notmuch within vim
3 " Copyright © Carl Worth
5 " This file is part of Notmuch.
7 " Notmuch is free software: you can redistribute it and/or modify it
8 " under the terms of the GNU General Public License as published by
9 " the Free Software Foundation, either version 3 of the License, or
10 " (at your option) any later version.
12 " Notmuch is distributed in the hope that it will be useful, but
13 " WITHOUT ANY WARRANTY; without even the implied warranty of
14 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 " General Public License for more details.
17 " You should have received a copy of the GNU General Public License
18 " along with Notmuch. If not, see <http://www.gnu.org/licenses/>.
20 " Authors: Bart Trojanowski <bart@jukie.net>
21 " Contributors: Felipe Contreras <felipe.contreras@gmail.com>,
22 " Peter Hartman <peterjohnhartman@gmail.com>
24 " --- configuration defaults {{{1
26 let s:notmuch_defaults = {
27 \ 'g:notmuch_cmd': 'notmuch' ,
28 \ 'g:notmuch_sendmail': 'sendmail' ,
29 \ 'g:notmuch_debug': 0 ,
31 \ 'g:notmuch_search_newest_first': 1 ,
32 \ 'g:notmuch_search_from_column_width': 20 ,
34 \ 'g:notmuch_show_fold_signatures': 1 ,
35 \ 'g:notmuch_show_fold_citations': 1 ,
36 \ 'g:notmuch_show_fold_bodies': 0 ,
37 \ 'g:notmuch_show_fold_headers': 1 ,
39 \ 'g:notmuch_show_message_begin_regexp': '
\fmessage{' ,
40 \ 'g:notmuch_show_message_end_regexp': '
\fmessage}' ,
41 \ 'g:notmuch_show_header_begin_regexp': '
\fheader{' ,
42 \ 'g:notmuch_show_header_end_regexp': '
\fheader}' ,
43 \ 'g:notmuch_show_body_begin_regexp': '
\fbody{' ,
44 \ 'g:notmuch_show_body_end_regexp': '
\fbody}' ,
45 \ 'g:notmuch_show_attachment_begin_regexp': '
\fattachment{' ,
46 \ 'g:notmuch_show_attachment_end_regexp': '
\fattachment}' ,
47 \ 'g:notmuch_show_part_begin_regexp': '
\fpart{' ,
48 \ 'g:notmuch_show_part_end_regexp': '
\fpart}' ,
49 \ 'g:notmuch_show_marker_regexp': '
\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
51 \ 'g:notmuch_show_message_parse_regexp': '\(id:[^ ]*\) depth:\([0-9]*\) match:\([0-9]*\) filename:\(.*\)$',
52 \ 'g:notmuch_show_tags_regexp': '(\([^)]*\))$' ,
54 \ 'g:notmuch_show_signature_regexp': '^\(-- \?\|_\+\)$' ,
55 \ 'g:notmuch_show_signature_lines_max': 12 ,
57 \ 'g:notmuch_show_citation_regexp': '^\s*>' ,
59 \ 'g:notmuch_compose_insert_mode_start': 1 ,
60 \ 'g:notmuch_compose_header_help': 1 ,
61 \ 'g:notmuch_compose_temp_file_dir': '~/.notmuch/compose/' ,
64 " defaults for g:notmuch_initial_search_words
65 " override with: let g:notmuch_initial_search_words = [ ... ]
66 let s:notmuch_initial_search_words_defaults = [
67 \ 'tag:inbox and tag:unread',
70 " defaults for g:notmuch_show_headers
71 " override with: let g:notmuch_show_headers = [ ... ]
72 let s:notmuch_show_headers_defaults = [
80 " defaults for g:notmuch_folders
81 " override with: let g:notmuch_folders = [ ... ]
82 let s:notmuch_folders_defaults = [
83 \ [ 'new', 'tag:inbox and tag:unread' ],
84 \ [ 'inbox', 'tag:inbox' ],
85 \ [ 'unread', 'tag:unread' ],
88 " defaults for g:notmuch_signature
89 " override with: let g:notmuch_signature = [ ... ]
90 let s:notmuch_signature_defaults = [
93 \ 'email sent from notmuch.vim plugin'
96 " defaults for g:notmuch_compose_headers
97 " override with: let g:notmuch_compose_headers = [ ... ]
98 let s:notmuch_compose_headers_defaults = [
106 " --- keyboard mapping definitions {{{1
108 " --- --- bindings for folders mode {{{2
110 let g:notmuch_folders_maps = {
111 \ 'm': ':call <SID>NM_new_mail()<CR>',
112 \ 's': ':call <SID>NM_search_prompt()<CR>',
113 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
114 \ '=': ':call <SID>NM_folders_refresh_view()<CR>',
115 \ '<Enter>': ':call <SID>NM_folders_show_search()<CR>',
118 " --- --- bindings for search screen {{{2
119 let g:notmuch_search_maps = {
120 \ '<Space>': ':call <SID>NM_search_show_thread(0)<CR>',
121 \ '<Enter>': ':call <SID>NM_search_show_thread(1)<CR>',
122 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
123 \ 'I': ':call <SID>NM_search_mark_read_thread()<CR>',
124 \ 'a': ':call <SID>NM_search_archive_thread()<CR>',
125 \ 'A': ':call <SID>NM_search_mark_read_then_archive_thread()<CR>',
126 \ 'f': ':call <SID>NM_search_filter()<CR>',
127 \ 'm': ':call <SID>NM_new_mail()<CR>',
128 \ 'o': ':call <SID>NM_search_toggle_order()<CR>',
129 \ 'r': ':call <SID>NM_search_reply_to_thread()<CR>',
130 \ 's': ':call <SID>NM_search_prompt()<CR>',
131 \ ',s': ':call <SID>NM_search_edit()<CR>',
132 \ 't': ':call <SID>NM_search_filter_by_tag()<CR>',
133 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
134 \ '+': ':call <SID>NM_search_add_tags([])<CR>',
135 \ '-': ':call <SID>NM_search_remove_tags([])<CR>',
136 \ '=': ':call <SID>NM_search_refresh_view()<CR>',
137 \ '?': ':echo <SID>NM_search_thread_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
140 " --- --- bindings for show screen {{{2
141 let g:notmuch_show_maps = {
142 \ '<C-P>': ':call <SID>NM_show_previous(1, 0)<CR>',
143 \ '<C-N>': ':call <SID>NM_show_next(1, 0)<CR>',
144 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
145 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
146 \ 's': ':call <SID>NM_search_prompt()<CR>',
148 \ 'b': ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
149 \ 'c': ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
150 \ 'h': ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
151 \ 'i': ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
153 \ 'I': ':call <SID>NM_show_mark_read_thread()<CR>',
154 \ 'a': ':call <SID>NM_show_archive_thread()<CR>',
155 \ 'A': ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
156 \ 'N': ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
157 \ 'v': ':call <SID>NM_show_view_all_mime_parts()<CR>',
158 \ '+': ':call <SID>NM_show_add_tag()<CR>',
159 \ '-': ':call <SID>NM_show_remove_tag()<CR>',
160 \ '<Space>': ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
161 \ '\|': ':call <SID>NM_show_pipe_message()<CR>',
163 \ '<S-Tab>': ':call <SID>NM_show_previous_fold()<CR>',
164 \ '<Tab>': ':call <SID>NM_show_next_fold()<CR>',
165 \ '<Enter>': ':call <SID>NM_show_toggle_fold()<CR>',
167 \ 'r': ':call <SID>NM_show_reply()<CR>',
168 \ 'm': ':call <SID>NM_new_mail()<CR>',
169 \ '?': ':echo <SID>NM_show_message_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
172 " --- --- bindings for compose screen {{{2
173 let g:notmuch_compose_nmaps = {
174 \ ',s': ':call <SID>NM_compose_send()<CR>',
175 \ ',a': ':call <SID>NM_compose_attach()<CR>',
176 \ ',q': ':call <SID>NM_kill_this_buffer()<CR>',
177 \ '<Tab>': ':call <SID>NM_compose_next_entry_area()<CR>',
179 let g:notmuch_compose_imaps = {
180 \ '<Tab>': '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
183 " --- implement folders screen {{{1
185 function! s:NM_cmd_folders(words)
187 throw 'Not expecting any arguments for folders command.'
192 for entry in g:notmuch_folders
193 let [ name, search ] = entry
194 let data = s:NM_run(cmd + [search])
195 let cnt = matchlist(data, '\(\d\+\)')[1]
196 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
197 call add(searches, search)
200 call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
201 let b:nm_searches = searches
202 let b:nm_timestamp = reltime()
204 call <SID>NM_cmd_folders_mksyntax()
205 call <SID>NM_set_map('n', g:notmuch_folders_maps)
210 function! s:NM_cmd_folders_mksyntax()
213 " --- --- folders screen action functions {{{2
215 function! s:NM_folders_refresh_view()
217 setlocal bufhidden=delete
218 call s:NM_cmd_folders([])
219 exec printf('norm %dG', lno)
222 function! s:NM_folders_show_search()
224 let search = b:nm_searches[line-1]
226 let prev_bufnr = bufnr('%')
227 setlocal bufhidden=hide
228 call <SID>NM_cmd_search([search])
229 setlocal bufhidden=delete
230 let b:nm_prev_bufnr = prev_bufnr
234 " --- implement search screen {{{1
236 function! s:NM_cmd_search(words)
238 if g:notmuch_search_newest_first
239 let cmd = cmd + ['--sort=newest-first']
241 let cmd = cmd + ['--sort=oldest-first']
243 let data = s:NM_run(cmd + a:words)
244 let lines = split(data, "\n")
245 let disp = copy(lines)
246 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
248 call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
249 let b:nm_raw_lines = lines
250 let b:nm_search_words = a:words
252 call <SID>NM_set_map('n', g:notmuch_search_maps)
256 function! s:NM_cmd_search_fmtline(line)
257 let m = matchlist(a:line, '^\(thread:\S\+\)\s\(.\{12\}\) \[\(\d\+\)/\d\+\] \([^;]\+\); \%(\[[^\[]\+\] \)*\(.*\) (\([^(]*\))$')
259 return 'ERROR PARSING: ' . a:line
261 let max = g:notmuch_search_from_column_width
263 for at in split(m[4], ", ")
264 let p = min([stridx(at, "."), stridx(at, "@")])
265 call insert(flist, tolower(at[0:p - 1]))
267 let from = join(flist, ", ")
268 return printf("%-12s %3s %-20.20s | %s (%s)", m[2], m[3], from, m[5], m[6])
271 " --- --- search screen action functions {{{2
273 function! s:NM_search_show_thread(everything)
274 let words = [ <SID>NM_search_thread_id() ]
275 if !a:everything && exists('b:nm_search_words')
276 call extend(words, ['AND', '('])
277 call extend(words, b:nm_search_words)
280 call <SID>NM_cmd_show(words)
281 let b:nm_show_everything = a:everything
284 function! s:NM_search_prompt()
285 " TODO: input() can support completion
286 let text = input('NotMuch Search: ')
288 let tags = split(text)
290 let tags = s:notmuch_initial_search_words_defaults
292 let prev_bufnr = bufnr('%')
293 if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
294 " TODO: we intend to replace the current buffer,
295 " ... maybe we could just clear it
296 let prev_bufnr = b:nm_prev_bufnr
297 setlocal bufhidden=delete
299 setlocal bufhidden=hide
301 call <SID>NM_cmd_search(tags)
302 setlocal bufhidden=delete
303 let b:nm_prev_bufnr = prev_bufnr
306 function! s:NM_search_edit()
307 " TODO: input() can support completion
308 let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
310 call <SID>NM_cmd_search(split(text))
314 function! s:NM_search_mark_read_thread()
315 call <SID>NM_tag([], ['-unread'])
319 function! s:NM_search_archive_thread()
320 call <SID>NM_tag([], ['-inbox'])
324 function! s:NM_search_mark_read_then_archive_thread()
325 call <SID>NM_tag([], ['-unread', '-inbox'])
329 function! s:NM_search_filter()
330 call <SID>NM_search_filter_helper('Filter: ', '', '')
333 function! s:NM_search_filter_by_tag()
334 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
337 function! s:NM_search_filter_helper(prompt, prefix, joiner)
338 " TODO: input() can support completion
339 let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
344 let tags = b:nm_search_words + ['AND']
345 \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
347 let prev_bufnr = bufnr('%')
348 setlocal bufhidden=hide
349 call <SID>NM_cmd_search(tags)
350 setlocal bufhidden=delete
351 let b:nm_prev_bufnr = prev_bufnr
354 function! s:NM_search_toggle_order()
355 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
356 " FIXME: maybe this would be better done w/o reading re-reading the lines
357 " reversing the b:nm_raw_lines and the buffer lines would be better
358 call <SID>NM_search_refresh_view()
361 function! s:NM_search_reply_to_thread()
363 call add(cmd, <SID>NM_search_thread_id())
365 call extend(cmd, <SID>NM_get_search_words())
367 let data = <SID>NM_run(cmd)
368 let lines = split(data, "\n")
369 call <SID>NM_newComposeBuffer(lines, 0)
372 function! s:NM_search_add_tags(tags)
373 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
376 function! s:NM_search_remove_tags(tags)
377 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
380 function! s:NM_search_refresh_view()
382 let prev_bufnr = b:nm_prev_bufnr
383 setlocal bufhidden=delete
384 call <SID>NM_cmd_search(b:nm_search_words)
385 let b:nm_prev_bufnr = prev_bufnr
386 " FIXME: should find the line of the thread we were on if possible
387 exec printf('norm %dG', lno)
390 " --- --- search screen helper functions {{{2
392 function! s:NM_search_thread_id()
393 if !exists('b:nm_raw_lines')
394 throw 'Eeek! no b:nm_raw_lines'
396 let mnum = line('.') - 1
397 if len(b:nm_raw_lines) <= mnum
400 let info = b:nm_raw_lines[mnum]
401 let what = split(info, '\s\+')[0]
405 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
406 if type(a:intags) != type([]) || len(a:intags) == 0
407 " TODO: input() can support completion
408 let text = input(a:prompt)
412 let tags = split(text, ' ')
416 call map(tags, 'a:prefix . v:val')
417 call <SID>NM_tag([], tags)
420 " --- implement show screen {{{1
422 function! s:NM_cmd_show(words)
423 let prev_bufnr = bufnr('%')
424 let data = s:NM_run(['show', '--entire-thread'] + a:words)
425 let lines = split(data, "\n")
427 let info = s:NM_cmd_show_parse(lines)
429 setlocal bufhidden=hide
430 call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
431 setlocal bufhidden=delete
432 let b:nm_search_words = a:words
433 let b:nm_raw_info = info
434 let b:nm_prev_bufnr = prev_bufnr
436 call <SID>NM_cmd_show_mkfolds()
437 call <SID>NM_cmd_show_mksyntax()
438 call <SID>NM_set_map('n', g:notmuch_show_maps)
439 setlocal foldtext=NM_cmd_show_foldtext()
441 setlocal foldcolumn=6
445 function! s:NM_show_previous(can_change_thread, find_matching)
446 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
447 let info = b:nm_raw_info
449 for msg in reverse(copy(info['msgs']))
450 if a:find_matching && msg['match'] == '0'
453 if lnum <= msg['start']
457 exec printf('norm %dGzt', msg['start'])
458 " TODO: try to fit the message on screen
461 if !a:can_change_thread
464 call <SID>NM_kill_this_buffer()
467 call <SID>NM_search_show_thread(everything)
469 call <SID>NM_show_previous(0, a:find_matching)
471 echo 'No more messages.'
475 function! s:NM_show_next(can_change_thread, find_matching)
476 let info = b:nm_raw_info
478 for msg in info['msgs']
479 if a:find_matching && msg['match'] == '0'
482 if lnum >= msg['start']
486 exec printf('norm %dGzt', msg['start'])
487 " TODO: try to fit the message on screen
490 if a:can_change_thread
491 call <SID>NM_show_next_thread()
495 function! s:NM_show_next_thread()
496 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
497 call <SID>NM_kill_this_buffer()
498 if line('.') != line('$')
500 call <SID>NM_search_show_thread(everything)
502 echo 'No more messages.'
506 function! s:NM_show_mark_read_thread()
507 call <SID>NM_tag(b:nm_search_words, ['-unread'])
508 call <SID>NM_show_next_thread()
511 function! s:NM_show_archive_thread()
512 call <SID>NM_tag(b:nm_search_words, ['-inbox'])
513 call <SID>NM_show_next_thread()
516 function! s:NM_show_mark_read_then_archive_thread()
517 call <SID>NM_tag(b:nm_search_words, ['-unread', '-inbox'])
518 call <SID>NM_show_next_thread()
521 function! s:NM_show_mark_read_then_next_open_message()
522 echo 'not implemented'
525 function! s:NM_show_previous_message()
526 echo 'not implemented'
529 function! s:NM_show_reply()
531 call add(cmd, <SID>NM_show_message_id())
533 call extend(cmd, <SID>NM_get_search_words())
535 let data = <SID>NM_run(cmd)
536 let lines = split(data, "\n")
537 call <SID>NM_newComposeBuffer(lines, 0)
540 function! s:NM_show_view_all_mime_parts()
541 echo 'not implemented'
544 function! s:NM_show_view_raw_message()
545 echo 'not implemented'
548 function! s:NM_show_add_tag()
549 echo 'not implemented'
552 function! s:NM_show_remove_tag()
553 echo 'not implemented'
556 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
557 " otherwise go to next message
558 " any message that is viewed entirely has inbox and unread tags removed
559 function! s:NM_show_advance_marking_read_and_archiving()
560 let advance_tags = ['unread', 'inbox']
562 let vis_top = line('w0')
563 let vis_bot = line('w$')
565 let msg_top = <SID>NM_show_get_message_for_line(vis_top)
566 if !has_key(msg_top,'id')
567 throw "No top visible message."
570 " if the top message is the last message, just expunge the entire thread and move on
571 if msg_top['end'] == line('$')
573 for msg in b:nm_raw_info['msgs']
574 if has_key(msg,'match') && msg['match'] != '0'
575 call add(ids, msg['id'])
578 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
580 \ + <SID>NM_combine_tags('', ids, 'OR', '()')
581 call map(advance_tags, '"+" . v:val')
582 call <SID>NM_tag(filter, advance_tags)
583 call <SID>NM_show_next(1, 1)
587 let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
588 if !has_key(msg_bot,'id')
589 throw "No bottom visible message."
592 " if entire message fits on the screen, read/archive it, move to the next one
593 if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
594 exec printf('norm %dG', vis_top)
595 call <SID>NM_show_next(0, 1)
596 if has_key(msg_top,'match') && msg_top['match'] != '0'
598 " do this last to hide the latency
599 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
600 \ + ['AND', msg_top['id']]
601 call map(advance_tags, '"-" . v:val')
602 call <SID>NM_tag(filter, advance_tags)
607 " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
608 let jmp = winheight(winnr()) / 2
609 let max = msg_bot['end'] - vis_bot
613 exec printf('norm %dGzt', vis_top + jmp)
617 function! s:NM_show_pipe_message()
618 echo 'not implemented'
621 function! s:NM_show_previous_fold()
622 echo 'not implemented'
625 function! s:NM_show_next_fold()
626 echo 'not implemented'
629 function! s:NM_show_toggle_fold()
630 echo 'not implemented'
634 " --- --- show screen helper functions {{{2
636 function! s:NM_show_get_message_for_line(line)
637 for msg in b:nm_raw_info['msgs']
638 if a:line > msg['end']
646 function! s:NM_show_message_id()
647 if !exists('b:nm_raw_info')
648 throw 'Eeek! no b:nm_raw_info'
650 let msg = <SID>NM_show_get_message_for_line(line('.'))
657 function! s:NM_show_fold_toggle(key, type, fold)
658 let info = b:nm_raw_info
663 for fld in info['folds']
668 "let msg = info['msgs'][idx]
669 "if has_key(msg,'match') && msg['match'] == '0'
672 let cls = foldclosed(fld[1])
673 if cls != -1 && cls != fld[1]
676 exec printf('%dfold%s', fld[1], act)
678 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
682 " s:NM_cmd_show_parse returns the following dictionary:
683 " 'disp': lines to display
684 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
685 " 'folds': fold info arrays [ type, start, end ]
686 " 'foldtext': fold text indexed by start line
687 function! s:NM_cmd_show_parse(inlines)
688 let info = { 'disp': [],
707 for line in a:inlines
708 let inlnum = inlnum + 1
714 if match(line, g:notmuch_show_part_end_regexp) != -1
715 let part_end = len(info['disp'])
717 call add(info['disp'], line)
720 if in_part == 'text/plain'
721 if !part_end && mode_type == ''
722 if match(line, g:notmuch_show_signature_regexp) != -1
723 let mode_type = 'sig'
724 let mode_start = len(info['disp'])
725 elseif match(line, g:notmuch_show_citation_regexp) != -1
726 let mode_type = 'cit'
727 let mode_start = len(info['disp'])
729 elseif mode_type == 'cit'
730 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
731 let outlnum = len(info['disp'])
732 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
733 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
736 elseif mode_type == 'sig'
737 let outlnum = len(info['disp'])
738 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
741 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
742 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
749 " FIXME: this is a hack for handling two folds being added for one line
750 " we should handle addinga fold in a function
751 if len(foldinfo) && foldinfo[1] < foldinfo[2]
752 call add(info['folds'], foldinfo[0:3])
753 let info['foldtext'][foldinfo[1]] = foldinfo[4]
756 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
757 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
759 call add(info['disp'], '')
763 if !has_key(msg,'body_start')
764 let msg['body_start'] = len(info['disp']) + 1
766 if match(line, g:notmuch_show_body_end_regexp) != -1
767 let body_end = len(info['disp'])
768 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
769 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
773 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
774 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
775 let in_part = 'unknown'
779 call add(info['disp'],
780 \ printf('--- %s ---', in_part))
781 let part_start = len(info['disp']) + 1
786 let msg['descr'] = line
787 call add(info['disp'], line)
789 let msg['hdr_start'] = len(info['disp']) + 1
792 if match(line, g:notmuch_show_header_end_regexp) != -1
793 let hdr_start = msg['hdr_start']+1
794 let hdr_end = len(info['disp'])
795 let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
796 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
797 let msg['header'] = hdr
801 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
804 if match(g:notmuch_show_headers, m[1]) != -1
805 call add(info['disp'], line)
812 if match(line, g:notmuch_show_message_end_regexp) != -1
813 let msg['end'] = len(info['disp'])
814 call add(info['disp'], '')
816 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
817 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
819 call add(info['msgs'], msg)
826 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
830 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
831 let body_start = len(info['disp']) + 1
837 if match(line, g:notmuch_show_message_begin_regexp) != -1
838 let msg['start'] = len(info['disp']) + 1
840 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
843 let msg['depth'] = m[2]
844 let msg['match'] = m[3]
845 let msg['filename'] = m[4]
852 if len(foldinfo) && foldinfo[1] < foldinfo[2]
853 call add(info['folds'], foldinfo[0:3])
854 let info['foldtext'][foldinfo[1]] = foldinfo[4]
860 function! s:NM_cmd_show_mkfolds()
861 let info = b:nm_raw_info
863 for afold in info['folds']
864 exec printf('%d,%dfold', afold[1], afold[2])
866 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
867 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
868 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
869 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
871 elseif afold[0] == 'msg'
873 let msg = info['msgs'][idx]
874 if has_key(msg,'match') && msg['match'] == '0'
878 exec printf('%dfold%s', afold[1], state)
882 function! s:NM_cmd_show_mksyntax()
883 let info = b:nm_raw_info
885 for msg in info['msgs']
887 let start = msg['start']
888 let hdr_start = msg['hdr_start']
889 let body_start = msg['body_start']
891 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
892 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
893 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
897 function! NM_cmd_show_foldtext()
898 let foldtext = b:nm_raw_info['foldtext']
899 return foldtext[v:foldstart]
903 " --- implement compose screen {{{1
905 function! s:NM_cmd_compose(words, body_lines)
907 let start_on_line = 0
911 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
913 throw 'Eeek! bad parameter ''' . string(word) . ''''
915 let key = substitute(m[1], '\<\w', '\U&', 'g')
916 if !has_key(hdrs, key)
920 call add(hdrs[key], m[2])
924 if !has_key(hdrs, 'From') || !len(hdrs['From'])
925 let me = <SID>NM_compose_get_user_email()
926 let hdrs['From'] = [ me ]
929 for key in g:notmuch_compose_headers
930 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
931 call add(lines, key . ': ' . text)
932 if !start_on_line && !strlen(text)
933 let start_on_line = len(lines)
937 for [key,val] in items(hdrs)
938 if match(g:notmuch_compose_headers, key) == -1
939 let line = key . ': ' . join(val, ', ')
940 call add(lines, line)
946 let start_on_line = len(lines) + 1
950 call extend(lines, a:body_lines)
952 call extend(lines, [ '', '' ])
955 call <SID>NM_newComposeBuffer(lines, start_on_line)
958 function! s:NM_compose_send()
959 call <SID>NM_assert_buffer_type('compose')
960 let fname = expand('%')
962 let line = getline(lnum)
964 while match(line, '^$') == -1
965 if !exists("hdr_starts") && match(line, '^Notmuch-Help:') == -1
966 let hdr_starts = lnum - 1
969 let line = getline(lnum)
971 let body_starts = lnum - 1
973 call append(body_starts, 'Date: ' . strftime('%a, %d %b %Y %H:%M:%S %z'))
974 exec printf(':0,%dd', hdr_starts)
977 let line = getline(1)
978 let m = matchlist(line, '^From:\s*\(.*\)\s*<\(.*\)>$')
982 let m = matchlist(line, '^From:\s*\(.*\)$')
986 let cmdtxt = g:notmuch_sendmail . ' -t -f ' . from . ' < ' . fname
987 let out = system(cmdtxt)
988 let err = v:shell_error
992 call <SID>NM_newBuffer('new', 'error',
993 \ "While running...\n" .
994 \ ' ' . cmdtxt . "\n" .
996 \ "Failed with...\n" .
997 \ substitute(out, '^', ' ', 'g'))
999 echo 'Eeek! unable to send mail'
1004 if !exists('b:nm_prev_bufnr')
1007 let prev_bufnr = b:nm_prev_bufnr
1009 if prev_bufnr == bufnr('%')
1010 exec printf("buffer %d", prev_bufnr)
1014 echo 'Mail sent successfully.'
1017 function! s:NM_compose_attach()
1018 echo 'not implemented'
1021 function! s:NM_compose_next_entry_area()
1022 let lnum = line('.')
1023 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1026 let line = getline(lnum)
1027 if match(line, '^\([^:]\+\):\s*$') == -1
1028 call cursor(lnum, strlen(line) + 1)
1031 while match(getline(lnum+1), '^\s') != -1
1034 call cursor(lnum, strlen(getline(lnum)) + 1)
1037 elseif lnum == hdr_end
1038 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1042 if !getbufvar(bufnr('.'), '&et')
1046 let shiftwidth = a:shiftwidth
1047 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1048 " we assume no one has shiftwidth set to more than 40 :)
1049 return ' '[0:shiftwidth]
1053 " --- --- compose screen helper functions {{{2
1055 function! s:NM_compose_get_user_email()
1056 " TODO: do this properly (still), i.e., allow for multiple email accounts
1057 let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1061 function! s:NM_compose_find_line_match(start, pattern, failure)
1063 let lend = line('$')
1065 if match(getline(lnum), a:pattern) != -1
1074 " --- notmuch helper functions {{{1
1076 function! s:NM_newBuffer(how, type, content)
1082 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1083 silent put=a:content
1085 setlocal nomodifiable
1086 execute printf('set filetype=notmuch-%s', a:type)
1087 execute printf('set syntax=notmuch-%s', a:type)
1088 let b:nm_type = a:type
1091 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1092 let fdir = expand(a:fdir)
1093 if !isdirectory(fdir)
1094 call mkdir(fdir, 'p')
1096 let file_name = <SID>NM_mktemp(fdir, a:fname)
1097 if writefile(a:lines, file_name)
1098 throw 'Eeek! couldn''t write to temporary file ' . file_name
1100 exec printf('edit %s', file_name)
1101 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1102 execute printf('set filetype=notmuch-%s', a:type)
1103 execute printf('set syntax=notmuch-%s', a:type)
1104 let b:nm_type = a:type
1107 function! s:NM_newComposeBuffer(lines, start_on_line)
1109 let start_on_line = a:start_on_line
1110 let real_hdr_start = 1
1111 if g:notmuch_compose_header_help
1113 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1114 \ 'Notmuch-Help: ,a - attach a file',
1115 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
1116 \ 'Notmuch-Help: ,q - abort the message',
1117 \ 'Notmuch-Help: <Tab> - skip through header lines',
1119 call extend(lines, help_lines, 0)
1120 let real_hdr_start = len(help_lines)
1121 if start_on_line > 0
1122 let start_on_line = start_on_line + len(help_lines)
1125 call extend(lines, g:notmuch_signature)
1128 let prev_bufnr = bufnr('%')
1129 setlocal bufhidden=hide
1130 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1132 setlocal bufhidden=hide
1133 let b:nm_prev_bufnr = prev_bufnr
1135 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1136 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1138 if start_on_line > 0 && start_on_line <= len(lines)
1139 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1141 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1142 call <SID>NM_compose_next_entry_area()
1145 if g:notmuch_compose_insert_mode_start
1148 echo 'Type your message, use <TAB> to jump to next header and then body.'
1151 function! s:NM_assert_buffer_type(type)
1152 if !exists('b:nm_type') || b:nm_type != a:type
1153 throw printf('Eeek! expected type %s, but got %s.', a:type,
1154 \ exists(b:nm_type) ? b:nm_type : 'something else')
1158 function! s:NM_mktemp(dir, name)
1159 let time_stamp = strftime('%Y%m%d-%H%M%S')
1160 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1161 " TODO: check if it exists, try again
1165 function! s:NM_shell_escape(word)
1166 " TODO: use shellescape()
1167 let word = substitute(a:word, '''', '\\''', 'g')
1168 return '''' . word . ''''
1171 " this function was taken from git.vim, then fixed up
1172 " http://github.com/motemen/git-vim
1173 function! s:NM_shell_split(cmd)
1174 let l:split_cmd = []
1178 let t = match(cmd, '\S', iStart)
1184 let iSpace = match(cmd, '\v(\s|$)', iStart)
1189 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1190 if iQuote1 > iSpace || iQuote1 < iStart
1191 let iEnd = iSpace - 1
1192 let l:split_cmd += [ cmd[iStart : iEnd] ]
1194 let q = cmd[iQuote1]
1195 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1196 if iQuote2 < iQuote1
1197 throw 'No matching ' . q . ' quote'
1200 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1204 let iStart = iEnd + 1
1211 function! s:NM_run(args)
1213 call map(words, 's:NM_shell_escape(v:val)')
1214 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1216 if exists('g:notmuch_debug') && g:notmuch_debug
1217 let start = reltime()
1218 let out = system(cmd)
1219 let err = v:shell_error
1220 let delta = reltime(start)
1222 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1224 let out = system(cmd)
1225 let err = v:shell_error
1230 echo substitute(out, '\n*$', '', '')
1238 " --- external mail handling helpers {{{1
1240 function! s:NM_new_mail()
1241 call <SID>NM_cmd_compose([], [])
1244 " --- tag manipulation helpers {{{1
1246 " used to combine an array of words with prefixes and separators
1248 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1249 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1250 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1253 if len(res) && strlen(a:separator)
1254 call add(res, a:separator)
1256 call add(res, a:word_prefix . word)
1258 if len(res) > 1 && strlen(a:brackets)
1259 if strlen(a:brackets) != 2
1260 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1262 call insert(res, a:brackets[0])
1263 call add(res, a:brackets[1])
1268 " --- other helpers {{{1
1270 function! s:NM_get_search_words()
1271 if !exists('b:nm_search_words')
1272 throw 'Eeek! no b:nm_search_words'
1274 return b:nm_search_words
1277 function! s:NM_kill_this_buffer()
1278 if exists('b:nm_prev_bufnr')
1279 let prev_bufnr = b:nm_prev_bufnr
1281 exec printf("buffer %d", prev_bufnr)
1283 echo "This is the last buffer; use :q<CR> to quit."
1287 function! s:NM_search_expand(arg)
1288 let word = expand(a:arg)
1289 let prev_bufnr = bufnr('%')
1290 setlocal bufhidden=hide
1291 call <SID>NM_cmd_search([word])
1292 setlocal bufhidden=delete
1293 let b:nm_prev_bufnr = prev_bufnr
1296 function! s:NM_tag(filter, tags)
1297 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1299 throw 'Eeek! I couldn''t find the thead id!'
1302 call extend(args, a:tags)
1303 call add(args, '--')
1304 call extend(args, filter)
1305 " TODO: handle errors
1306 call <SID>NM_run(args)
1309 " --- process and set the defaults {{{1
1311 function! NM_set_defaults(force)
1312 for [key, dflt] in items(s:notmuch_defaults)
1314 if !a:force && exists(key) && type(dflt) == type(eval(key))
1316 elseif type(dflt) == type(0)
1317 let cmd = printf('let %s = %d', key, dflt)
1318 elseif type(dflt) == type('')
1319 let cmd = printf('let %s = ''%s''', key, dflt)
1320 " FIXME: not sure why this didn't work when dflt is an array
1321 "elseif type(dflt) == type([])
1322 " let cmd = printf('let %s = %s', key, string(dflt))
1324 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1325 \ a:force, key, string(dflt))
1331 call NM_set_defaults(0)
1333 " for some reason NM_set_defaults() didn't work for arrays...
1334 if !exists('g:notmuch_show_headers')
1335 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1337 if !exists('g:notmuch_initial_search_words')
1338 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1340 if !exists('g:notmuch_folders')
1341 let g:notmuch_folders = s:notmuch_folders_defaults
1344 if !exists('g:notmuch_signature')
1345 let g:notmuch_signature = s:notmuch_signature_defaults
1347 if !exists('g:notmuch_compose_headers')
1348 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1351 " --- assign keymaps {{{1
1353 function! s:NM_set_map(type, maps)
1355 for [key, code] in items(a:maps)
1356 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1358 " --- this is a hack for development :)
1359 nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1362 " --- command handler {{{1
1364 function! NotMuch(args)
1367 let args = 'folders'
1370 let words = <SID>NM_shell_split(args)
1371 if words[0] == 'folders' || words[0] == 'f'
1372 let words = words[1:]
1373 call <SID>NM_cmd_folders(words)
1375 elseif words[0] == 'search' || words[0] == 's'
1377 let words = words[1:]
1378 elseif exists('b:nm_search_words')
1379 let words = b:nm_search_words
1381 let words = g:notmuch_initial_search_words
1383 call <SID>NM_cmd_search(words)
1385 elseif words[0] == 'show'
1386 echoe 'show is not yet implemented.'
1388 elseif words[0] == 'new' || words[0] == 'compose'
1389 let words = words[1:]
1390 call <SID>NM_cmd_compose(words, [])
1393 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1400 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1401 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1403 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :