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'))
68 ruby $buf_queue.push($curbuf.number)
71 function! s:compose_unload()
75 if input('[s]end/[q]uit? ') =~ '^s'
82 function! s:compose_quit()
83 let b:compose_done = 1
84 call s:kill_this_buffer()
87 function! s:compose_send()
88 let b:compose_done = 1
89 let fname = expand('%')
95 let cmdtxt = g:notmuch_sendmail . ' -t -f ' . s:reply_from . ' < ' . fname
96 let out = system(cmdtxt)
97 let err = v:shell_error
102 echo 'Eeek! unable to send mail'
108 echo 'Mail sent successfully.'
109 call s:kill_this_buffer()
112 function! s:show_next_msg()
114 r, c = $curwin.cursor
115 n = $curbuf.line_number
116 i = $messages.index { |m| n >= m.start && n <= m.end }
120 VIM::command("normal #{m.start}zt")
121 $curwin.cursor = r, c
126 function! s:show_reply()
127 ruby open_reply get_message.mail
128 let b:compose_done = 0
129 call s:set_map(g:notmuch_compose_maps)
130 autocmd BufUnload <buffer> call s:compose_unload()
134 function! s:compose()
136 let b:compose_done = 0
137 call s:set_map(g:notmuch_compose_maps)
138 autocmd BufUnload <buffer> call s:compose_unload()
142 function! s:show_info()
143 ruby vim_puts get_message.inspect
146 function! s:show_extract_msg()
149 m.mail.attachments.each do |a|
150 File.open(a.filename, 'w') do |f|
151 f.write a.body.decoded
152 print "Extracted '#{a.filename}'"
158 function! s:show_open_msg()
161 mbox = File.expand_path('~/.notmuch/vim_mbox')
162 cmd = VIM::evaluate('g:notmuch_reader') % mbox
163 system "notmuch show --format=mbox id:#{m.message_id} > #{mbox} && #{cmd}"
167 function! s:show_save_msg()
168 let file = input('File name: ')
170 file = VIM::evaluate('file')
172 system "notmuch show --format=mbox id:#{m.message_id} > #{file}"
176 function! s:show_save_patches()
178 q = $curbuf.query($cur_thread)
179 t = q.search_threads.first
181 t.toplevel_messages.first.replies.each do |m|
182 next if not m['subject'] =~ /^\[PATCH.*\]/
183 file = "%04d.patch" % [n += 1]
184 system "notmuch show --format=mbox id:#{m.message_id} > #{file}"
186 vim_puts "Saved #{n} patches"
190 function! s:show_tag(intags)
192 let tags = input('tags: ')
196 ruby do_tag(get_cur_view, VIM::evaluate('l:tags'))
197 call s:show_next_thread()
200 function! s:search_search_prompt()
201 let text = input('Search: ')
207 $cur_search = VIM::evaluate('text')
209 search_render($cur_search)
211 setlocal nomodifiable
214 function! s:search_info()
215 ruby vim_puts get_thread_id
218 function! s:search_refresh()
221 ruby search_render($cur_search)
222 setlocal nomodifiable
225 function! s:search_tag(intags)
227 let tags = input('tags: ')
231 ruby do_tag(get_thread_id, VIM::evaluate('l:tags'))
235 function! s:folders_search_prompt()
236 let text = input('Search: ')
240 function! s:folders_refresh()
243 ruby folders_render()
244 setlocal nomodifiable
249 function! s:show_cursor_moved()
252 VIM::command('setlocal modifiable')
254 VIM::command('setlocal nomodifiable')
259 function! s:show_next_thread()
260 call s:kill_this_buffer()
261 if line('.') != line('$')
263 call s:search_show_thread(0)
265 echo 'No more messages.'
269 function! s:kill_this_buffer()
271 if $buf_queue.size > 1
273 VIM::command("bdelete!")
276 VIM::command("buffer #{b}") if b
281 function! s:set_map(maps)
283 for [key, code] in items(a:maps)
284 let cmd = printf(":call <SID>%s<CR>", code)
285 exec printf('nnoremap <buffer> %s %s', key, cmd)
289 function! s:new_buffer(type)
291 setlocal buftype=nofile bufhidden=hide
293 execute printf('set filetype=notmuch-%s', a:type)
294 execute printf('set syntax=notmuch-%s', a:type)
295 ruby $curbuf.init(VIM::evaluate('a:type'))
296 ruby $buf_queue.push($curbuf.number)
299 function! s:set_menu_buffer()
300 setlocal nomodifiable
307 function! s:show(thread_id)
308 call s:new_buffer('show')
311 thread_id = VIM::evaluate('a:thread_id')
312 $cur_thread = thread_id
314 $curbuf.render do |b|
315 q = $curbuf.query(get_cur_view)
316 q.sort = Notmuch::SORT_OLDEST_FIRST
317 msgs = q.search_messages
319 m = Mail.read(msg.filename)
320 part = m.find_first_text
321 nm_m = Message.new(msg, m)
323 date_fmt = VIM::evaluate('g:notmuch_datetime_format')
324 date = Time.at(msg.date).strftime(date_fmt)
326 b << "%s %s (%s)" % [msg['from'], date, msg.tags]
327 b << "Subject: %s" % [msg['subject']]
328 b << "To: %s" % msg['to']
329 b << "Cc: %s" % msg['cc']
330 b << "Date: %s" % msg['date']
331 nm_m.body_start = b.count
332 b << "--- %s ---" % part.mime_type
333 part.convert.each_line do |l|
341 $messages.each_with_index do |msg, i|
342 VIM::command("syntax region nmShowMsg#{i}Desc start='\\%%%il' end='\\%%%il' contains=@nmShowMsgDesc" % [msg.start, msg.start + 1])
343 VIM::command("syntax region nmShowMsg#{i}Head start='\\%%%il' end='\\%%%il' contains=@nmShowMsgHead" % [msg.start + 1, msg.body_start])
344 VIM::command("syntax region nmShowMsg#{i}Body start='\\%%%il' end='\\%%%dl' contains=@nmShowMsgBody" % [msg.body_start, msg.end])
347 setlocal nomodifiable
348 call s:set_map(g:notmuch_show_maps)
351 function! s:search_show_thread(mode)
353 mode = VIM::evaluate('a:mode')
357 when 1; $cur_filter = nil
358 when 2; $cur_filter = $cur_search
360 VIM::command("call s:show('#{id}')")
364 function! s:search(search)
365 call s:new_buffer('search')
367 $cur_search = VIM::evaluate('a:search')
368 search_render($cur_search)
370 call s:set_menu_buffer()
371 call s:set_map(g:notmuch_search_maps)
372 autocmd CursorMoved <buffer> call s:show_cursor_moved()
375 function! s:folders_show_search()
377 n = $curbuf.line_number
379 VIM::command("call s:search('#{s}')")
383 function! s:folders()
384 call s:new_buffer('folders')
385 ruby folders_render()
386 call s:set_menu_buffer()
387 call s:set_map(g:notmuch_folders_maps)
392 function! s:set_defaults()
393 if !exists('g:notmuch_date_format')
394 if exists('g:notmuch_rb_date_format')
395 let g:notmuch_date_format = g:notmuch_rb_date_format
397 let g:notmuch_date_format = s:notmuch_date_format_default
401 if !exists('g:notmuch_datetime_format')
402 if exists('g:notmuch_rb_datetime_format')
403 let g:notmuch_datetime_format = g:notmuch_rb_datetime_format
405 let g:notmuch_datetime_format = s:notmuch_datetime_format_default
409 if !exists('g:notmuch_reader')
410 if exists('g:notmuch_rb_reader')
411 let g:notmuch_reader = g:notmuch_rb_reader
413 let g:notmuch_reader = s:notmuch_reader_default
417 if !exists('g:notmuch_sendmail')
418 if exists('g:notmuch_rb_sendmail')
419 let g:notmuch_sendmail = g:notmuch_rb_sendmail
421 let g:notmuch_sendmail = s:notmuch_sendmail_default
425 if !exists('g:notmuch_folders_count_threads')
426 if exists('g:notmuch_rb_count_threads')
427 let g:notmuch_count_threads = g:notmuch_rb_count_threads
429 let g:notmuch_folders_count_threads = s:notmuch_folders_count_threads_default
433 if !exists('g:notmuch_custom_search_maps') && exists('g:notmuch_rb_custom_search_maps')
434 let g:notmuch_custom_search_maps = g:notmuch_rb_custom_search_maps
437 if !exists('g:notmuch_custom_show_maps') && exists('g:notmuch_rb_custom_show_maps')
438 let g:notmuch_custom_show_maps = g:notmuch_rb_custom_show_maps
441 if exists('g:notmuch_custom_search_maps')
442 call extend(g:notmuch_search_maps, g:notmuch_custom_search_maps)
445 if exists('g:notmuch_custom_show_maps')
446 call extend(g:notmuch_show_maps, g:notmuch_custom_show_maps)
449 if !exists('g:notmuch_folders')
450 if exists('g:notmuch_rb_folders')
451 let g:notmuch_folders = g:notmuch_rb_folders
453 let g:notmuch_folders = s:notmuch_folders_default
458 function! s:NotMuch(...)
459 call s:set_defaults()
472 $email = $email_name = $email_address = nil
478 $mail_installed = defined?(Mail)
482 config = ENV['NOTMUCH_CONFIG'] || '~/.notmuch-config'
483 File.open(File.expand_path(config)).each do |l|
490 key = "%s.%s" % [group, $1]
496 $db_name = $config['database.path']
497 $email_name = $config['user.name']
498 $email_address = $config['user.primary_email']
499 $email = "%s <%s>" % [$email_name, $email_address]
503 VIM::command("echo '#{s.to_s}'")
507 VIM::command("echo '#{s.inspect}'")
511 # TODO email format, aliases
513 a.gsub!(/[\.@].*/, '')
515 a.gsub!(/ \(.*\)/, '')
520 n = $curbuf.line_number - 1
521 return "thread:%s" % $threads[n]
525 n = $curbuf.line_number
526 return $messages.find { |m| n >= m.start && n <= m.end }
531 return "#{$cur_thread} and (#{$cur_filter})"
537 def generate_message_id
539 random_tag = sprintf('%x%x_%x%x%x',
541 $$, Thread.current.object_id.abs, rand(255))
542 return "<#{random_tag}@#{Socket.gethostname}.notmuch>"
545 def open_compose_helper(lines, cur)
547 'Notmuch-Help: Type in your message here; to help you use these bindings:',
548 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
549 'Notmuch-Help: ,q - abort the message',
552 dir = File.expand_path('~/.notmuch/compose')
553 FileUtils.mkdir_p(dir)
554 Tempfile.open(['nm-', '.mail'], dir) do |f|
559 sig_file = File.expand_path('~/.signature')
560 if File.exists?(sig_file)
562 f.write(File.read(sig_file))
567 cur += help_lines.size + 1
569 VIM::command("let s:reply_from='%s'" % $email_address)
570 VIM::command("call s:new_file_buffer('compose', '#{f.path}')")
571 VIM::command("call cursor(#{cur}, 0)")
576 reply = orig.reply do |m|
579 m.to = [orig[:from].to_s, orig[:to].to_s]
583 m.message_id = generate_message_id
585 m.content_transfer_encoding = '7bit'
592 addr = Mail::Address.new(orig[:from].value)
594 name = addr.local + "@" if name.nil? && !addr.local.nil?
598 name = "somebody" if name.nil?
600 body_lines << "%s wrote:" % name
601 part = orig.find_first_text
602 part.convert.each_line do |l|
603 body_lines << "> %s" % l.chomp
609 reply.body = body_lines.join("\n")
611 lines += reply.to_s.lines.map { |e| e.chomp }
614 cur = lines.count - 1
616 open_compose_helper(lines, cur)
622 lines << "Date: #{Time.now().strftime('%a, %-d %b %Y %T %z')}"
623 lines << "From: #{$email}"
629 lines << "Message-Id: #{generate_message_id}"
631 lines << "Mime-Version: 1.0"
632 lines << "Content-Type: text/plain; charset=utf-8"
633 lines << "Content-Transfer-Encoding: 7bit"
638 open_compose_helper(lines, cur)
642 $curbuf.render do |b|
643 folders = VIM::evaluate('g:notmuch_folders')
644 count_threads = VIM::evaluate('g:notmuch_folders_count_threads')
646 folders.each do |name, search|
647 q = $curbuf.query(search)
649 count = count_threads ? q.search_threads.count : q.search_messages.count
650 b << "%9d %-20s (%s)" % [count, name, search]
655 def search_render(search)
656 date_fmt = VIM::evaluate('g:notmuch_date_format')
657 q = $curbuf.query(search)
658 q.sort = Notmuch::SORT_NEWEST_FIRST
662 $render = $curbuf.render_staged(t) do |b, items|
664 authors = e.authors.to_utf8.split(/[,|]/).map { |a| author_filter(a) }.join(",")
665 date = Time.at(e.newest_date).strftime(date_fmt)
666 subject = e.messages.first['subject']
668 subject = Mail::Field.new("Subject: " + subject).to_s
670 subject = subject.force_encoding('utf-8')
672 b << "%-12s %3s %-20.20s | %s (%s)" % [date, e.matched_messages, authors, subject, e.tags]
673 $threads << e.thread_id
678 def do_tag(filter, tags)
679 $curbuf.do_write do |db|
681 q.search_messages.each do |e|
683 tags.split.each do |t|
694 e.tags_to_maildir_flags
703 @db = Notmuch::Database.new($db_name)
714 @queries.delete_if { |q| ! q.destroy! }
720 @db = Notmuch::Database.new($db_name)
724 db = Notmuch::Database.new($db_name, :mode => Notmuch::MODE_READ_WRITE)
734 attr_accessor :start, :body_start, :end
735 attr_reader :message_id, :filename, :mail
737 def initialize(msg, mail)
738 @message_id = msg.message_id
739 @filename = msg.filename
743 mail.import_headers(msg) if not $mail_installed
747 "id:%s" % @message_id
751 "id:%s, file:%s" % [@message_id, @filename]
756 def initialize(buffer, enumerable, block)
758 @enumerable = enumerable
762 @b.render { do_next }
766 @last_render - @b.line_number <= $curwin.height
770 items = @enumerable.take($curwin.height * 2)
771 return if items.empty?
772 @block.call @b, items
773 @last_render = @b.count
784 def render_staged(enumerable, &block)
785 StagedRender.new(self, enumerable, block)
791 (1..old_count).each do
803 class Notmuch::Message
809 # workaround for bug in vim's ruby
817 def self.parse(string)
818 return nil if string.empty?
819 return Header.new(string.split(/,\s+/))
827 def initialize(string = nil)
834 if string =~ /(.*?(\r\n|\n))\2/m
835 head, body = $1, $' || '', $2
837 head, body = string, ''
843 @headers[name.to_sym]
847 @headers[name.to_sym] = value
850 def format_header(value)
851 value.to_s.tr('_', '-').gsub(/(\w+)/) { $1.capitalize }
856 @headers.each do |key, value|
857 buffer << "%s: %s\r\n" %
858 [format_header(key), value]
886 r = Mail::Message.new
890 r[:in_reply_to] = self[:message_id]
891 r[:references] = self[:references]
895 HEADERS = [ :from, :to, :cc, :references, :in_reply_to, :reply_to, :message_id ]
897 def import_headers(m)
899 dashed = format_header(e)
900 @headers[e] = Header.parse(m[dashed])
907 if not $mail_installed
908 puts "WARNING: Install the 'mail' gem, without it support is limited"
910 def self.read(filename)
911 Message.new(File.open(filename, 'rb') { |f| f.read })
915 include SimpleMessage
922 return self if not multipart?
923 return text_part || html_part
927 if mime_type != "text/html"
930 IO.popen("elinks --dump", "w+") do |pipe|
931 pipe.write(decode_body)
943 RUBY_VERSION >= "1.9" ? force_encoding('utf-8') : self
950 call s:search(join(a:000))
956 command -nargs=* NotMuch call s:NotMuch(<f-args>)
958 " vim: set noexpandtab: