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 let g:notmuch_date_format = s:notmuch_date_format_default
397 if !exists('g:notmuch_datetime_format')
398 let g:notmuch_datetime_format = s:notmuch_datetime_format_default
401 if !exists('g:notmuch_reader')
402 let g:notmuch_reader = s:notmuch_reader_default
405 if !exists('g:notmuch_sendmail')
406 let g:notmuch_sendmail = s:notmuch_sendmail_default
409 if !exists('g:notmuch_folders_count_threads')
410 let g:notmuch_folders_count_threads = s:notmuch_folders_count_threads_default
413 if exists('g:notmuch_custom_search_maps')
414 call extend(g:notmuch_search_maps, g:notmuch_custom_search_maps)
417 if exists('g:notmuch_custom_show_maps')
418 call extend(g:notmuch_show_maps, g:notmuch_custom_show_maps)
421 if !exists('g:notmuch_folders')
422 let g:notmuch_folders = s:notmuch_folders_default
426 function! s:NotMuch(...)
427 call s:set_defaults()
440 $email = $email_name = $email_address = nil
446 $mail_installed = defined?(Mail)
450 config = ENV['NOTMUCH_CONFIG'] || '~/.notmuch-config'
451 File.open(File.expand_path(config)).each do |l|
458 key = "%s.%s" % [group, $1]
464 $db_name = $config['database.path']
465 $email_name = $config['user.name']
466 $email_address = $config['user.primary_email']
467 $email = "%s <%s>" % [$email_name, $email_address]
471 VIM::command("echo '#{s.to_s}'")
475 VIM::command("echo '#{s.inspect}'")
479 # TODO email format, aliases
481 a.gsub!(/[\.@].*/, '')
483 a.gsub!(/ \(.*\)/, '')
488 n = $curbuf.line_number - 1
489 return "thread:%s" % $threads[n]
493 n = $curbuf.line_number
494 return $messages.find { |m| n >= m.start && n <= m.end }
499 return "#{$cur_thread} and (#{$cur_filter})"
505 def generate_message_id
507 random_tag = sprintf('%x%x_%x%x%x',
509 $$, Thread.current.object_id.abs, rand(255))
510 return "<#{random_tag}@#{Socket.gethostname}.notmuch>"
513 def open_compose_helper(lines, cur)
515 'Notmuch-Help: Type in your message here; to help you use these bindings:',
516 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
517 'Notmuch-Help: ,q - abort the message',
520 dir = File.expand_path('~/.notmuch/compose')
521 FileUtils.mkdir_p(dir)
522 Tempfile.open(['nm-', '.mail'], dir) do |f|
527 sig_file = File.expand_path('~/.signature')
528 if File.exists?(sig_file)
530 f.write(File.read(sig_file))
535 cur += help_lines.size + 1
537 VIM::command("let s:reply_from='%s'" % $email_address)
538 VIM::command("call s:new_file_buffer('compose', '#{f.path}')")
539 VIM::command("call cursor(#{cur}, 0)")
544 reply = orig.reply do |m|
547 m.to = [orig[:from].to_s, orig[:to].to_s]
551 m.message_id = generate_message_id
553 m.content_transfer_encoding = '7bit'
560 addr = Mail::Address.new(orig[:from].value)
562 name = addr.local + "@" if name.nil? && !addr.local.nil?
566 name = "somebody" if name.nil?
568 body_lines << "%s wrote:" % name
569 part = orig.find_first_text
570 part.convert.each_line do |l|
571 body_lines << "> %s" % l.chomp
577 reply.body = body_lines.join("\n")
579 lines += reply.to_s.lines.map { |e| e.chomp }
582 cur = lines.count - 1
584 open_compose_helper(lines, cur)
590 lines << "Date: #{Time.now().strftime('%a, %-d %b %Y %T %z')}"
591 lines << "From: #{$email}"
597 lines << "Message-Id: #{generate_message_id}"
599 lines << "Mime-Version: 1.0"
600 lines << "Content-Type: text/plain; charset=utf-8"
601 lines << "Content-Transfer-Encoding: 7bit"
606 open_compose_helper(lines, cur)
610 $curbuf.render do |b|
611 folders = VIM::evaluate('g:notmuch_folders')
612 count_threads = VIM::evaluate('g:notmuch_folders_count_threads')
614 folders.each do |name, search|
615 q = $curbuf.query(search)
617 count = count_threads ? q.search_threads.count : q.search_messages.count
618 b << "%9d %-20s (%s)" % [count, name, search]
623 def search_render(search)
624 date_fmt = VIM::evaluate('g:notmuch_date_format')
625 q = $curbuf.query(search)
626 q.sort = Notmuch::SORT_NEWEST_FIRST
630 $render = $curbuf.render_staged(t) do |b, items|
632 authors = e.authors.to_utf8.split(/[,|]/).map { |a| author_filter(a) }.join(",")
633 date = Time.at(e.newest_date).strftime(date_fmt)
634 subject = e.messages.first['subject']
636 subject = Mail::Field.new("Subject: " + subject).to_s
638 subject = subject.force_encoding('utf-8')
640 b << "%-12s %3s %-20.20s | %s (%s)" % [date, e.matched_messages, authors, subject, e.tags]
641 $threads << e.thread_id
646 def do_tag(filter, tags)
647 $curbuf.do_write do |db|
649 q.search_messages.each do |e|
651 tags.split.each do |t|
662 e.tags_to_maildir_flags
671 @db = Notmuch::Database.new($db_name)
682 @queries.delete_if { |q| ! q.destroy! }
688 @db = Notmuch::Database.new($db_name)
692 db = Notmuch::Database.new($db_name, :mode => Notmuch::MODE_READ_WRITE)
702 attr_accessor :start, :body_start, :end
703 attr_reader :message_id, :filename, :mail
705 def initialize(msg, mail)
706 @message_id = msg.message_id
707 @filename = msg.filename
711 mail.import_headers(msg) if not $mail_installed
715 "id:%s" % @message_id
719 "id:%s, file:%s" % [@message_id, @filename]
724 def initialize(buffer, enumerable, block)
726 @enumerable = enumerable
730 @b.render { do_next }
734 @last_render - @b.line_number <= $curwin.height
738 items = @enumerable.take($curwin.height * 2)
739 return if items.empty?
740 @block.call @b, items
741 @last_render = @b.count
752 def render_staged(enumerable, &block)
753 StagedRender.new(self, enumerable, block)
759 (1..old_count).each do
771 class Notmuch::Message
777 # workaround for bug in vim's ruby
785 def self.parse(string)
786 return nil if string.empty?
787 return Header.new(string.split(/,\s+/))
795 def initialize(string = nil)
802 if string =~ /(.*?(\r\n|\n))\2/m
803 head, body = $1, $' || '', $2
805 head, body = string, ''
811 @headers[name.to_sym]
815 @headers[name.to_sym] = value
818 def format_header(value)
819 value.to_s.tr('_', '-').gsub(/(\w+)/) { $1.capitalize }
824 @headers.each do |key, value|
825 buffer << "%s: %s\r\n" %
826 [format_header(key), value]
854 r = Mail::Message.new
858 r[:in_reply_to] = self[:message_id]
859 r[:references] = self[:references]
863 HEADERS = [ :from, :to, :cc, :references, :in_reply_to, :reply_to, :message_id ]
865 def import_headers(m)
867 dashed = format_header(e)
868 @headers[e] = Header.parse(m[dashed])
875 if not $mail_installed
876 puts "WARNING: Install the 'mail' gem, without it support is limited"
878 def self.read(filename)
879 Message.new(File.open(filename, 'rb') { |f| f.read })
883 include SimpleMessage
890 return self if not multipart?
891 return text_part || html_part
895 if mime_type != "text/html"
898 IO.popen("elinks --dump", "w+") do |pipe|
899 pipe.write(decode_body)
911 RUBY_VERSION >= "1.9" ? force_encoding('utf-8') : self
918 call s:search(join(a:000))
924 command -nargs=* NotMuch call s:NotMuch(<f-args>)
926 " vim: set noexpandtab: