1 if exists("g:loaded_notmuch")
5 if !has("ruby") || version < 700
9 let g:loaded_notmuch = "yep"
11 let g:notmuch_folders_maps = {
12 \ '<Enter>': 'folders_show_search()',
13 \ 's': 'folders_search_prompt()',
14 \ '=': 'folders_refresh()',
18 let g:notmuch_search_maps = {
19 \ 'q': 'kill_this_buffer()',
20 \ '<Enter>': 'search_show_thread(1)',
21 \ '<Space>': 'search_show_thread(2)',
22 \ 'A': 'search_tag("-inbox -unread")',
23 \ 'I': 'search_tag("-unread")',
24 \ 't': 'search_tag("")',
25 \ 's': 'search_search_prompt()',
26 \ '=': 'search_refresh()',
27 \ '?': 'search_info()',
31 let g:notmuch_show_maps = {
32 \ 'q': 'kill_this_buffer()',
33 \ 'A': 'show_tag("-inbox -unread")',
34 \ 'I': 'show_tag("-unread")',
35 \ 't': 'show_tag("")',
36 \ 'o': 'show_open_msg()',
37 \ 'e': 'show_extract_msg()',
38 \ 's': 'show_save_msg()',
39 \ 'p': 'show_save_patches()',
40 \ 'r': 'show_reply()',
42 \ '<Tab>': 'show_next_msg()',
46 let g:notmuch_compose_maps = {
47 \ ',s': 'compose_send()',
48 \ ',q': 'compose_quit()',
51 let s:notmuch_folders_default = [
52 \ [ 'new', 'tag:inbox and tag:unread' ],
53 \ [ 'inbox', 'tag:inbox' ],
54 \ [ 'unread', 'tag:unread' ],
57 let s:notmuch_date_format_default = '%d.%m.%y'
58 let s:notmuch_datetime_format_default = '%d.%m.%y %H:%M:%S'
59 let s:notmuch_reader_default = 'mutt -f %s'
60 let s:notmuch_sendmail_default = 'sendmail'
61 let s:notmuch_folders_count_threads_default = 0
63 function! s:new_file_buffer(type, fname)
64 exec printf('edit %s', a:fname)
65 execute printf('set filetype=notmuch-%s', a:type)
66 execute printf('set syntax=notmuch-%s', a:type)
67 ruby $curbuf.init(VIM::evaluate('a:type'))
70 function! s:on_compose_delete()
74 if input('[s]end/[q]uit? ') =~ '^s'
81 function! s:compose_quit()
82 let b:compose_done = 1
83 call s:kill_this_buffer()
86 function! s:compose_send()
87 let b:compose_done = 1
88 let fname = expand('%')
94 let cmdtxt = g:notmuch_sendmail . ' -t -f ' . s:reply_from . ' < ' . fname
95 let out = system(cmdtxt)
96 let err = v:shell_error
101 echo 'Eeek! unable to send mail'
107 echo 'Mail sent successfully.'
108 call s:kill_this_buffer()
111 function! s:show_next_msg()
113 r, c = $curwin.cursor
114 n = $curbuf.line_number
115 i = $messages.index { |m| n >= m.start && n <= m.end }
119 VIM::command("normal #{m.start}zt")
120 $curwin.cursor = r, c
125 function! s:show_reply()
126 ruby open_reply get_message.mail
127 let b:compose_done = 0
128 call s:set_map(g:notmuch_compose_maps)
129 autocmd BufDelete <buffer> call s:on_compose_delete()
133 function! s:compose()
135 let b:compose_done = 0
136 call s:set_map(g:notmuch_compose_maps)
137 autocmd BufDelete <buffer> call s:on_compose_delete()
141 function! s:show_info()
142 ruby vim_puts get_message.inspect
145 function! s:show_extract_msg()
148 m.mail.attachments.each do |a|
149 File.open(a.filename, 'w') do |f|
150 f.write a.body.decoded
151 print "Extracted '#{a.filename}'"
157 function! s:show_open_msg()
160 mbox = File.expand_path('~/.notmuch/vim_mbox')
161 cmd = VIM::evaluate('g:notmuch_reader') % mbox
162 system "notmuch show --format=mbox id:#{m.message_id} > #{mbox} && #{cmd}"
166 function! s:show_save_msg()
167 let file = input('File name: ')
169 file = VIM::evaluate('file')
171 system "notmuch show --format=mbox id:#{m.message_id} > #{file}"
175 function! s:show_save_patches()
177 q = $curbuf.query($cur_thread)
178 t = q.search_threads.first
180 t.toplevel_messages.first.replies.each do |m|
181 next if not m['subject'] =~ /^\[PATCH.*\]/
182 file = "%04d.patch" % [n += 1]
183 system "notmuch show --format=mbox id:#{m.message_id} > #{file}"
185 vim_puts "Saved #{n} patches"
189 function! s:show_tag(intags)
191 let tags = input('tags: ')
195 ruby do_tag(get_cur_view, VIM::evaluate('l:tags'))
196 call s:show_next_thread()
199 function! s:search_search_prompt()
200 let text = input('Search: ')
206 $cur_search = VIM::evaluate('text')
208 search_render($cur_search)
210 setlocal nomodifiable
213 function! s:search_info()
214 ruby vim_puts get_thread_id
217 function! s:search_refresh()
220 ruby search_render($cur_search)
221 setlocal nomodifiable
224 function! s:search_tag(intags)
226 let tags = input('tags: ')
230 ruby do_tag(get_thread_id, VIM::evaluate('l:tags'))
234 function! s:folders_search_prompt()
235 let text = input('Search: ')
239 function! s:folders_refresh()
242 ruby folders_render()
243 setlocal nomodifiable
248 function! s:show_cursor_moved()
251 VIM::command('setlocal modifiable')
253 VIM::command('setlocal nomodifiable')
258 function! s:show_next_thread()
259 call s:kill_this_buffer()
260 if line('.') != line('$')
262 call s:search_show_thread(0)
264 echo 'No more messages.'
268 function! s:kill_this_buffer()
271 VIM::command("bdelete!")
275 function! s:set_map(maps)
277 for [key, code] in items(a:maps)
278 let cmd = printf(":call <SID>%s<CR>", code)
279 exec printf('nnoremap <buffer> %s %s', key, cmd)
283 function! s:new_buffer(type)
285 setlocal buftype=nofile bufhidden=hide
287 execute printf('set filetype=notmuch-%s', a:type)
288 execute printf('set syntax=notmuch-%s', a:type)
289 ruby $curbuf.init(VIM::evaluate('a:type'))
292 function! s:set_menu_buffer()
293 setlocal nomodifiable
300 function! s:show(thread_id)
301 call s:new_buffer('show')
304 thread_id = VIM::evaluate('a:thread_id')
305 $cur_thread = thread_id
307 $curbuf.render do |b|
308 q = $curbuf.query(get_cur_view)
309 q.sort = Notmuch::SORT_OLDEST_FIRST
310 msgs = q.search_messages
312 m = Mail.read(msg.filename)
313 part = m.find_first_text
314 nm_m = Message.new(msg, m)
316 date_fmt = VIM::evaluate('g:notmuch_datetime_format')
317 date = Time.at(msg.date).strftime(date_fmt)
319 b << "%s %s (%s)" % [msg['from'], date, msg.tags]
320 b << "Subject: %s" % [msg['subject']]
321 b << "To: %s" % msg['to']
322 b << "Cc: %s" % msg['cc']
323 b << "Date: %s" % msg['date']
324 nm_m.body_start = b.count
325 b << "--- %s ---" % part.mime_type
326 part.convert.each_line do |l|
334 $messages.each_with_index do |msg, i|
335 VIM::command("syntax region nmShowMsg#{i}Desc start='\\%%%il' end='\\%%%il' contains=@nmShowMsgDesc" % [msg.start, msg.start + 1])
336 VIM::command("syntax region nmShowMsg#{i}Head start='\\%%%il' end='\\%%%il' contains=@nmShowMsgHead" % [msg.start + 1, msg.body_start])
337 VIM::command("syntax region nmShowMsg#{i}Body start='\\%%%il' end='\\%%%dl' contains=@nmShowMsgBody" % [msg.body_start, msg.end])
340 setlocal nomodifiable
341 call s:set_map(g:notmuch_show_maps)
344 function! s:search_show_thread(mode)
346 mode = VIM::evaluate('a:mode')
350 when 1; $cur_filter = nil
351 when 2; $cur_filter = $cur_search
353 VIM::command("call s:show('#{id}')")
357 function! s:search(search)
358 call s:new_buffer('search')
360 $cur_search = VIM::evaluate('a:search')
361 search_render($cur_search)
363 call s:set_menu_buffer()
364 call s:set_map(g:notmuch_search_maps)
365 autocmd CursorMoved <buffer> call s:show_cursor_moved()
368 function! s:folders_show_search()
370 n = $curbuf.line_number
372 VIM::command("call s:search('#{s}')")
376 function! s:folders()
377 call s:new_buffer('folders')
378 ruby folders_render()
379 call s:set_menu_buffer()
380 call s:set_map(g:notmuch_folders_maps)
385 function! s:set_defaults()
386 if !exists('g:notmuch_date_format')
387 if exists('g:notmuch_rb_date_format')
388 let g:notmuch_date_format = g:notmuch_rb_date_format
390 let g:notmuch_date_format = s:notmuch_date_format_default
394 if !exists('g:notmuch_datetime_format')
395 if exists('g:notmuch_rb_datetime_format')
396 let g:notmuch_datetime_format = g:notmuch_rb_datetime_format
398 let g:notmuch_datetime_format = s:notmuch_datetime_format_default
402 if !exists('g:notmuch_reader')
403 if exists('g:notmuch_rb_reader')
404 let g:notmuch_reader = g:notmuch_rb_reader
406 let g:notmuch_reader = s:notmuch_reader_default
410 if !exists('g:notmuch_sendmail')
411 if exists('g:notmuch_rb_sendmail')
412 let g:notmuch_sendmail = g:notmuch_rb_sendmail
414 let g:notmuch_sendmail = s:notmuch_sendmail_default
418 if !exists('g:notmuch_folders_count_threads')
419 if exists('g:notmuch_rb_count_threads')
420 let g:notmuch_count_threads = g:notmuch_rb_count_threads
422 let g:notmuch_folders_count_threads = s:notmuch_folders_count_threads_default
426 if !exists('g:notmuch_custom_search_maps') && exists('g:notmuch_rb_custom_search_maps')
427 let g:notmuch_custom_search_maps = g:notmuch_rb_custom_search_maps
430 if !exists('g:notmuch_custom_show_maps') && exists('g:notmuch_rb_custom_show_maps')
431 let g:notmuch_custom_show_maps = g:notmuch_rb_custom_show_maps
434 if exists('g:notmuch_custom_search_maps')
435 call extend(g:notmuch_search_maps, g:notmuch_custom_search_maps)
438 if exists('g:notmuch_custom_show_maps')
439 call extend(g:notmuch_show_maps, g:notmuch_custom_show_maps)
442 if !exists('g:notmuch_folders')
443 if exists('g:notmuch_rb_folders')
444 let g:notmuch_folders = g:notmuch_rb_folders
446 let g:notmuch_folders = s:notmuch_folders_default
451 function! s:NotMuch(...)
452 call s:set_defaults()
465 $email = $email_name = $email_address = nil
470 $mail_installed = defined?(Mail)
474 config = ENV['NOTMUCH_CONFIG'] || '~/.notmuch-config'
475 File.open(File.expand_path(config)).each do |l|
482 key = "%s.%s" % [group, $1]
488 $db_name = $config['database.path']
489 $email_name = $config['user.name']
490 $email_address = $config['user.primary_email']
491 $email = "%s <%s>" % [$email_name, $email_address]
495 VIM::command("echo '#{s.to_s}'")
499 VIM::command("echo '#{s.inspect}'")
503 # TODO email format, aliases
505 a.gsub!(/[\.@].*/, '')
507 a.gsub!(/ \(.*\)/, '')
512 n = $curbuf.line_number - 1
513 return "thread:%s" % $threads[n]
517 n = $curbuf.line_number
518 return $messages.find { |m| n >= m.start && n <= m.end }
523 return "#{$cur_thread} and (#{$cur_filter})"
529 def generate_message_id
531 random_tag = sprintf('%x%x_%x%x%x',
533 $$, Thread.current.object_id.abs, rand(255))
534 return "<#{random_tag}@#{Socket.gethostname}.notmuch>"
537 def open_compose_helper(lines, cur)
539 'Notmuch-Help: Type in your message here; to help you use these bindings:',
540 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
541 'Notmuch-Help: ,q - abort the message',
544 dir = File.expand_path('~/.notmuch/compose')
545 FileUtils.mkdir_p(dir)
546 Tempfile.open(['nm-', '.mail'], dir) do |f|
551 sig_file = File.expand_path('~/.signature')
552 if File.exists?(sig_file)
554 f.write(File.read(sig_file))
559 cur += help_lines.size + 1
561 VIM::command("let s:reply_from='%s'" % $email_address)
562 VIM::command("call s:new_file_buffer('compose', '#{f.path}')")
563 VIM::command("call cursor(#{cur}, 0)")
568 reply = orig.reply do |m|
571 m.to = [orig[:from].to_s, orig[:to].to_s]
575 m.message_id = generate_message_id
577 m.content_transfer_encoding = '7bit'
584 addr = Mail::Address.new(orig[:from].value)
586 name = addr.local + "@" if name.nil? && !addr.local.nil?
590 name = "somebody" if name.nil?
592 body_lines << "%s wrote:" % name
593 part = orig.find_first_text
594 part.convert.each_line do |l|
595 body_lines << "> %s" % l.chomp
601 reply.body = body_lines.join("\n")
603 lines += reply.to_s.lines.map { |e| e.chomp }
606 cur = lines.count - 1
608 open_compose_helper(lines, cur)
614 lines << "Date: #{Time.now().strftime('%a, %-d %b %Y %T %z')}"
615 lines << "From: #{$email}"
621 lines << "Message-Id: #{generate_message_id}"
623 lines << "Mime-Version: 1.0"
624 lines << "Content-Type: text/plain; charset=utf-8"
625 lines << "Content-Transfer-Encoding: 7bit"
630 open_compose_helper(lines, cur)
634 $curbuf.render do |b|
635 folders = VIM::evaluate('g:notmuch_folders')
636 count_threads = VIM::evaluate('g:notmuch_folders_count_threads')
638 folders.each do |name, search|
639 q = $curbuf.query(search)
641 count = count_threads ? q.search_threads.count : q.search_messages.count
642 b << "%9d %-20s (%s)" % [count, name, search]
647 def search_render(search)
648 date_fmt = VIM::evaluate('g:notmuch_date_format')
649 q = $curbuf.query(search)
650 q.sort = Notmuch::SORT_NEWEST_FIRST
654 $render = $curbuf.render_staged(t) do |b, items|
656 authors = e.authors.to_utf8.split(/[,|]/).map { |a| author_filter(a) }.join(",")
657 date = Time.at(e.newest_date).strftime(date_fmt)
658 subject = e.messages.first['subject']
660 subject = Mail::Field.new("Subject: " + subject).to_s
662 subject = subject.force_encoding('utf-8')
664 b << "%-12s %3s %-20.20s | %s (%s)" % [date, e.matched_messages, authors, subject, e.tags]
665 $threads << e.thread_id
670 def do_tag(filter, tags)
671 $curbuf.do_write do |db|
673 q.search_messages.each do |e|
675 tags.split.each do |t|
686 e.tags_to_maildir_flags
695 @db = Notmuch::Database.new($db_name)
706 @queries.delete_if { |q| ! q.destroy! }
712 @db = Notmuch::Database.new($db_name)
716 db = Notmuch::Database.new($db_name, :mode => Notmuch::MODE_READ_WRITE)
726 attr_accessor :start, :body_start, :end
727 attr_reader :message_id, :filename, :mail
729 def initialize(msg, mail)
730 @message_id = msg.message_id
731 @filename = msg.filename
735 mail.import_headers(msg) if not $mail_installed
739 "id:%s" % @message_id
743 "id:%s, file:%s" % [@message_id, @filename]
748 def initialize(buffer, enumerable, block)
750 @enumerable = enumerable
754 @b.render { do_next }
758 @last_render - @b.line_number <= $curwin.height
762 items = @enumerable.take($curwin.height * 2)
763 return if items.empty?
764 @block.call @b, items
765 @last_render = @b.count
776 def render_staged(enumerable, &block)
777 StagedRender.new(self, enumerable, block)
783 (1..old_count).each do
795 class Notmuch::Message
801 # workaround for bug in vim's ruby
809 def self.parse(string)
810 return nil if string.empty?
811 return Header.new(string.split(/,\s+/))
819 def initialize(string = nil)
826 if string =~ /(.*?(\r\n|\n))\2/m
827 head, body = $1, $' || '', $2
829 head, body = string, ''
835 @headers[name.to_sym]
839 @headers[name.to_sym] = value
842 def format_header(value)
843 value.to_s.tr('_', '-').gsub(/(\w+)/) { $1.capitalize }
848 @headers.each do |key, value|
849 buffer << "%s: %s\r\n" %
850 [format_header(key), value]
878 r = Mail::Message.new
882 r[:in_reply_to] = self[:message_id]
883 r[:references] = self[:references]
887 HEADERS = [ :from, :to, :cc, :references, :in_reply_to, :reply_to, :message_id ]
889 def import_headers(m)
891 dashed = format_header(e)
892 @headers[e] = Header.parse(m[dashed])
899 if not $mail_installed
900 puts "WARNING: Install the 'mail' gem, without it support is limited"
902 def self.read(filename)
903 Message.new(File.open(filename, 'rb') { |f| f.read })
907 include SimpleMessage
914 return self if not multipart?
915 return text_part || html_part
919 if mime_type != "text/html"
922 IO.popen("elinks --dump", "w+") do |pipe|
923 pipe.write(decode_body)
935 RUBY_VERSION >= "1.9" ? force_encoding('utf-8') : self
942 call s:search(join(a:000))
948 command -nargs=* NotMuch call s:NotMuch(<f-args>)
950 " vim: set noexpandtab: