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 \ 'r': 'show_reply()',
39 \ '<Tab>': 'show_next_msg()',
42 let g:notmuch_rb_compose_maps = {
43 \ ',s': 'compose_send()',
44 \ ',q': 'compose_quit()',
47 let s:notmuch_rb_folders_default = [
48 \ [ 'new', 'tag:inbox and tag:unread' ],
49 \ [ 'inbox', 'tag:inbox' ],
50 \ [ 'unread', 'tag:unread' ],
53 let s:notmuch_rb_date_format_default = '%d.%m.%y'
54 let s:notmuch_rb_datetime_format_default = '%d.%m.%y %H:%M:%S'
55 let s:notmuch_rb_reader_default = 'mutt -f %s'
56 let s:notmuch_rb_sendmail_default = 'sendmail'
57 let s:notmuch_rb_folders_count_threads_default = 0
59 if !exists('g:notmuch_rb_date_format')
60 let g:notmuch_rb_date_format = s:notmuch_rb_date_format_default
63 if !exists('g:notmuch_rb_datetime_format')
64 let g:notmuch_rb_datetime_format = s:notmuch_rb_datetime_format_default
67 if !exists('g:notmuch_rb_reader')
68 let g:notmuch_rb_reader = s:notmuch_rb_reader_default
71 if !exists('g:notmuch_rb_sendmail')
72 let g:notmuch_rb_sendmail = s:notmuch_rb_sendmail_default
75 if !exists('g:notmuch_rb_folders_count_threads')
76 let g:notmuch_rb_folders_count_threads = s:notmuch_rb_folders_count_threads_default
79 function! s:new_file_buffer(type, fname)
80 exec printf('edit %s', a:fname)
81 execute printf('set filetype=notmuch-%s', a:type)
82 execute printf('set syntax=notmuch-%s', a:type)
83 ruby $curbuf.init(VIM::evaluate('a:type'))
84 ruby $buf_queue.push($curbuf.number)
87 function! s:compose_unload()
91 if input('[s]end/[q]uit? ') =~ '^s'
98 function! s:compose_quit()
99 let b:compose_done = 1
100 call s:kill_this_buffer()
103 function! s:compose_send()
104 let b:compose_done = 1
105 let fname = expand('%')
111 let cmdtxt = g:notmuch_sendmail . ' -t -f ' . s:reply_from . ' < ' . fname
112 let out = system(cmdtxt)
113 let err = v:shell_error
118 echo 'Eeek! unable to send mail'
124 echo 'Mail sent successfully.'
125 call s:kill_this_buffer()
128 function! s:show_next_msg()
130 r, c = $curwin.cursor
131 n = $curbuf.line_number
132 i = $messages.index { |m| n >= m.start && n <= m.end }
136 VIM::command("normal #{m.start}zt")
137 $curwin.cursor = r, c
142 function! s:show_reply()
143 ruby open_reply get_message.mail
144 let b:compose_done = 0
145 call s:set_map(g:notmuch_rb_compose_maps)
146 autocmd BufUnload <buffer> call s:compose_unload()
150 function! s:show_info()
151 ruby vim_puts get_message.inspect
154 function! s:show_extract_msg()
157 m.mail.attachments.each do |a|
158 File.open(a.filename, 'w') do |f|
159 f.write a.body.decoded
160 print "Extracted '#{a.filename}'"
166 function! s:show_open_msg()
169 mbox = File.expand_path('~/.notmuch/vim_mbox')
170 cmd = VIM::evaluate('g:notmuch_rb_reader') % mbox
171 system "notmuch show --format=mbox id:#{m.message_id} > #{mbox} && #{cmd}"
175 function! s:show_save_msg()
176 let file = input('File name: ')
178 file = VIM::evaluate('file')
180 system "notmuch show --format=mbox id:#{m.message_id} > #{file}"
184 function! s:show_tag(intags)
186 let tags = input('tags: ')
190 ruby do_tag(get_cur_view, VIM::evaluate('l:tags'))
191 call s:show_next_thread()
194 function! s:search_search_prompt()
195 let text = input('Search: ')
198 $cur_search = VIM::evaluate('text')
200 search_render($cur_search)
202 setlocal nomodifiable
205 function! s:search_info()
206 ruby vim_puts get_thread_id
209 function! s:search_refresh()
212 ruby search_render($cur_search)
213 setlocal nomodifiable
216 function! s:search_tag(intags)
218 let tags = input('tags: ')
222 ruby do_tag(get_thread_id, VIM::evaluate('l:tags'))
226 function! s:folders_search_prompt()
227 let text = input('Search: ')
231 function! s:folders_refresh()
234 ruby folders_render()
235 setlocal nomodifiable
240 function! s:show_cursor_moved()
243 VIM::command('setlocal modifiable')
245 VIM::command('setlocal nomodifiable')
250 function! s:show_next_thread()
251 call s:kill_this_buffer()
252 if line('.') != line('$')
254 call s:search_show_thread(0)
256 echo 'No more messages.'
260 function! s:kill_this_buffer()
266 VIM::command("buffer #{b}") if b
270 function! s:set_map(maps)
272 for [key, code] in items(a:maps)
273 let cmd = printf(":call <SID>%s<CR>", code)
274 exec printf('nnoremap <buffer> %s %s', key, cmd)
278 function! s:new_buffer(type)
280 setlocal buftype=nofile bufhidden=hide
282 execute printf('set filetype=notmuch-%s', a:type)
283 execute printf('set syntax=notmuch-%s', a:type)
284 ruby $curbuf.init(VIM::evaluate('a:type'))
285 ruby $buf_queue.push($curbuf.number)
288 function! s:set_menu_buffer()
289 setlocal nomodifiable
296 function! s:show(thread_id)
297 call s:new_buffer('show')
300 thread_id = VIM::evaluate('a:thread_id')
301 $cur_thread = thread_id
303 $curbuf.render do |b|
304 q = $curbuf.query(get_cur_view)
306 msgs = q.search_messages
308 m = Mail.read(msg.filename)
309 part = m.find_first_text
310 nm_m = Message.new(msg, m)
312 date_fmt = VIM::evaluate('g:notmuch_rb_datetime_format')
313 date = Time.at(msg.date).strftime(date_fmt)
315 b << "%s %s (%s)" % [msg['from'], date, msg.tags]
316 b << "Subject: %s" % [msg['subject']]
317 b << "To: %s" % msg['to']
318 b << "Cc: %s" % msg['cc']
319 b << "Date: %s" % msg['date']
320 nm_m.body_start = b.count
321 b << "--- %s ---" % part.mime_type
322 part.convert.each_line do |l|
330 $messages.each_with_index do |msg, i|
331 VIM::command("syntax region nmShowMsg#{i}Desc start='\\%%%il' end='\\%%%il' contains=@nmShowMsgDesc" % [msg.start, msg.start + 1])
332 VIM::command("syntax region nmShowMsg#{i}Head start='\\%%%il' end='\\%%%il' contains=@nmShowMsgHead" % [msg.start + 1, msg.body_start])
333 VIM::command("syntax region nmShowMsg#{i}Body start='\\%%%il' end='\\%%%dl' contains=@nmShowMsgBody" % [msg.body_start, msg.end])
336 setlocal nomodifiable
337 call s:set_map(g:notmuch_rb_show_maps)
340 function! s:search_show_thread(mode)
342 mode = VIM::evaluate('a:mode')
346 when 1; $cur_filter = nil
347 when 2; $cur_filter = $cur_search
349 VIM::command("call s:show('#{id}')")
353 function! s:search(search)
354 call s:new_buffer('search')
356 $cur_search = VIM::evaluate('a:search')
357 search_render($cur_search)
359 call s:set_menu_buffer()
360 call s:set_map(g:notmuch_rb_search_maps)
361 autocmd CursorMoved <buffer> call s:show_cursor_moved()
364 function! s:folders_show_search()
366 n = $curbuf.line_number
368 VIM::command("call s:search('#{s}')")
372 function! s:folders()
373 call s:new_buffer('folders')
374 ruby folders_render()
375 call s:set_menu_buffer()
376 call s:set_map(g:notmuch_rb_folders_maps)
381 function! s:set_defaults()
382 if exists('g:notmuch_rb_custom_search_maps')
383 call extend(g:notmuch_rb_search_maps, g:notmuch_rb_custom_search_maps)
386 if exists('g:notmuch_rb_custom_show_maps')
387 call extend(g:notmuch_rb_show_maps, g:notmuch_rb_custom_show_maps)
390 " TODO for now lets check the old folders too
391 if !exists('g:notmuch_rb_folders')
392 if exists('g:notmuch_folders')
393 let g:notmuch_rb_folders = g:notmuch_folders
395 let g:notmuch_rb_folders = s:notmuch_rb_folders_default
400 function! s:NotMuch()
401 call s:set_defaults()
419 $mail_installed = defined?(Mail)
423 config = ENV['NOTMUCH_CONFIG'] || '~/.notmuch-config'
424 File.open(File.expand_path(config)).each do |l|
431 key = "%s.%s" % [group, $1]
437 $db_name = $config['database.path']
438 $email_address = "%s <%s>" % [$config['user.name'], $config['user.primary_email']]
442 VIM::command("echo '#{s.to_s}'")
446 VIM::command("echo '#{s.inspect}'")
450 # TODO email format, aliases
452 a.gsub!(/[\.@].*/, '')
454 a.gsub!(/ \(.*\)/, '')
459 n = $curbuf.line_number - 1
460 return "thread:%s" % $threads[n]
464 n = $curbuf.line_number
465 return $messages.find { |m| n >= m.start && n <= m.end }
470 return "#{$cur_thread} and (#{$cur_filter})"
478 'Notmuch-Help: Type in your message here; to help you use these bindings:',
479 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
480 'Notmuch-Help: ,q - abort the message',
482 reply = orig.reply do |m|
485 m.to = [orig[:from].to_s, orig[:to].to_s]
488 m.from = $email_address
490 m.content_transfer_encoding = '7bit'
493 dir = File.expand_path('~/.notmuch/compose')
494 FileUtils.mkdir_p(dir)
495 Tempfile.open(['nm-', '.mail'], dir) do |f|
503 addr = Mail::Address.new(orig[:from].value)
505 name = addr.local + "@" if name.nil? && !addr.local.nil?
509 name = "somebody" if name.nil?
511 body_lines << "%s wrote:" % name
512 part = orig.find_first_text
513 part.convert.each_line do |l|
514 body_lines << "> %s" % l.chomp
520 reply.body = body_lines.join("\n")
522 lines += reply.to_s.lines.map { |e| e.chomp }
525 old_count = lines.count - 1
529 sig_file = File.expand_path('~/.signature')
530 if File.exists?(sig_file)
532 f.write(File.read(sig_file))
537 VIM::command("let s:reply_from='%s'" % reply.from.first.to_s)
538 VIM::command("call s:new_file_buffer('compose', '#{f.path}')")
539 VIM::command("call cursor(#{old_count}, 0)")
544 $curbuf.render do |b|
545 folders = VIM::evaluate('g:notmuch_rb_folders')
546 count_threads = VIM::evaluate('g:notmuch_rb_folders_count_threads')
548 folders.each do |name, search|
549 q = $curbuf.query(search)
551 count = count_threads ? q.search_threads.count : q.search_messages.count
552 b << "%9d %-20s (%s)" % [count, name, search]
557 def search_render(search)
558 date_fmt = VIM::evaluate('g:notmuch_rb_date_format')
559 q = $curbuf.query(search)
563 $render = $curbuf.render_staged(t) do |b, items|
565 authors = e.authors.to_utf8.split(/[,|]/).map { |a| author_filter(a) }.join(",")
566 date = Time.at(e.newest_date).strftime(date_fmt)
568 subject = Mail::Field.new("Subject: " + e.subject).to_s
570 subject = e.subject.force_encoding('utf-8')
572 b << "%-12s %3s %-20.20s | %s (%s)" % [date, e.matched_messages, authors, subject, e.tags]
573 $threads << e.thread_id
578 def do_tag(filter, tags)
579 $curbuf.do_write do |db|
581 q.search_messages.each do |e|
583 tags.split.each do |t|
594 e.tags_to_maildir_flags
603 @db = Notmuch::Database.new($db_name)
614 @queries.delete_if { |q| ! q.destroy! }
620 @db = Notmuch::Database.new($db_name)
624 db = Notmuch::Database.new($db_name, :mode => Notmuch::MODE_READ_WRITE)
634 attr_accessor :start, :body_start, :end
635 attr_reader :message_id, :filename, :mail
637 def initialize(msg, mail)
638 @message_id = msg.message_id
639 @filename = msg.filename
643 mail.import_headers(msg) if not $mail_installed
647 "id:%s" % @message_id
651 "id:%s, file:%s" % [@message_id, @filename]
656 def initialize(buffer, enumerable, block)
658 @enumerable = enumerable
662 @b.render { do_next }
666 @last_render - @b.line_number <= $curwin.height
670 items = @enumerable.take($curwin.height * 2)
671 return if items.empty?
672 @block.call @b, items
673 @last_render = @b.count
684 def render_staged(enumerable, &block)
685 StagedRender.new(self, enumerable, block)
691 (1..old_count).each do
703 class Notmuch::Message
709 # workaround for bug in vim's ruby
717 def self.parse(string)
718 return nil if string.empty?
719 return Header.new(string.split(/,\s+/))
727 def initialize(string = nil)
734 if string =~ /(.*?(\r\n|\n))\2/m
735 head, body = $1, $' || '', $2
737 head, body = string, ''
743 @headers[name.to_sym]
747 @headers[name.to_sym] = value
750 def format_header(value)
751 value.to_s.tr('_', '-').gsub(/(\w+)/) { $1.capitalize }
756 @headers.each do |key, value|
757 buffer << "%s: %s\r\n" %
758 [format_header(key), value]
786 r = Mail::Message.new
790 r[:in_reply_to] = self[:message_id]
791 r[:references] = self[:references]
795 HEADERS = [ :from, :to, :cc, :references, :in_reply_to, :reply_to, :message_id ]
797 def import_headers(m)
799 dashed = format_header(e)
800 @headers[e] = Header.parse(m[dashed])
807 if not $mail_installed
808 puts "WARNING: Install the 'mail' gem, without it support is limited"
810 def self.read(filename)
811 Message.new(File.open(filename, 'rb') { |f| f.read })
815 include SimpleMessage
822 return self if not multipart?
823 return text_part || html_part
827 if mime_type != "text/html"
830 IO.popen("elinks --dump", "w+") do |pipe|
831 pipe.write(decode_body)
843 RUBY_VERSION >= "1.9" ? force_encoding('utf-8') : self
852 command NotMuch :call s:NotMuch()
854 " vim: set noexpandtab: