1 if exists("g:loaded_notmuch_rb")
5 if !has("ruby") || version < 700
9 let g:loaded_notmuch_rb = "yep"
11 let g:notmuch_rb_folders_maps = {
12 \ '<Enter>': 'folders_show_search()',
13 \ 's': 'folders_search_prompt()',
14 \ '=': 'folders_refresh()',
18 let g:notmuch_rb_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_rb_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_rb_compose_maps = {
47 \ ',s': 'compose_send()',
48 \ ',q': 'compose_quit()',
51 let s:notmuch_rb_folders_default = [
52 \ [ 'new', 'tag:inbox and tag:unread' ],
53 \ [ 'inbox', 'tag:inbox' ],
54 \ [ 'unread', 'tag:unread' ],
57 let s:notmuch_rb_date_format_default = '%d.%m.%y'
58 let s:notmuch_rb_datetime_format_default = '%d.%m.%y %H:%M:%S'
59 let s:notmuch_rb_reader_default = 'mutt -f %s'
60 let s:notmuch_rb_sendmail_default = 'sendmail'
61 let s:notmuch_rb_folders_count_threads_default = 0
63 if !exists('g:notmuch_rb_date_format')
64 let g:notmuch_rb_date_format = s:notmuch_rb_date_format_default
67 if !exists('g:notmuch_rb_datetime_format')
68 let g:notmuch_rb_datetime_format = s:notmuch_rb_datetime_format_default
71 if !exists('g:notmuch_rb_reader')
72 let g:notmuch_rb_reader = s:notmuch_rb_reader_default
75 if !exists('g:notmuch_rb_sendmail')
76 let g:notmuch_rb_sendmail = s:notmuch_rb_sendmail_default
79 if !exists('g:notmuch_rb_folders_count_threads')
80 let g:notmuch_rb_folders_count_threads = s:notmuch_rb_folders_count_threads_default
83 function! s:new_file_buffer(type, fname)
84 exec printf('edit %s', a:fname)
85 execute printf('set filetype=notmuch-%s', a:type)
86 execute printf('set syntax=notmuch-%s', a:type)
87 ruby $curbuf.init(VIM::evaluate('a:type'))
88 ruby $buf_queue.push($curbuf.number)
91 function! s:compose_unload()
95 if input('[s]end/[q]uit? ') =~ '^s'
102 function! s:compose_quit()
103 let b:compose_done = 1
104 call s:kill_this_buffer()
107 function! s:compose_send()
108 let b:compose_done = 1
109 let fname = expand('%')
115 let cmdtxt = g:notmuch_sendmail . ' -t -f ' . s:reply_from . ' < ' . fname
116 let out = system(cmdtxt)
117 let err = v:shell_error
122 echo 'Eeek! unable to send mail'
128 echo 'Mail sent successfully.'
129 call s:kill_this_buffer()
132 function! s:show_next_msg()
134 r, c = $curwin.cursor
135 n = $curbuf.line_number
136 i = $messages.index { |m| n >= m.start && n <= m.end }
140 VIM::command("normal #{m.start}zt")
141 $curwin.cursor = r, c
146 function! s:show_reply()
147 ruby open_reply get_message.mail
148 let b:compose_done = 0
149 call s:set_map(g:notmuch_rb_compose_maps)
150 autocmd BufUnload <buffer> call s:compose_unload()
154 function! s:compose()
156 let b:compose_done = 0
157 call s:set_map(g:notmuch_rb_compose_maps)
158 autocmd BufUnload <buffer> call s:compose_unload()
162 function! s:show_info()
163 ruby vim_puts get_message.inspect
166 function! s:show_extract_msg()
169 m.mail.attachments.each do |a|
170 File.open(a.filename, 'w') do |f|
171 f.write a.body.decoded
172 print "Extracted '#{a.filename}'"
178 function! s:show_open_msg()
181 mbox = File.expand_path('~/.notmuch/vim_mbox')
182 cmd = VIM::evaluate('g:notmuch_rb_reader') % mbox
183 system "notmuch show --format=mbox id:#{m.message_id} > #{mbox} && #{cmd}"
187 function! s:show_save_msg()
188 let file = input('File name: ')
190 file = VIM::evaluate('file')
192 system "notmuch show --format=mbox id:#{m.message_id} > #{file}"
196 function! s:show_save_patches()
198 q = $curbuf.query($cur_thread)
199 t = q.search_threads.first
201 t.toplevel_messages.first.replies.each do |m|
202 next if not m['subject'] =~ /^\[PATCH.*\]/
203 file = "%04d.patch" % [n += 1]
204 system "notmuch show --format=mbox id:#{m.message_id} > #{file}"
206 vim_puts "Saved #{n} patches"
210 function! s:show_tag(intags)
212 let tags = input('tags: ')
216 ruby do_tag(get_cur_view, VIM::evaluate('l:tags'))
217 call s:show_next_thread()
220 function! s:search_search_prompt()
221 let text = input('Search: ')
227 $cur_search = VIM::evaluate('text')
229 search_render($cur_search)
231 setlocal nomodifiable
234 function! s:search_info()
235 ruby vim_puts get_thread_id
238 function! s:search_refresh()
241 ruby search_render($cur_search)
242 setlocal nomodifiable
245 function! s:search_tag(intags)
247 let tags = input('tags: ')
251 ruby do_tag(get_thread_id, VIM::evaluate('l:tags'))
255 function! s:folders_search_prompt()
256 let text = input('Search: ')
260 function! s:folders_refresh()
263 ruby folders_render()
264 setlocal nomodifiable
269 function! s:show_cursor_moved()
272 VIM::command('setlocal modifiable')
274 VIM::command('setlocal nomodifiable')
279 function! s:show_next_thread()
280 call s:kill_this_buffer()
281 if line('.') != line('$')
283 call s:search_show_thread(0)
285 echo 'No more messages.'
289 function! s:kill_this_buffer()
291 if $buf_queue.size > 1
293 VIM::command("bdelete!")
296 VIM::command("buffer #{b}") if b
301 function! s:set_map(maps)
303 for [key, code] in items(a:maps)
304 let cmd = printf(":call <SID>%s<CR>", code)
305 exec printf('nnoremap <buffer> %s %s', key, cmd)
309 function! s:new_buffer(type)
311 setlocal buftype=nofile bufhidden=hide
313 execute printf('set filetype=notmuch-%s', a:type)
314 execute printf('set syntax=notmuch-%s', a:type)
315 ruby $curbuf.init(VIM::evaluate('a:type'))
316 ruby $buf_queue.push($curbuf.number)
319 function! s:set_menu_buffer()
320 setlocal nomodifiable
327 function! s:show(thread_id)
328 call s:new_buffer('show')
331 thread_id = VIM::evaluate('a:thread_id')
332 $cur_thread = thread_id
334 $curbuf.render do |b|
335 q = $curbuf.query(get_cur_view)
336 q.sort = Notmuch::SORT_OLDEST_FIRST
337 msgs = q.search_messages
339 m = Mail.read(msg.filename)
340 part = m.find_first_text
341 nm_m = Message.new(msg, m)
343 date_fmt = VIM::evaluate('g:notmuch_rb_datetime_format')
344 date = Time.at(msg.date).strftime(date_fmt)
346 b << "%s %s (%s)" % [msg['from'], date, msg.tags]
347 b << "Subject: %s" % [msg['subject']]
348 b << "To: %s" % msg['to']
349 b << "Cc: %s" % msg['cc']
350 b << "Date: %s" % msg['date']
351 nm_m.body_start = b.count
352 b << "--- %s ---" % part.mime_type
353 part.convert.each_line do |l|
361 $messages.each_with_index do |msg, i|
362 VIM::command("syntax region nmShowMsg#{i}Desc start='\\%%%il' end='\\%%%il' contains=@nmShowMsgDesc" % [msg.start, msg.start + 1])
363 VIM::command("syntax region nmShowMsg#{i}Head start='\\%%%il' end='\\%%%il' contains=@nmShowMsgHead" % [msg.start + 1, msg.body_start])
364 VIM::command("syntax region nmShowMsg#{i}Body start='\\%%%il' end='\\%%%dl' contains=@nmShowMsgBody" % [msg.body_start, msg.end])
367 setlocal nomodifiable
368 call s:set_map(g:notmuch_rb_show_maps)
371 function! s:search_show_thread(mode)
373 mode = VIM::evaluate('a:mode')
377 when 1; $cur_filter = nil
378 when 2; $cur_filter = $cur_search
380 VIM::command("call s:show('#{id}')")
384 function! s:search(search)
385 call s:new_buffer('search')
387 $cur_search = VIM::evaluate('a:search')
388 search_render($cur_search)
390 call s:set_menu_buffer()
391 call s:set_map(g:notmuch_rb_search_maps)
392 autocmd CursorMoved <buffer> call s:show_cursor_moved()
395 function! s:folders_show_search()
397 n = $curbuf.line_number
399 VIM::command("call s:search('#{s}')")
403 function! s:folders()
404 call s:new_buffer('folders')
405 ruby folders_render()
406 call s:set_menu_buffer()
407 call s:set_map(g:notmuch_rb_folders_maps)
412 function! s:set_defaults()
413 if exists('g:notmuch_rb_custom_search_maps')
414 call extend(g:notmuch_rb_search_maps, g:notmuch_rb_custom_search_maps)
417 if exists('g:notmuch_rb_custom_show_maps')
418 call extend(g:notmuch_rb_show_maps, g:notmuch_rb_custom_show_maps)
421 " TODO for now lets check the old folders too
422 if !exists('g:notmuch_rb_folders')
423 if exists('g:notmuch_folders')
424 let g:notmuch_rb_folders = g:notmuch_folders
426 let g:notmuch_rb_folders = s:notmuch_rb_folders_default
431 function! s:NotMuch(...)
432 call s:set_defaults()
445 $email = $email_name = $email_address = nil
451 $mail_installed = defined?(Mail)
455 config = ENV['NOTMUCH_CONFIG'] || '~/.notmuch-config'
456 File.open(File.expand_path(config)).each do |l|
463 key = "%s.%s" % [group, $1]
469 $db_name = $config['database.path']
470 $email_name = $config['user.name']
471 $email_address = $config['user.primary_email']
472 $email = "%s <%s>" % [$email_name, $email_address]
476 VIM::command("echo '#{s.to_s}'")
480 VIM::command("echo '#{s.inspect}'")
484 # TODO email format, aliases
486 a.gsub!(/[\.@].*/, '')
488 a.gsub!(/ \(.*\)/, '')
493 n = $curbuf.line_number - 1
494 return "thread:%s" % $threads[n]
498 n = $curbuf.line_number
499 return $messages.find { |m| n >= m.start && n <= m.end }
504 return "#{$cur_thread} and (#{$cur_filter})"
510 def generate_message_id
512 random_tag = sprintf('%x%x_%x%x%x',
514 $$, Thread.current.object_id.abs, rand(255))
515 return "<#{random_tag}@#{Socket.gethostname}.notmuch>"
518 def open_compose_helper(lines, cur)
520 'Notmuch-Help: Type in your message here; to help you use these bindings:',
521 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
522 'Notmuch-Help: ,q - abort the message',
525 dir = File.expand_path('~/.notmuch/compose')
526 FileUtils.mkdir_p(dir)
527 Tempfile.open(['nm-', '.mail'], dir) do |f|
532 sig_file = File.expand_path('~/.signature')
533 if File.exists?(sig_file)
535 f.write(File.read(sig_file))
540 cur += help_lines.size + 1
542 VIM::command("let s:reply_from='%s'" % $email_address)
543 VIM::command("call s:new_file_buffer('compose', '#{f.path}')")
544 VIM::command("call cursor(#{cur}, 0)")
549 reply = orig.reply do |m|
552 m.to = [orig[:from].to_s, orig[:to].to_s]
556 m.message_id = generate_message_id
558 m.content_transfer_encoding = '7bit'
565 addr = Mail::Address.new(orig[:from].value)
567 name = addr.local + "@" if name.nil? && !addr.local.nil?
571 name = "somebody" if name.nil?
573 body_lines << "%s wrote:" % name
574 part = orig.find_first_text
575 part.convert.each_line do |l|
576 body_lines << "> %s" % l.chomp
582 reply.body = body_lines.join("\n")
584 lines += reply.to_s.lines.map { |e| e.chomp }
587 cur = lines.count - 1
589 open_compose_helper(lines, cur)
595 lines << "Date: #{Time.now().strftime('%a, %-d %b %Y %T %z')}"
596 lines << "From: #{$email}"
602 lines << "Message-Id: #{generate_message_id}"
604 lines << "Mime-Version: 1.0"
605 lines << "Content-Type: text/plain; charset=utf-8"
606 lines << "Content-Transfer-Encoding: 7bit"
611 open_compose_helper(lines, cur)
615 $curbuf.render do |b|
616 folders = VIM::evaluate('g:notmuch_rb_folders')
617 count_threads = VIM::evaluate('g:notmuch_rb_folders_count_threads')
619 folders.each do |name, search|
620 q = $curbuf.query(search)
622 count = count_threads ? q.search_threads.count : q.search_messages.count
623 b << "%9d %-20s (%s)" % [count, name, search]
628 def search_render(search)
629 date_fmt = VIM::evaluate('g:notmuch_rb_date_format')
630 q = $curbuf.query(search)
631 q.sort = Notmuch::SORT_NEWEST_FIRST
635 $render = $curbuf.render_staged(t) do |b, items|
637 authors = e.authors.to_utf8.split(/[,|]/).map { |a| author_filter(a) }.join(",")
638 date = Time.at(e.newest_date).strftime(date_fmt)
639 subject = e.messages.first['subject']
641 subject = Mail::Field.new("Subject: " + subject).to_s
643 subject = subject.force_encoding('utf-8')
645 b << "%-12s %3s %-20.20s | %s (%s)" % [date, e.matched_messages, authors, subject, e.tags]
646 $threads << e.thread_id
651 def do_tag(filter, tags)
652 $curbuf.do_write do |db|
654 q.search_messages.each do |e|
656 tags.split.each do |t|
667 e.tags_to_maildir_flags
676 @db = Notmuch::Database.new($db_name)
687 @queries.delete_if { |q| ! q.destroy! }
693 @db = Notmuch::Database.new($db_name)
697 db = Notmuch::Database.new($db_name, :mode => Notmuch::MODE_READ_WRITE)
707 attr_accessor :start, :body_start, :end
708 attr_reader :message_id, :filename, :mail
710 def initialize(msg, mail)
711 @message_id = msg.message_id
712 @filename = msg.filename
716 mail.import_headers(msg) if not $mail_installed
720 "id:%s" % @message_id
724 "id:%s, file:%s" % [@message_id, @filename]
729 def initialize(buffer, enumerable, block)
731 @enumerable = enumerable
735 @b.render { do_next }
739 @last_render - @b.line_number <= $curwin.height
743 items = @enumerable.take($curwin.height * 2)
744 return if items.empty?
745 @block.call @b, items
746 @last_render = @b.count
757 def render_staged(enumerable, &block)
758 StagedRender.new(self, enumerable, block)
764 (1..old_count).each do
776 class Notmuch::Message
782 # workaround for bug in vim's ruby
790 def self.parse(string)
791 return nil if string.empty?
792 return Header.new(string.split(/,\s+/))
800 def initialize(string = nil)
807 if string =~ /(.*?(\r\n|\n))\2/m
808 head, body = $1, $' || '', $2
810 head, body = string, ''
816 @headers[name.to_sym]
820 @headers[name.to_sym] = value
823 def format_header(value)
824 value.to_s.tr('_', '-').gsub(/(\w+)/) { $1.capitalize }
829 @headers.each do |key, value|
830 buffer << "%s: %s\r\n" %
831 [format_header(key), value]
859 r = Mail::Message.new
863 r[:in_reply_to] = self[:message_id]
864 r[:references] = self[:references]
868 HEADERS = [ :from, :to, :cc, :references, :in_reply_to, :reply_to, :message_id ]
870 def import_headers(m)
872 dashed = format_header(e)
873 @headers[e] = Header.parse(m[dashed])
880 if not $mail_installed
881 puts "WARNING: Install the 'mail' gem, without it support is limited"
883 def self.read(filename)
884 Message.new(File.open(filename, 'rb') { |f| f.read })
888 include SimpleMessage
895 return self if not multipart?
896 return text_part || html_part
900 if mime_type != "text/html"
903 IO.popen("elinks --dump", "w+") do |pipe|
904 pipe.write(decode_body)
916 RUBY_VERSION >= "1.9" ? force_encoding('utf-8') : self
923 call s:search(join(a:000))
929 command -nargs=* NotMuch call s:NotMuch(<f-args>)
931 " vim: set noexpandtab: