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()',
17 let g:notmuch_rb_search_maps = {
18 \ 'q': 'kill_this_buffer()',
19 \ '<Enter>': 'search_show_thread(1)',
20 \ '<Space>': 'search_show_thread(2)',
21 \ 'A': 'search_tag("-inbox -unread")',
22 \ 'I': 'search_tag("-unread")',
23 \ 't': 'search_tag("")',
24 \ 's': 'search_search_prompt()',
25 \ '=': 'search_refresh()',
26 \ '?': 'search_info()',
29 let g:notmuch_rb_show_maps = {
30 \ 'q': 'kill_this_buffer()',
31 \ 'A': 'show_tag("-inbox -unread")',
32 \ 'I': 'show_tag("-unread")',
33 \ 't': 'show_tag("")',
34 \ 'o': 'show_open_msg()',
35 \ 'e': 'show_extract_msg()',
36 \ 's': 'show_save_msg()',
37 \ 'p': 'show_save_patches()',
38 \ 'r': 'show_reply()',
40 \ '<Tab>': 'show_next_msg()',
43 let g:notmuch_rb_compose_maps = {
44 \ ',s': 'compose_send()',
45 \ ',q': 'compose_quit()',
48 let s:notmuch_rb_folders_default = [
49 \ [ 'new', 'tag:inbox and tag:unread' ],
50 \ [ 'inbox', 'tag:inbox' ],
51 \ [ 'unread', 'tag:unread' ],
54 let s:notmuch_rb_date_format_default = '%d.%m.%y'
55 let s:notmuch_rb_datetime_format_default = '%d.%m.%y %H:%M:%S'
56 let s:notmuch_rb_reader_default = 'mutt -f %s'
57 let s:notmuch_rb_sendmail_default = 'sendmail'
58 let s:notmuch_rb_folders_count_threads_default = 0
60 if !exists('g:notmuch_rb_date_format')
61 let g:notmuch_rb_date_format = s:notmuch_rb_date_format_default
64 if !exists('g:notmuch_rb_datetime_format')
65 let g:notmuch_rb_datetime_format = s:notmuch_rb_datetime_format_default
68 if !exists('g:notmuch_rb_reader')
69 let g:notmuch_rb_reader = s:notmuch_rb_reader_default
72 if !exists('g:notmuch_rb_sendmail')
73 let g:notmuch_rb_sendmail = s:notmuch_rb_sendmail_default
76 if !exists('g:notmuch_rb_folders_count_threads')
77 let g:notmuch_rb_folders_count_threads = s:notmuch_rb_folders_count_threads_default
80 function! s:new_file_buffer(type, fname)
81 exec printf('edit %s', a:fname)
82 execute printf('set filetype=notmuch-%s', a:type)
83 execute printf('set syntax=notmuch-%s', a:type)
84 ruby $curbuf.init(VIM::evaluate('a:type'))
85 ruby $buf_queue.push($curbuf.number)
88 function! s:compose_unload()
92 if input('[s]end/[q]uit? ') =~ '^s'
99 function! s:compose_quit()
100 let b:compose_done = 1
101 call s:kill_this_buffer()
104 function! s:compose_send()
105 let b:compose_done = 1
106 let fname = expand('%')
112 let cmdtxt = g:notmuch_sendmail . ' -t -f ' . s:reply_from . ' < ' . fname
113 let out = system(cmdtxt)
114 let err = v:shell_error
119 echo 'Eeek! unable to send mail'
125 echo 'Mail sent successfully.'
126 call s:kill_this_buffer()
129 function! s:show_next_msg()
131 r, c = $curwin.cursor
132 n = $curbuf.line_number
133 i = $messages.index { |m| n >= m.start && n <= m.end }
137 VIM::command("normal #{m.start}zt")
138 $curwin.cursor = r, c
143 function! s:show_reply()
144 ruby open_reply get_message.mail
145 let b:compose_done = 0
146 call s:set_map(g:notmuch_rb_compose_maps)
147 autocmd BufUnload <buffer> call s:compose_unload()
151 function! s:show_info()
152 ruby vim_puts get_message.inspect
155 function! s:show_extract_msg()
158 m.mail.attachments.each do |a|
159 File.open(a.filename, 'w') do |f|
160 f.write a.body.decoded
161 print "Extracted '#{a.filename}'"
167 function! s:show_open_msg()
170 mbox = File.expand_path('~/.notmuch/vim_mbox')
171 cmd = VIM::evaluate('g:notmuch_rb_reader') % mbox
172 system "notmuch show --format=mbox id:#{m.message_id} > #{mbox} && #{cmd}"
176 function! s:show_save_msg()
177 let file = input('File name: ')
179 file = VIM::evaluate('file')
181 system "notmuch show --format=mbox id:#{m.message_id} > #{file}"
185 function! s:show_save_patches()
187 q = $curbuf.query($cur_thread)
188 t = q.search_threads.first
190 t.toplevel_messages.first.replies.each do |m|
191 next if not m['subject'] =~ /^\[PATCH.*\]/
192 file = "%04d.patch" % [n += 1]
193 system "notmuch show --format=mbox id:#{m.message_id} > #{file}"
195 vim_puts "Saved #{n} patches"
199 function! s:show_tag(intags)
201 let tags = input('tags: ')
205 ruby do_tag(get_cur_view, VIM::evaluate('l:tags'))
206 call s:show_next_thread()
209 function! s:search_search_prompt()
210 let text = input('Search: ')
213 $cur_search = VIM::evaluate('text')
215 search_render($cur_search)
217 setlocal nomodifiable
220 function! s:search_info()
221 ruby vim_puts get_thread_id
224 function! s:search_refresh()
227 ruby search_render($cur_search)
228 setlocal nomodifiable
231 function! s:search_tag(intags)
233 let tags = input('tags: ')
237 ruby do_tag(get_thread_id, VIM::evaluate('l:tags'))
241 function! s:folders_search_prompt()
242 let text = input('Search: ')
246 function! s:folders_refresh()
249 ruby folders_render()
250 setlocal nomodifiable
255 function! s:show_cursor_moved()
258 VIM::command('setlocal modifiable')
260 VIM::command('setlocal nomodifiable')
265 function! s:show_next_thread()
266 call s:kill_this_buffer()
267 if line('.') != line('$')
269 call s:search_show_thread(0)
271 echo 'No more messages.'
275 function! s:kill_this_buffer()
277 if $buf_queue.size > 1
279 VIM::command("bdelete!")
282 VIM::command("buffer #{b}") if b
287 function! s:set_map(maps)
289 for [key, code] in items(a:maps)
290 let cmd = printf(":call <SID>%s<CR>", code)
291 exec printf('nnoremap <buffer> %s %s', key, cmd)
295 function! s:new_buffer(type)
297 setlocal buftype=nofile bufhidden=hide
299 execute printf('set filetype=notmuch-%s', a:type)
300 execute printf('set syntax=notmuch-%s', a:type)
301 ruby $curbuf.init(VIM::evaluate('a:type'))
302 ruby $buf_queue.push($curbuf.number)
305 function! s:set_menu_buffer()
306 setlocal nomodifiable
313 function! s:show(thread_id)
314 call s:new_buffer('show')
317 thread_id = VIM::evaluate('a:thread_id')
318 $cur_thread = thread_id
320 $curbuf.render do |b|
321 q = $curbuf.query(get_cur_view)
322 q.sort = Notmuch::SORT_OLDEST_FIRST
323 msgs = q.search_messages
325 m = Mail.read(msg.filename)
326 part = m.find_first_text
327 nm_m = Message.new(msg, m)
329 date_fmt = VIM::evaluate('g:notmuch_rb_datetime_format')
330 date = Time.at(msg.date).strftime(date_fmt)
332 b << "%s %s (%s)" % [msg['from'], date, msg.tags]
333 b << "Subject: %s" % [msg['subject']]
334 b << "To: %s" % msg['to']
335 b << "Cc: %s" % msg['cc']
336 b << "Date: %s" % msg['date']
337 nm_m.body_start = b.count
338 b << "--- %s ---" % part.mime_type
339 part.convert.each_line do |l|
347 $messages.each_with_index do |msg, i|
348 VIM::command("syntax region nmShowMsg#{i}Desc start='\\%%%il' end='\\%%%il' contains=@nmShowMsgDesc" % [msg.start, msg.start + 1])
349 VIM::command("syntax region nmShowMsg#{i}Head start='\\%%%il' end='\\%%%il' contains=@nmShowMsgHead" % [msg.start + 1, msg.body_start])
350 VIM::command("syntax region nmShowMsg#{i}Body start='\\%%%il' end='\\%%%dl' contains=@nmShowMsgBody" % [msg.body_start, msg.end])
353 setlocal nomodifiable
354 call s:set_map(g:notmuch_rb_show_maps)
357 function! s:search_show_thread(mode)
359 mode = VIM::evaluate('a:mode')
363 when 1; $cur_filter = nil
364 when 2; $cur_filter = $cur_search
366 VIM::command("call s:show('#{id}')")
370 function! s:search(search)
371 call s:new_buffer('search')
373 $cur_search = VIM::evaluate('a:search')
374 search_render($cur_search)
376 call s:set_menu_buffer()
377 call s:set_map(g:notmuch_rb_search_maps)
378 autocmd CursorMoved <buffer> call s:show_cursor_moved()
381 function! s:folders_show_search()
383 n = $curbuf.line_number
385 VIM::command("call s:search('#{s}')")
389 function! s:folders()
390 call s:new_buffer('folders')
391 ruby folders_render()
392 call s:set_menu_buffer()
393 call s:set_map(g:notmuch_rb_folders_maps)
398 function! s:set_defaults()
399 if exists('g:notmuch_rb_custom_search_maps')
400 call extend(g:notmuch_rb_search_maps, g:notmuch_rb_custom_search_maps)
403 if exists('g:notmuch_rb_custom_show_maps')
404 call extend(g:notmuch_rb_show_maps, g:notmuch_rb_custom_show_maps)
407 " TODO for now lets check the old folders too
408 if !exists('g:notmuch_rb_folders')
409 if exists('g:notmuch_folders')
410 let g:notmuch_rb_folders = g:notmuch_folders
412 let g:notmuch_rb_folders = s:notmuch_rb_folders_default
417 function! s:NotMuch(...)
418 call s:set_defaults()
431 $email = $email_name = $email_address = nil
437 $mail_installed = defined?(Mail)
441 config = ENV['NOTMUCH_CONFIG'] || '~/.notmuch-config'
442 File.open(File.expand_path(config)).each do |l|
449 key = "%s.%s" % [group, $1]
455 $db_name = $config['database.path']
456 $email_name = $config['user.name']
457 $email_address = $config['user.primary_email']
458 $email = "%s <%s>" % [$email_name, $email_address]
462 VIM::command("echo '#{s.to_s}'")
466 VIM::command("echo '#{s.inspect}'")
470 # TODO email format, aliases
472 a.gsub!(/[\.@].*/, '')
474 a.gsub!(/ \(.*\)/, '')
479 n = $curbuf.line_number - 1
480 return "thread:%s" % $threads[n]
484 n = $curbuf.line_number
485 return $messages.find { |m| n >= m.start && n <= m.end }
490 return "#{$cur_thread} and (#{$cur_filter})"
496 def generate_message_id
498 random_tag = sprintf('%x%x_%x%x%x',
500 $$, Thread.current.object_id.abs, rand(255))
501 return "<#{random_tag}@#{Socket.gethostname}.notmuch>"
506 'Notmuch-Help: Type in your message here; to help you use these bindings:',
507 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
508 'Notmuch-Help: ,q - abort the message',
510 reply = orig.reply do |m|
513 m.to = [orig[:from].to_s, orig[:to].to_s]
517 m.message_id = generate_message_id
519 m.content_transfer_encoding = '7bit'
522 dir = File.expand_path('~/.notmuch/compose')
523 FileUtils.mkdir_p(dir)
524 Tempfile.open(['nm-', '.mail'], dir) do |f|
532 addr = Mail::Address.new(orig[:from].value)
534 name = addr.local + "@" if name.nil? && !addr.local.nil?
538 name = "somebody" if name.nil?
540 body_lines << "%s wrote:" % name
541 part = orig.find_first_text
542 part.convert.each_line do |l|
543 body_lines << "> %s" % l.chomp
549 reply.body = body_lines.join("\n")
551 lines += reply.to_s.lines.map { |e| e.chomp }
554 old_count = lines.count - 1
558 sig_file = File.expand_path('~/.signature')
559 if File.exists?(sig_file)
561 f.write(File.read(sig_file))
566 VIM::command("let s:reply_from='%s'" % reply.from.first.to_s)
567 VIM::command("call s:new_file_buffer('compose', '#{f.path}')")
568 VIM::command("call cursor(#{old_count}, 0)")
573 $curbuf.render do |b|
574 folders = VIM::evaluate('g:notmuch_rb_folders')
575 count_threads = VIM::evaluate('g:notmuch_rb_folders_count_threads')
577 folders.each do |name, search|
578 q = $curbuf.query(search)
580 count = count_threads ? q.search_threads.count : q.search_messages.count
581 b << "%9d %-20s (%s)" % [count, name, search]
586 def search_render(search)
587 date_fmt = VIM::evaluate('g:notmuch_rb_date_format')
588 q = $curbuf.query(search)
589 q.sort = Notmuch::SORT_NEWEST_FIRST
593 $render = $curbuf.render_staged(t) do |b, items|
595 authors = e.authors.to_utf8.split(/[,|]/).map { |a| author_filter(a) }.join(",")
596 date = Time.at(e.newest_date).strftime(date_fmt)
597 subject = e.messages.first['subject']
599 subject = Mail::Field.new("Subject: " + subject).to_s
601 subject = subject.force_encoding('utf-8')
603 b << "%-12s %3s %-20.20s | %s (%s)" % [date, e.matched_messages, authors, subject, e.tags]
604 $threads << e.thread_id
609 def do_tag(filter, tags)
610 $curbuf.do_write do |db|
612 q.search_messages.each do |e|
614 tags.split.each do |t|
625 e.tags_to_maildir_flags
634 @db = Notmuch::Database.new($db_name)
645 @queries.delete_if { |q| ! q.destroy! }
651 @db = Notmuch::Database.new($db_name)
655 db = Notmuch::Database.new($db_name, :mode => Notmuch::MODE_READ_WRITE)
665 attr_accessor :start, :body_start, :end
666 attr_reader :message_id, :filename, :mail
668 def initialize(msg, mail)
669 @message_id = msg.message_id
670 @filename = msg.filename
674 mail.import_headers(msg) if not $mail_installed
678 "id:%s" % @message_id
682 "id:%s, file:%s" % [@message_id, @filename]
687 def initialize(buffer, enumerable, block)
689 @enumerable = enumerable
693 @b.render { do_next }
697 @last_render - @b.line_number <= $curwin.height
701 items = @enumerable.take($curwin.height * 2)
702 return if items.empty?
703 @block.call @b, items
704 @last_render = @b.count
715 def render_staged(enumerable, &block)
716 StagedRender.new(self, enumerable, block)
722 (1..old_count).each do
734 class Notmuch::Message
740 # workaround for bug in vim's ruby
748 def self.parse(string)
749 return nil if string.empty?
750 return Header.new(string.split(/,\s+/))
758 def initialize(string = nil)
765 if string =~ /(.*?(\r\n|\n))\2/m
766 head, body = $1, $' || '', $2
768 head, body = string, ''
774 @headers[name.to_sym]
778 @headers[name.to_sym] = value
781 def format_header(value)
782 value.to_s.tr('_', '-').gsub(/(\w+)/) { $1.capitalize }
787 @headers.each do |key, value|
788 buffer << "%s: %s\r\n" %
789 [format_header(key), value]
817 r = Mail::Message.new
821 r[:in_reply_to] = self[:message_id]
822 r[:references] = self[:references]
826 HEADERS = [ :from, :to, :cc, :references, :in_reply_to, :reply_to, :message_id ]
828 def import_headers(m)
830 dashed = format_header(e)
831 @headers[e] = Header.parse(m[dashed])
838 if not $mail_installed
839 puts "WARNING: Install the 'mail' gem, without it support is limited"
841 def self.read(filename)
842 Message.new(File.open(filename, 'rb') { |f| f.read })
846 include SimpleMessage
853 return self if not multipart?
854 return text_part || html_part
858 if mime_type != "text/html"
861 IO.popen("elinks --dump", "w+") do |pipe|
862 pipe.write(decode_body)
874 RUBY_VERSION >= "1.9" ? force_encoding('utf-8') : self
881 call s:search(join(a:000))
887 command -nargs=* NotMuch call s:NotMuch(<f-args>)
889 " vim: set noexpandtab: