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: ')
216 $cur_search = VIM::evaluate('text')
218 search_render($cur_search)
220 setlocal nomodifiable
223 function! s:search_info()
224 ruby vim_puts get_thread_id
227 function! s:search_refresh()
230 ruby search_render($cur_search)
231 setlocal nomodifiable
234 function! s:search_tag(intags)
236 let tags = input('tags: ')
240 ruby do_tag(get_thread_id, VIM::evaluate('l:tags'))
244 function! s:folders_search_prompt()
245 let text = input('Search: ')
249 function! s:folders_refresh()
252 ruby folders_render()
253 setlocal nomodifiable
258 function! s:show_cursor_moved()
261 VIM::command('setlocal modifiable')
263 VIM::command('setlocal nomodifiable')
268 function! s:show_next_thread()
269 call s:kill_this_buffer()
270 if line('.') != line('$')
272 call s:search_show_thread(0)
274 echo 'No more messages.'
278 function! s:kill_this_buffer()
280 if $buf_queue.size > 1
282 VIM::command("bdelete!")
285 VIM::command("buffer #{b}") if b
290 function! s:set_map(maps)
292 for [key, code] in items(a:maps)
293 let cmd = printf(":call <SID>%s<CR>", code)
294 exec printf('nnoremap <buffer> %s %s', key, cmd)
298 function! s:new_buffer(type)
300 setlocal buftype=nofile bufhidden=hide
302 execute printf('set filetype=notmuch-%s', a:type)
303 execute printf('set syntax=notmuch-%s', a:type)
304 ruby $curbuf.init(VIM::evaluate('a:type'))
305 ruby $buf_queue.push($curbuf.number)
308 function! s:set_menu_buffer()
309 setlocal nomodifiable
316 function! s:show(thread_id)
317 call s:new_buffer('show')
320 thread_id = VIM::evaluate('a:thread_id')
321 $cur_thread = thread_id
323 $curbuf.render do |b|
324 q = $curbuf.query(get_cur_view)
325 q.sort = Notmuch::SORT_OLDEST_FIRST
326 msgs = q.search_messages
328 m = Mail.read(msg.filename)
329 part = m.find_first_text
330 nm_m = Message.new(msg, m)
332 date_fmt = VIM::evaluate('g:notmuch_rb_datetime_format')
333 date = Time.at(msg.date).strftime(date_fmt)
335 b << "%s %s (%s)" % [msg['from'], date, msg.tags]
336 b << "Subject: %s" % [msg['subject']]
337 b << "To: %s" % msg['to']
338 b << "Cc: %s" % msg['cc']
339 b << "Date: %s" % msg['date']
340 nm_m.body_start = b.count
341 b << "--- %s ---" % part.mime_type
342 part.convert.each_line do |l|
350 $messages.each_with_index do |msg, i|
351 VIM::command("syntax region nmShowMsg#{i}Desc start='\\%%%il' end='\\%%%il' contains=@nmShowMsgDesc" % [msg.start, msg.start + 1])
352 VIM::command("syntax region nmShowMsg#{i}Head start='\\%%%il' end='\\%%%il' contains=@nmShowMsgHead" % [msg.start + 1, msg.body_start])
353 VIM::command("syntax region nmShowMsg#{i}Body start='\\%%%il' end='\\%%%dl' contains=@nmShowMsgBody" % [msg.body_start, msg.end])
356 setlocal nomodifiable
357 call s:set_map(g:notmuch_rb_show_maps)
360 function! s:search_show_thread(mode)
362 mode = VIM::evaluate('a:mode')
366 when 1; $cur_filter = nil
367 when 2; $cur_filter = $cur_search
369 VIM::command("call s:show('#{id}')")
373 function! s:search(search)
374 call s:new_buffer('search')
376 $cur_search = VIM::evaluate('a:search')
377 search_render($cur_search)
379 call s:set_menu_buffer()
380 call s:set_map(g:notmuch_rb_search_maps)
381 autocmd CursorMoved <buffer> call s:show_cursor_moved()
384 function! s:folders_show_search()
386 n = $curbuf.line_number
388 VIM::command("call s:search('#{s}')")
392 function! s:folders()
393 call s:new_buffer('folders')
394 ruby folders_render()
395 call s:set_menu_buffer()
396 call s:set_map(g:notmuch_rb_folders_maps)
401 function! s:set_defaults()
402 if exists('g:notmuch_rb_custom_search_maps')
403 call extend(g:notmuch_rb_search_maps, g:notmuch_rb_custom_search_maps)
406 if exists('g:notmuch_rb_custom_show_maps')
407 call extend(g:notmuch_rb_show_maps, g:notmuch_rb_custom_show_maps)
410 " TODO for now lets check the old folders too
411 if !exists('g:notmuch_rb_folders')
412 if exists('g:notmuch_folders')
413 let g:notmuch_rb_folders = g:notmuch_folders
415 let g:notmuch_rb_folders = s:notmuch_rb_folders_default
420 function! s:NotMuch(...)
421 call s:set_defaults()
434 $email = $email_name = $email_address = nil
440 $mail_installed = defined?(Mail)
444 config = ENV['NOTMUCH_CONFIG'] || '~/.notmuch-config'
445 File.open(File.expand_path(config)).each do |l|
452 key = "%s.%s" % [group, $1]
458 $db_name = $config['database.path']
459 $email_name = $config['user.name']
460 $email_address = $config['user.primary_email']
461 $email = "%s <%s>" % [$email_name, $email_address]
465 VIM::command("echo '#{s.to_s}'")
469 VIM::command("echo '#{s.inspect}'")
473 # TODO email format, aliases
475 a.gsub!(/[\.@].*/, '')
477 a.gsub!(/ \(.*\)/, '')
482 n = $curbuf.line_number - 1
483 return "thread:%s" % $threads[n]
487 n = $curbuf.line_number
488 return $messages.find { |m| n >= m.start && n <= m.end }
493 return "#{$cur_thread} and (#{$cur_filter})"
499 def generate_message_id
501 random_tag = sprintf('%x%x_%x%x%x',
503 $$, Thread.current.object_id.abs, rand(255))
504 return "<#{random_tag}@#{Socket.gethostname}.notmuch>"
507 def open_compose_helper(lines, cur)
509 'Notmuch-Help: Type in your message here; to help you use these bindings:',
510 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
511 'Notmuch-Help: ,q - abort the message',
514 dir = File.expand_path('~/.notmuch/compose')
515 FileUtils.mkdir_p(dir)
516 Tempfile.open(['nm-', '.mail'], dir) do |f|
521 sig_file = File.expand_path('~/.signature')
522 if File.exists?(sig_file)
524 f.write(File.read(sig_file))
529 cur += help_lines.size + 1
531 VIM::command("let s:reply_from='%s'" % $email_address)
532 VIM::command("call s:new_file_buffer('compose', '#{f.path}')")
533 VIM::command("call cursor(#{cur}, 0)")
538 reply = orig.reply do |m|
541 m.to = [orig[:from].to_s, orig[:to].to_s]
545 m.message_id = generate_message_id
547 m.content_transfer_encoding = '7bit'
554 addr = Mail::Address.new(orig[:from].value)
556 name = addr.local + "@" if name.nil? && !addr.local.nil?
560 name = "somebody" if name.nil?
562 body_lines << "%s wrote:" % name
563 part = orig.find_first_text
564 part.convert.each_line do |l|
565 body_lines << "> %s" % l.chomp
571 reply.body = body_lines.join("\n")
573 lines += reply.to_s.lines.map { |e| e.chomp }
576 cur = lines.count - 1
578 open_compose_helper(lines, cur)
582 $curbuf.render do |b|
583 folders = VIM::evaluate('g:notmuch_rb_folders')
584 count_threads = VIM::evaluate('g:notmuch_rb_folders_count_threads')
586 folders.each do |name, search|
587 q = $curbuf.query(search)
589 count = count_threads ? q.search_threads.count : q.search_messages.count
590 b << "%9d %-20s (%s)" % [count, name, search]
595 def search_render(search)
596 date_fmt = VIM::evaluate('g:notmuch_rb_date_format')
597 q = $curbuf.query(search)
598 q.sort = Notmuch::SORT_NEWEST_FIRST
602 $render = $curbuf.render_staged(t) do |b, items|
604 authors = e.authors.to_utf8.split(/[,|]/).map { |a| author_filter(a) }.join(",")
605 date = Time.at(e.newest_date).strftime(date_fmt)
606 subject = e.messages.first['subject']
608 subject = Mail::Field.new("Subject: " + subject).to_s
610 subject = subject.force_encoding('utf-8')
612 b << "%-12s %3s %-20.20s | %s (%s)" % [date, e.matched_messages, authors, subject, e.tags]
613 $threads << e.thread_id
618 def do_tag(filter, tags)
619 $curbuf.do_write do |db|
621 q.search_messages.each do |e|
623 tags.split.each do |t|
634 e.tags_to_maildir_flags
643 @db = Notmuch::Database.new($db_name)
654 @queries.delete_if { |q| ! q.destroy! }
660 @db = Notmuch::Database.new($db_name)
664 db = Notmuch::Database.new($db_name, :mode => Notmuch::MODE_READ_WRITE)
674 attr_accessor :start, :body_start, :end
675 attr_reader :message_id, :filename, :mail
677 def initialize(msg, mail)
678 @message_id = msg.message_id
679 @filename = msg.filename
683 mail.import_headers(msg) if not $mail_installed
687 "id:%s" % @message_id
691 "id:%s, file:%s" % [@message_id, @filename]
696 def initialize(buffer, enumerable, block)
698 @enumerable = enumerable
702 @b.render { do_next }
706 @last_render - @b.line_number <= $curwin.height
710 items = @enumerable.take($curwin.height * 2)
711 return if items.empty?
712 @block.call @b, items
713 @last_render = @b.count
724 def render_staged(enumerable, &block)
725 StagedRender.new(self, enumerable, block)
731 (1..old_count).each do
743 class Notmuch::Message
749 # workaround for bug in vim's ruby
757 def self.parse(string)
758 return nil if string.empty?
759 return Header.new(string.split(/,\s+/))
767 def initialize(string = nil)
774 if string =~ /(.*?(\r\n|\n))\2/m
775 head, body = $1, $' || '', $2
777 head, body = string, ''
783 @headers[name.to_sym]
787 @headers[name.to_sym] = value
790 def format_header(value)
791 value.to_s.tr('_', '-').gsub(/(\w+)/) { $1.capitalize }
796 @headers.each do |key, value|
797 buffer << "%s: %s\r\n" %
798 [format_header(key), value]
826 r = Mail::Message.new
830 r[:in_reply_to] = self[:message_id]
831 r[:references] = self[:references]
835 HEADERS = [ :from, :to, :cc, :references, :in_reply_to, :reply_to, :message_id ]
837 def import_headers(m)
839 dashed = format_header(e)
840 @headers[e] = Header.parse(m[dashed])
847 if not $mail_installed
848 puts "WARNING: Install the 'mail' gem, without it support is limited"
850 def self.read(filename)
851 Message.new(File.open(filename, 'rb') { |f| f.read })
855 include SimpleMessage
862 return self if not multipart?
863 return text_part || html_part
867 if mime_type != "text/html"
870 IO.popen("elinks --dump", "w+") do |pipe|
871 pipe.write(decode_body)
883 RUBY_VERSION >= "1.9" ? force_encoding('utf-8') : self
890 call s:search(join(a:000))
896 command -nargs=* NotMuch call s:NotMuch(<f-args>)
898 " vim: set noexpandtab: