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 \ 'D': ':call <SID>NM_search_delete_thread()<CR>',
127 \ 'f': ':call <SID>NM_search_filter()<CR>',
128 \ 'm': ':call <SID>NM_new_mail()<CR>',
129 \ 'o': ':call <SID>NM_search_toggle_order()<CR>',
130 \ 'r': ':call <SID>NM_search_reply_to_thread()<CR>',
131 \ 's': ':call <SID>NM_search_prompt()<CR>',
132 \ ',s': ':call <SID>NM_search_edit()<CR>',
133 \ 't': ':call <SID>NM_search_filter_by_tag()<CR>',
134 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
135 \ '+': ':call <SID>NM_search_add_tags([])<CR>',
136 \ '-': ':call <SID>NM_search_remove_tags([])<CR>',
137 \ '=': ':call <SID>NM_search_refresh_view()<CR>',
138 \ '?': ':echo <SID>NM_search_thread_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
141 " --- --- bindings for show screen {{{2
142 let g:notmuch_show_maps = {
143 \ '<C-P>': ':call <SID>NM_show_previous(1, 0)<CR>',
144 \ '<C-N>': ':call <SID>NM_show_next(1, 0)<CR>',
145 \ '<C-]>': ':call <SID>NM_search_expand(''<cword>'')<CR>',
146 \ 'q': ':call <SID>NM_kill_this_buffer()<CR>',
147 \ 's': ':call <SID>NM_search_prompt()<CR>',
149 \ 'b': ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
150 \ 'c': ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
151 \ 'h': ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
152 \ 'i': ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
154 \ 'I': ':call <SID>NM_show_mark_read_thread()<CR>',
155 \ 'a': ':call <SID>NM_show_archive_thread()<CR>',
156 \ 'A': ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
157 \ 'N': ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
158 \ 'v': ':call <SID>NM_show_view_all_mime_parts()<CR>',
159 \ '+': ':call <SID>NM_show_add_tag()<CR>',
160 \ '-': ':call <SID>NM_show_remove_tag()<CR>',
161 \ '<Space>': ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
162 \ '\|': ':call <SID>NM_show_pipe_message()<CR>',
164 \ '<S-Tab>': ':call <SID>NM_show_previous_fold()<CR>',
165 \ '<Tab>': ':call <SID>NM_show_next_fold()<CR>',
166 \ '<Enter>': ':call <SID>NM_show_toggle_fold()<CR>',
168 \ 'r': ':call <SID>NM_show_reply()<CR>',
169 \ 'm': ':call <SID>NM_new_mail()<CR>',
170 \ '?': ':echo <SID>NM_show_message_id() . '' @ '' . join(<SID>NM_get_search_words())<CR>',
173 " --- --- bindings for compose screen {{{2
174 let g:notmuch_compose_nmaps = {
175 \ ',s': ':call <SID>NM_compose_send()<CR>',
176 \ ',a': ':call <SID>NM_compose_attach()<CR>',
177 \ ',q': ':call <SID>NM_kill_this_buffer()<CR>',
178 \ '<Tab>': ':call <SID>NM_compose_next_entry_area()<CR>',
180 let g:notmuch_compose_imaps = {
181 \ '<Tab>': '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
184 " --- implement folders screen {{{1
186 function! s:NM_cmd_folders(words)
188 throw 'Not expecting any arguments for folders command.'
193 for entry in g:notmuch_folders
194 let [ name, search ] = entry
195 let data = s:NM_run(cmd + [search])
196 let cnt = matchlist(data, '\(\d\+\)')[1]
197 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
198 call add(searches, search)
201 call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
202 let b:nm_searches = searches
203 let b:nm_timestamp = reltime()
205 call <SID>NM_cmd_folders_mksyntax()
206 call <SID>NM_set_map('n', g:notmuch_folders_maps)
211 function! s:NM_cmd_folders_mksyntax()
214 " --- --- folders screen action functions {{{2
216 function! s:NM_folders_refresh_view()
218 setlocal bufhidden=delete
219 call s:NM_cmd_folders([])
220 exec printf('norm %dG', lno)
223 function! s:NM_folders_show_search()
225 let search = b:nm_searches[line-1]
227 let prev_bufnr = bufnr('%')
228 setlocal bufhidden=hide
229 call <SID>NM_cmd_search([search])
230 setlocal bufhidden=delete
231 let b:nm_prev_bufnr = prev_bufnr
235 " --- implement search screen {{{1
237 function! s:NM_cmd_search(words)
239 if g:notmuch_search_newest_first
240 let cmd = cmd + ['--sort=newest-first']
242 let cmd = cmd + ['--sort=oldest-first']
244 let data = s:NM_run(cmd + a:words)
245 let lines = split(data, "\n")
246 let disp = copy(lines)
247 call map(disp, 's:NM_cmd_search_fmtline(v:val)')
249 call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
250 let b:nm_raw_lines = lines
251 let b:nm_search_words = a:words
253 call <SID>NM_set_map('n', g:notmuch_search_maps)
257 function! s:NM_cmd_search_fmtline(line)
258 let m = matchlist(a:line, '^\(thread:\S\+\)\s\(.\{12\}\) \[\(\d\+\)/\d\+\] \([^;]\+\); \%(\[[^\[]\+\] \)*\(.*\) (\([^(]*\))$')
260 return 'ERROR PARSING: ' . a:line
262 let max = g:notmuch_search_from_column_width
264 for at in split(m[4], ", ")
265 let p = min([stridx(at, "."), stridx(at, "@")])
266 call insert(flist, tolower(at[0:p - 1]))
268 let from = join(flist, ", ")
269 return printf("%-12s %3s %-20.20s | %s (%s)", m[2], m[3], from, m[5], m[6])
272 " --- --- search screen action functions {{{2
274 function! s:NM_search_show_thread(everything)
275 let words = [ <SID>NM_search_thread_id() ]
276 if !a:everything && exists('b:nm_search_words')
277 call extend(words, ['AND', '('])
278 call extend(words, b:nm_search_words)
281 call <SID>NM_cmd_show(words)
282 let b:nm_show_everything = a:everything
285 function! s:NM_search_prompt()
286 " TODO: input() can support completion
287 let text = input('NotMuch Search: ')
289 let tags = split(text)
291 let tags = s:notmuch_initial_search_words_defaults
293 let prev_bufnr = bufnr('%')
294 if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
295 " TODO: we intend to replace the current buffer,
296 " ... maybe we could just clear it
297 let prev_bufnr = b:nm_prev_bufnr
298 setlocal bufhidden=delete
300 setlocal bufhidden=hide
302 call <SID>NM_cmd_search(tags)
303 setlocal bufhidden=delete
304 let b:nm_prev_bufnr = prev_bufnr
307 function! s:NM_search_edit()
308 " TODO: input() can support completion
309 let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
311 call <SID>NM_cmd_search(split(text))
315 function! s:NM_search_mark_read_thread()
316 call <SID>NM_tag([], ['-unread'])
320 function! s:NM_search_archive_thread()
321 call <SID>NM_tag([], ['-inbox'])
325 function! s:NM_search_mark_read_then_archive_thread()
326 call <SID>NM_tag([], ['-unread', '-inbox'])
330 function! s:NM_search_delete_thread()
331 call <SID>NM_tag([], ['+delete','-inbox','-unread'])
335 function! s:NM_search_filter()
336 call <SID>NM_search_filter_helper('Filter: ', '', '')
339 function! s:NM_search_filter_by_tag()
340 call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
343 function! s:NM_search_filter_helper(prompt, prefix, joiner)
344 " TODO: input() can support completion
345 let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
350 let tags = b:nm_search_words + ['AND']
351 \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
353 let prev_bufnr = bufnr('%')
354 setlocal bufhidden=hide
355 call <SID>NM_cmd_search(tags)
356 setlocal bufhidden=delete
357 let b:nm_prev_bufnr = prev_bufnr
360 function! s:NM_search_toggle_order()
361 let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
362 " FIXME: maybe this would be better done w/o reading re-reading the lines
363 " reversing the b:nm_raw_lines and the buffer lines would be better
364 call <SID>NM_search_refresh_view()
367 function! s:NM_search_reply_to_thread()
369 call add(cmd, <SID>NM_search_thread_id())
371 call extend(cmd, <SID>NM_get_search_words())
373 let data = <SID>NM_run(cmd)
374 let lines = split(data, "\n")
375 call <SID>NM_newComposeBuffer(lines, 0)
378 function! s:NM_search_add_tags(tags)
379 call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
382 function! s:NM_search_remove_tags(tags)
383 call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
386 function! s:NM_search_refresh_view()
388 let prev_bufnr = b:nm_prev_bufnr
389 setlocal bufhidden=delete
390 call <SID>NM_cmd_search(b:nm_search_words)
391 let b:nm_prev_bufnr = prev_bufnr
392 " FIXME: should find the line of the thread we were on if possible
393 exec printf('norm %dG', lno)
396 " --- --- search screen helper functions {{{2
398 function! s:NM_search_thread_id()
399 if !exists('b:nm_raw_lines')
400 throw 'Eeek! no b:nm_raw_lines'
402 let mnum = line('.') - 1
403 if len(b:nm_raw_lines) <= mnum
406 let info = b:nm_raw_lines[mnum]
407 let what = split(info, '\s\+')[0]
411 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
412 if type(a:intags) != type([]) || len(a:intags) == 0
413 " TODO: input() can support completion
414 let text = input(a:prompt)
418 let tags = split(text, ' ')
422 call map(tags, 'a:prefix . v:val')
423 call <SID>NM_tag([], tags)
426 " --- implement show screen {{{1
428 function! s:NM_cmd_show(words)
429 let prev_bufnr = bufnr('%')
430 let data = s:NM_run(['show', '--entire-thread'] + a:words)
431 let lines = split(data, "\n")
433 let info = s:NM_cmd_show_parse(lines)
435 setlocal bufhidden=hide
436 call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
437 setlocal bufhidden=delete
438 let b:nm_search_words = a:words
439 let b:nm_raw_info = info
440 let b:nm_prev_bufnr = prev_bufnr
442 call <SID>NM_cmd_show_mkfolds()
443 call <SID>NM_cmd_show_mksyntax()
444 call <SID>NM_set_map('n', g:notmuch_show_maps)
445 setlocal foldtext=NM_cmd_show_foldtext()
447 setlocal foldcolumn=6
451 function! s:NM_show_previous(can_change_thread, find_matching)
452 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
453 let info = b:nm_raw_info
455 for msg in reverse(copy(info['msgs']))
456 if a:find_matching && msg['match'] == '0'
459 if lnum <= msg['start']
463 exec printf('norm %dGzt', msg['start'])
464 " TODO: try to fit the message on screen
467 if !a:can_change_thread
470 call <SID>NM_kill_this_buffer()
473 call <SID>NM_search_show_thread(everything)
475 call <SID>NM_show_previous(0, a:find_matching)
477 echo 'No more messages.'
481 function! s:NM_show_next(can_change_thread, find_matching)
482 let info = b:nm_raw_info
484 for msg in info['msgs']
485 if a:find_matching && msg['match'] == '0'
488 if lnum >= msg['start']
492 exec printf('norm %dGzt', msg['start'])
493 " TODO: try to fit the message on screen
496 if a:can_change_thread
497 call <SID>NM_show_next_thread()
501 function! s:NM_show_next_thread()
502 let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
503 call <SID>NM_kill_this_buffer()
504 if line('.') != line('$')
506 call <SID>NM_search_show_thread(everything)
508 echo 'No more messages.'
512 function! s:NM_show_mark_read_thread()
513 call <SID>NM_tag(b:nm_search_words, ['-unread'])
514 call <SID>NM_show_next_thread()
517 function! s:NM_show_archive_thread()
518 call <SID>NM_tag(b:nm_search_words, ['-inbox'])
519 call <SID>NM_show_next_thread()
522 function! s:NM_show_mark_read_then_archive_thread()
523 call <SID>NM_tag(b:nm_search_words, ['-unread', '-inbox'])
524 call <SID>NM_show_next_thread()
527 function! s:NM_show_mark_read_then_next_open_message()
528 echo 'not implemented'
531 function! s:NM_show_previous_message()
532 echo 'not implemented'
535 function! s:NM_show_reply()
537 call add(cmd, <SID>NM_show_message_id())
539 call extend(cmd, <SID>NM_get_search_words())
541 let data = <SID>NM_run(cmd)
542 let lines = split(data, "\n")
543 call <SID>NM_newComposeBuffer(lines, 0)
546 function! s:NM_show_view_all_mime_parts()
547 echo 'not implemented'
550 function! s:NM_show_view_raw_message()
551 echo 'not implemented'
554 function! s:NM_show_add_tag()
555 echo 'not implemented'
558 function! s:NM_show_remove_tag()
559 echo 'not implemented'
562 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
563 " otherwise go to next message
564 " any message that is viewed entirely has inbox and unread tags removed
565 function! s:NM_show_advance_marking_read_and_archiving()
566 let advance_tags = ['unread', 'inbox']
568 let vis_top = line('w0')
569 let vis_bot = line('w$')
571 let msg_top = <SID>NM_show_get_message_for_line(vis_top)
572 if !has_key(msg_top,'id')
573 throw "No top visible message."
576 " if the top message is the last message, just expunge the entire thread and move on
577 if msg_top['end'] == line('$')
579 for msg in b:nm_raw_info['msgs']
580 if has_key(msg,'match') && msg['match'] != '0'
581 call add(ids, msg['id'])
584 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
586 \ + <SID>NM_combine_tags('', ids, 'OR', '()')
587 call map(advance_tags, '"+" . v:val')
588 call <SID>NM_tag(filter, advance_tags)
589 call <SID>NM_show_next(1, 1)
593 let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
594 if !has_key(msg_bot,'id')
595 throw "No bottom visible message."
598 " if entire message fits on the screen, read/archive it, move to the next one
599 if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
600 exec printf('norm %dG', vis_top)
601 call <SID>NM_show_next(0, 1)
602 if has_key(msg_top,'match') && msg_top['match'] != '0'
604 " do this last to hide the latency
605 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
606 \ + ['AND', msg_top['id']]
607 call map(advance_tags, '"-" . v:val')
608 call <SID>NM_tag(filter, advance_tags)
613 " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
614 let jmp = winheight(winnr()) / 2
615 let max = msg_bot['end'] - vis_bot
619 exec printf('norm %dGzt', vis_top + jmp)
623 function! s:NM_show_pipe_message()
624 echo 'not implemented'
627 function! s:NM_show_previous_fold()
628 echo 'not implemented'
631 function! s:NM_show_next_fold()
632 echo 'not implemented'
635 function! s:NM_show_toggle_fold()
636 echo 'not implemented'
640 " --- --- show screen helper functions {{{2
642 function! s:NM_show_get_message_for_line(line)
643 for msg in b:nm_raw_info['msgs']
644 if a:line > msg['end']
652 function! s:NM_show_message_id()
653 if !exists('b:nm_raw_info')
654 throw 'Eeek! no b:nm_raw_info'
656 let msg = <SID>NM_show_get_message_for_line(line('.'))
663 function! s:NM_show_fold_toggle(key, type, fold)
664 let info = b:nm_raw_info
669 for fld in info['folds']
674 "let msg = info['msgs'][idx]
675 "if has_key(msg,'match') && msg['match'] == '0'
678 let cls = foldclosed(fld[1])
679 if cls != -1 && cls != fld[1]
682 exec printf('%dfold%s', fld[1], act)
684 exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
688 " s:NM_cmd_show_parse returns the following dictionary:
689 " 'disp': lines to display
690 " 'msgs': message info dicts { start, end, id, depth, filename, descr, header }
691 " 'folds': fold info arrays [ type, start, end ]
692 " 'foldtext': fold text indexed by start line
693 function! s:NM_cmd_show_parse(inlines)
694 let info = { 'disp': [],
713 for line in a:inlines
714 let inlnum = inlnum + 1
720 if match(line, g:notmuch_show_part_end_regexp) != -1
721 let part_end = len(info['disp'])
723 call add(info['disp'], line)
726 if in_part == 'text/plain'
727 if !part_end && mode_type == ''
728 if match(line, g:notmuch_show_signature_regexp) != -1
729 let mode_type = 'sig'
730 let mode_start = len(info['disp'])
731 elseif match(line, g:notmuch_show_citation_regexp) != -1
732 let mode_type = 'cit'
733 let mode_start = len(info['disp'])
735 elseif mode_type == 'cit'
736 if part_end || match(line, g:notmuch_show_citation_regexp) == -1
737 let outlnum = len(info['disp'])
738 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
739 \ printf('[ %d-line citation. Press "c" to show. ]', outlnum - mode_start) ]
742 elseif mode_type == 'sig'
743 let outlnum = len(info['disp'])
744 if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
747 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
748 \ printf('[ %d-line signature. Press "s" to show. ]', outlnum - mode_start) ]
755 " FIXME: this is a hack for handling two folds being added for one line
756 " we should handle addinga fold in a function
757 if len(foldinfo) && foldinfo[1] < foldinfo[2]
758 call add(info['folds'], foldinfo[0:3])
759 let info['foldtext'][foldinfo[1]] = foldinfo[4]
762 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
763 \ printf('[ %d-line %s. Press "p" to show. ]', part_end - part_start, in_part) ]
765 call add(info['disp'], '')
769 if !has_key(msg,'body_start')
770 let msg['body_start'] = len(info['disp']) + 1
772 if match(line, g:notmuch_show_body_end_regexp) != -1
773 let body_end = len(info['disp'])
774 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
775 \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
779 elseif match(line, g:notmuch_show_part_begin_regexp) != -1
780 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
781 let in_part = 'unknown'
785 call add(info['disp'],
786 \ printf('--- %s ---', in_part))
787 let part_start = len(info['disp']) + 1
792 let msg['descr'] = line
793 call add(info['disp'], line)
795 let msg['hdr_start'] = len(info['disp']) + 1
798 if match(line, g:notmuch_show_header_end_regexp) != -1
799 let hdr_start = msg['hdr_start']+1
800 let hdr_end = len(info['disp'])
801 let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
802 \ printf('[ %d-line headers. Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
803 let msg['header'] = hdr
807 let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
810 if match(g:notmuch_show_headers, m[1]) != -1
811 call add(info['disp'], line)
818 if match(line, g:notmuch_show_message_end_regexp) != -1
819 let msg['end'] = len(info['disp'])
820 call add(info['disp'], '')
822 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
823 \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
825 call add(info['msgs'], msg)
832 elseif match(line, g:notmuch_show_header_begin_regexp) != -1
836 elseif match(line, g:notmuch_show_body_begin_regexp) != -1
837 let body_start = len(info['disp']) + 1
843 if match(line, g:notmuch_show_message_begin_regexp) != -1
844 let msg['start'] = len(info['disp']) + 1
846 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
849 let msg['depth'] = m[2]
850 let msg['match'] = m[3]
851 let msg['filename'] = m[4]
858 if len(foldinfo) && foldinfo[1] < foldinfo[2]
859 call add(info['folds'], foldinfo[0:3])
860 let info['foldtext'][foldinfo[1]] = foldinfo[4]
866 function! s:NM_cmd_show_mkfolds()
867 let info = b:nm_raw_info
869 for afold in info['folds']
870 exec printf('%d,%dfold', afold[1], afold[2])
872 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
873 \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
874 \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
875 \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
877 elseif afold[0] == 'msg'
879 let msg = info['msgs'][idx]
880 if has_key(msg,'match') && msg['match'] == '0'
884 exec printf('%dfold%s', afold[1], state)
888 function! s:NM_cmd_show_mksyntax()
889 let info = b:nm_raw_info
891 for msg in info['msgs']
893 let start = msg['start']
894 let hdr_start = msg['hdr_start']
895 let body_start = msg['body_start']
897 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
898 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
899 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
903 function! NM_cmd_show_foldtext()
904 let foldtext = b:nm_raw_info['foldtext']
905 return foldtext[v:foldstart]
909 " --- implement compose screen {{{1
911 function! s:NM_cmd_compose(words, body_lines)
913 let start_on_line = 0
917 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
919 throw 'Eeek! bad parameter ''' . string(word) . ''''
921 let key = substitute(m[1], '\<\w', '\U&', 'g')
922 if !has_key(hdrs, key)
926 call add(hdrs[key], m[2])
930 if !has_key(hdrs, 'From') || !len(hdrs['From'])
931 let me = <SID>NM_compose_get_user_email()
932 let hdrs['From'] = [ me ]
935 for key in g:notmuch_compose_headers
936 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
937 call add(lines, key . ': ' . text)
938 if !start_on_line && !strlen(text)
939 let start_on_line = len(lines)
943 for [key,val] in items(hdrs)
944 if match(g:notmuch_compose_headers, key) == -1
945 let line = key . ': ' . join(val, ', ')
946 call add(lines, line)
952 let start_on_line = len(lines) + 1
956 call extend(lines, a:body_lines)
958 call extend(lines, [ '', '' ])
961 call <SID>NM_newComposeBuffer(lines, start_on_line)
964 function! s:NM_compose_send()
965 call <SID>NM_assert_buffer_type('compose')
966 let fname = expand('%')
968 let line = getline(lnum)
970 while match(line, '^$') == -1
971 if !exists("hdr_starts") && match(line, '^Notmuch-Help:') == -1
972 let hdr_starts = lnum - 1
975 let line = getline(lnum)
977 let body_starts = lnum - 1
979 call append(body_starts, 'Date: ' . strftime('%a, %d %b %Y %H:%M:%S %z'))
980 exec printf(':0,%dd', hdr_starts)
983 let line = getline(1)
984 let m = matchlist(line, '^From:\s*\(.*\)\s*<\(.*\)>$')
988 let m = matchlist(line, '^From:\s*\(.*\)$')
992 let cmdtxt = g:notmuch_sendmail . ' -t -f ' . from . ' < ' . fname
993 let out = system(cmdtxt)
994 let err = v:shell_error
998 call <SID>NM_newBuffer('new', 'error',
999 \ "While running...\n" .
1000 \ ' ' . cmdtxt . "\n" .
1002 \ "Failed with...\n" .
1003 \ substitute(out, '^', ' ', 'g'))
1005 echo 'Eeek! unable to send mail'
1010 if !exists('b:nm_prev_bufnr')
1013 let prev_bufnr = b:nm_prev_bufnr
1015 if prev_bufnr == bufnr('%')
1016 exec printf("buffer %d", prev_bufnr)
1020 echo 'Mail sent successfully.'
1023 function! s:NM_compose_attach()
1024 echo 'not implemented'
1027 function! s:NM_compose_next_entry_area()
1028 let lnum = line('.')
1029 let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1032 let line = getline(lnum)
1033 if match(line, '^\([^:]\+\):\s*$') == -1
1034 call cursor(lnum, strlen(line) + 1)
1037 while match(getline(lnum+1), '^\s') != -1
1040 call cursor(lnum, strlen(getline(lnum)) + 1)
1043 elseif lnum == hdr_end
1044 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1048 if !getbufvar(bufnr('.'), '&et')
1052 let shiftwidth = a:shiftwidth
1053 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1054 " we assume no one has shiftwidth set to more than 40 :)
1055 return ' '[0:shiftwidth]
1059 " --- --- compose screen helper functions {{{2
1061 function! s:NM_compose_get_user_email()
1062 " TODO: do this properly (still), i.e., allow for multiple email accounts
1063 let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1067 function! s:NM_compose_find_line_match(start, pattern, failure)
1069 let lend = line('$')
1071 if match(getline(lnum), a:pattern) != -1
1080 " --- notmuch helper functions {{{1
1082 function! s:NM_newBuffer(how, type, content)
1088 setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1089 silent put=a:content
1091 setlocal nomodifiable
1092 execute printf('set filetype=notmuch-%s', a:type)
1093 execute printf('set syntax=notmuch-%s', a:type)
1094 let b:nm_type = a:type
1097 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1098 let fdir = expand(a:fdir)
1099 if !isdirectory(fdir)
1100 call mkdir(fdir, 'p')
1102 let file_name = <SID>NM_mktemp(fdir, a:fname)
1103 if writefile(a:lines, file_name)
1104 throw 'Eeek! couldn''t write to temporary file ' . file_name
1106 exec printf('edit %s', file_name)
1107 setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
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_newComposeBuffer(lines, start_on_line)
1115 let start_on_line = a:start_on_line
1116 let real_hdr_start = 1
1117 if g:notmuch_compose_header_help
1119 \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1120 \ 'Notmuch-Help: ,a - attach a file',
1121 \ 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
1122 \ 'Notmuch-Help: ,q - abort the message',
1123 \ 'Notmuch-Help: <Tab> - skip through header lines',
1125 call extend(lines, help_lines, 0)
1126 let real_hdr_start = len(help_lines)
1127 if start_on_line > 0
1128 let start_on_line = start_on_line + len(help_lines)
1131 call extend(lines, g:notmuch_signature)
1134 let prev_bufnr = bufnr('%')
1135 setlocal bufhidden=hide
1136 call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1138 setlocal bufhidden=hide
1139 let b:nm_prev_bufnr = prev_bufnr
1141 call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1142 call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1144 if start_on_line > 0 && start_on_line <= len(lines)
1145 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1147 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1148 call <SID>NM_compose_next_entry_area()
1151 if g:notmuch_compose_insert_mode_start
1154 echo 'Type your message, use <TAB> to jump to next header and then body.'
1157 function! s:NM_assert_buffer_type(type)
1158 if !exists('b:nm_type') || b:nm_type != a:type
1159 throw printf('Eeek! expected type %s, but got %s.', a:type,
1160 \ exists(b:nm_type) ? b:nm_type : 'something else')
1164 function! s:NM_mktemp(dir, name)
1165 let time_stamp = strftime('%Y%m%d-%H%M%S')
1166 let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1167 " TODO: check if it exists, try again
1171 function! s:NM_shell_escape(word)
1172 " TODO: use shellescape()
1173 let word = substitute(a:word, '''', '\\''', 'g')
1174 return '''' . word . ''''
1177 " this function was taken from git.vim, then fixed up
1178 " http://github.com/motemen/git-vim
1179 function! s:NM_shell_split(cmd)
1180 let l:split_cmd = []
1184 let t = match(cmd, '\S', iStart)
1190 let iSpace = match(cmd, '\v(\s|$)', iStart)
1195 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1196 if iQuote1 > iSpace || iQuote1 < iStart
1197 let iEnd = iSpace - 1
1198 let l:split_cmd += [ cmd[iStart : iEnd] ]
1200 let q = cmd[iQuote1]
1201 let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1202 if iQuote2 < iQuote1
1203 throw 'No matching ' . q . ' quote'
1206 let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1210 let iStart = iEnd + 1
1217 function! s:NM_run(args)
1219 call map(words, 's:NM_shell_escape(v:val)')
1220 let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1222 if exists('g:notmuch_debug') && g:notmuch_debug
1223 let start = reltime()
1224 let out = system(cmd)
1225 let err = v:shell_error
1226 let delta = reltime(start)
1228 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1230 let out = system(cmd)
1231 let err = v:shell_error
1236 echo substitute(out, '\n*$', '', '')
1244 " --- external mail handling helpers {{{1
1246 function! s:NM_new_mail()
1247 call <SID>NM_cmd_compose([], [])
1250 " --- tag manipulation helpers {{{1
1252 " used to combine an array of words with prefixes and separators
1254 " NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1255 " -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1256 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1259 if len(res) && strlen(a:separator)
1260 call add(res, a:separator)
1262 call add(res, a:word_prefix . word)
1264 if len(res) > 1 && strlen(a:brackets)
1265 if strlen(a:brackets) != 2
1266 throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1268 call insert(res, a:brackets[0])
1269 call add(res, a:brackets[1])
1274 " --- other helpers {{{1
1276 function! s:NM_get_search_words()
1277 if !exists('b:nm_search_words')
1278 throw 'Eeek! no b:nm_search_words'
1280 return b:nm_search_words
1283 function! s:NM_kill_this_buffer()
1284 if exists('b:nm_prev_bufnr')
1285 let prev_bufnr = b:nm_prev_bufnr
1287 exec printf("buffer %d", prev_bufnr)
1289 echo "This is the last buffer; use :q<CR> to quit."
1293 function! s:NM_search_expand(arg)
1294 let word = expand(a:arg)
1295 let prev_bufnr = bufnr('%')
1296 setlocal bufhidden=hide
1297 call <SID>NM_cmd_search([word])
1298 setlocal bufhidden=delete
1299 let b:nm_prev_bufnr = prev_bufnr
1302 function! s:NM_tag(filter, tags)
1303 let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1305 throw 'Eeek! I couldn''t find the thead id!'
1308 call extend(args, a:tags)
1309 call add(args, '--')
1310 call extend(args, filter)
1311 " TODO: handle errors
1312 call <SID>NM_run(args)
1315 " --- process and set the defaults {{{1
1317 function! NM_set_defaults(force)
1318 for [key, dflt] in items(s:notmuch_defaults)
1320 if !a:force && exists(key) && type(dflt) == type(eval(key))
1322 elseif type(dflt) == type(0)
1323 let cmd = printf('let %s = %d', key, dflt)
1324 elseif type(dflt) == type('')
1325 let cmd = printf('let %s = ''%s''', key, dflt)
1326 " FIXME: not sure why this didn't work when dflt is an array
1327 "elseif type(dflt) == type([])
1328 " let cmd = printf('let %s = %s', key, string(dflt))
1330 echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1331 \ a:force, key, string(dflt))
1337 call NM_set_defaults(0)
1339 " for some reason NM_set_defaults() didn't work for arrays...
1340 if !exists('g:notmuch_show_headers')
1341 let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1343 if !exists('g:notmuch_initial_search_words')
1344 let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1346 if !exists('g:notmuch_folders')
1347 let g:notmuch_folders = s:notmuch_folders_defaults
1350 if !exists('g:notmuch_signature')
1351 let g:notmuch_signature = s:notmuch_signature_defaults
1353 if !exists('g:notmuch_compose_headers')
1354 let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1357 " --- assign keymaps {{{1
1359 function! s:NM_set_map(type, maps)
1361 for [key, code] in items(a:maps)
1362 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1364 " --- this is a hack for development :)
1365 nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1368 " --- command handler {{{1
1370 function! NotMuch(args)
1373 let args = 'folders'
1376 let words = <SID>NM_shell_split(args)
1377 if words[0] == 'folders' || words[0] == 'f'
1378 let words = words[1:]
1379 call <SID>NM_cmd_folders(words)
1381 elseif words[0] == 'search' || words[0] == 's'
1383 let words = words[1:]
1384 elseif exists('b:nm_search_words')
1385 let words = b:nm_search_words
1387 let words = g:notmuch_initial_search_words
1389 call <SID>NM_cmd_search(words)
1391 elseif words[0] == 'show'
1392 echoe 'show is not yet implemented.'
1394 elseif words[0] == 'new' || words[0] == 'compose'
1395 let words = words[1:]
1396 call <SID>NM_cmd_compose(words, [])
1399 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1406 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1407 cabbrev notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1409 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :