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
62 let s:notmuch_compose_start_insert_default = 1
64 function! s:new_file_buffer(type, fname)
65 exec printf('edit %s', a:fname)
66 execute printf('set filetype=notmuch-%s', a:type)
67 execute printf('set syntax=notmuch-%s', a:type)
68 ruby $curbuf.init(VIM::evaluate('a:type'))
71 function! s:on_compose_delete()
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('%')
90 let lines = getline(5, '$')
93 # Generate proper mail to send
94 text = VIM::evaluate('lines').join("\n")
95 fname = VIM::evaluate('fname')
96 transport = Mail.new(text)
97 transport.message_id = generate_message_id
98 transport.charset = 'utf-8'
99 File.write(fname, transport.to_s)
102 let cmdtxt = g:notmuch_sendmail . ' -t -f ' . s:reply_from . ' < ' . fname
103 let out = system(cmdtxt)
104 let err = v:shell_error
107 echo 'Eeek! unable to send mail'
113 echo 'Mail sent successfully.'
114 call s:kill_this_buffer()
117 function! s:show_next_msg()
119 r, c = $curwin.cursor
120 n = $curbuf.line_number
121 i = $messages.index { |m| n >= m.start && n <= m.end }
125 VIM::command("normal #{m.start}zt")
126 $curwin.cursor = r, c
131 function! s:show_reply()
132 ruby open_reply get_message.mail
133 let b:compose_done = 0
134 call s:set_map(g:notmuch_compose_maps)
135 autocmd BufDelete <buffer> call s:on_compose_delete()
136 if g:notmuch_compose_start_insert
141 function! s:compose()
143 let b:compose_done = 0
144 call s:set_map(g:notmuch_compose_maps)
145 autocmd BufDelete <buffer> call s:on_compose_delete()
146 if g:notmuch_compose_start_insert
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_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()
281 VIM::command("bdelete!")
285 function! s:set_map(maps)
287 for [key, code] in items(a:maps)
288 let cmd = printf(":call <SID>%s<CR>", code)
289 exec printf('nnoremap <buffer> %s %s', key, cmd)
293 function! s:new_buffer(type)
295 setlocal buftype=nofile bufhidden=hide
297 execute printf('set filetype=notmuch-%s', a:type)
298 execute printf('set syntax=notmuch-%s', a:type)
299 ruby $curbuf.init(VIM::evaluate('a:type'))
302 function! s:set_menu_buffer()
303 setlocal nomodifiable
310 function! s:show(thread_id)
311 call s:new_buffer('show')
314 thread_id = VIM::evaluate('a:thread_id')
315 $cur_thread = thread_id
317 $curbuf.render do |b|
318 q = $curbuf.query(get_cur_view)
319 q.sort = Notmuch::SORT_OLDEST_FIRST
320 msgs = q.search_messages
322 m = Mail.read(msg.filename)
323 part = m.find_first_text
324 nm_m = Message.new(msg, m)
326 date_fmt = VIM::evaluate('g:notmuch_datetime_format')
327 date = Time.at(msg.date).strftime(date_fmt)
329 b << "%s %s (%s)" % [msg['from'], date, msg.tags]
330 b << "Subject: %s" % [msg['subject']]
331 b << "To: %s" % msg['to']
332 b << "Cc: %s" % msg['cc']
333 b << "Date: %s" % msg['date']
334 nm_m.body_start = b.count
335 b << "--- %s ---" % part.mime_type
336 part.convert.each_line do |l|
344 $messages.each_with_index do |msg, i|
345 VIM::command("syntax region nmShowMsg#{i}Desc start='\\%%%il' end='\\%%%il' contains=@nmShowMsgDesc" % [msg.start, msg.start + 1])
346 VIM::command("syntax region nmShowMsg#{i}Head start='\\%%%il' end='\\%%%il' contains=@nmShowMsgHead" % [msg.start + 1, msg.body_start])
347 VIM::command("syntax region nmShowMsg#{i}Body start='\\%%%il' end='\\%%%dl' contains=@nmShowMsgBody" % [msg.body_start, msg.end])
350 setlocal nomodifiable
351 call s:set_map(g:notmuch_show_maps)
354 function! s:search_show_thread(mode)
356 mode = VIM::evaluate('a:mode')
360 when 1; $cur_filter = nil
361 when 2; $cur_filter = $cur_search
363 VIM::command("call s:show('#{id}')")
367 function! s:search(search)
368 call s:new_buffer('search')
370 $cur_search = VIM::evaluate('a:search')
371 search_render($cur_search)
373 call s:set_menu_buffer()
374 call s:set_map(g:notmuch_search_maps)
375 autocmd CursorMoved <buffer> call s:show_cursor_moved()
378 function! s:folders_show_search()
380 n = $curbuf.line_number
382 VIM::command("call s:search('#{s}')")
386 function! s:folders()
387 call s:new_buffer('folders')
388 ruby folders_render()
389 call s:set_menu_buffer()
390 call s:set_map(g:notmuch_folders_maps)
395 function! s:set_defaults()
396 if !exists('g:notmuch_date_format')
397 if exists('g:notmuch_rb_date_format')
398 let g:notmuch_date_format = g:notmuch_rb_date_format
400 let g:notmuch_date_format = s:notmuch_date_format_default
404 if !exists('g:notmuch_datetime_format')
405 if exists('g:notmuch_rb_datetime_format')
406 let g:notmuch_datetime_format = g:notmuch_rb_datetime_format
408 let g:notmuch_datetime_format = s:notmuch_datetime_format_default
412 if !exists('g:notmuch_reader')
413 if exists('g:notmuch_rb_reader')
414 let g:notmuch_reader = g:notmuch_rb_reader
416 let g:notmuch_reader = s:notmuch_reader_default
420 if !exists('g:notmuch_sendmail')
421 if exists('g:notmuch_rb_sendmail')
422 let g:notmuch_sendmail = g:notmuch_rb_sendmail
424 let g:notmuch_sendmail = s:notmuch_sendmail_default
428 if !exists('g:notmuch_folders_count_threads')
429 if exists('g:notmuch_rb_count_threads')
430 let g:notmuch_count_threads = g:notmuch_rb_count_threads
432 let g:notmuch_folders_count_threads = s:notmuch_folders_count_threads_default
436 if !exists('g:notmuch_compose_start_insert')
437 let g:notmuch_compose_start_insert = s:notmuch_compose_start_insert_default
440 if !exists('g:notmuch_custom_search_maps') && exists('g:notmuch_rb_custom_search_maps')
441 let g:notmuch_custom_search_maps = g:notmuch_rb_custom_search_maps
444 if !exists('g:notmuch_custom_show_maps') && exists('g:notmuch_rb_custom_show_maps')
445 let g:notmuch_custom_show_maps = g:notmuch_rb_custom_show_maps
448 if exists('g:notmuch_custom_search_maps')
449 call extend(g:notmuch_search_maps, g:notmuch_custom_search_maps)
452 if exists('g:notmuch_custom_show_maps')
453 call extend(g:notmuch_show_maps, g:notmuch_custom_show_maps)
456 if !exists('g:notmuch_folders')
457 if exists('g:notmuch_rb_folders')
458 let g:notmuch_folders = g:notmuch_rb_folders
460 let g:notmuch_folders = s:notmuch_folders_default
465 function! s:NotMuch(...)
466 call s:set_defaults()
479 $email = $email_name = $email_address = nil
484 $mail_installed = defined?(Mail)
486 def get_config_item(item)
488 IO.popen(['notmuch', 'config', 'get', item]) { |out|
495 $db_name = get_config_item('database.path')
496 $email_name = get_config_item('user.name')
497 $email_address = get_config_item('user.primary_email')
498 $email_name = get_config_item('user.name')
499 $email = "%s <%s>" % [$email_name, $email_address]
500 ignore_tags = get_config_item('search.exclude_tags')
501 $exclude_tags = ignore_tags.split("\n")
505 VIM::command("echo '#{s.to_s}'")
509 VIM::command("echo '#{s.inspect}'")
513 # TODO email format, aliases
515 a.gsub!(/[\.@].*/, '')
517 a.gsub!(/ \(.*\)/, '')
522 n = $curbuf.line_number - 1
523 return "thread:%s" % $threads[n]
527 n = $curbuf.line_number
528 return $messages.find { |m| n >= m.start && n <= m.end }
533 return "#{$cur_thread} and (#{$cur_filter})"
539 def generate_message_id
541 random_tag = sprintf('%x%x_%x%x%x',
543 $$, Thread.current.object_id.abs, rand(255))
544 return "<#{random_tag}@#{Socket.gethostname}.notmuch>"
547 def open_compose_helper(lines, cur)
549 'Notmuch-Help: Type in your message here; to help you use these bindings:',
550 'Notmuch-Help: ,s - send the message (Notmuch-Help lines will be removed)',
551 'Notmuch-Help: ,q - abort the message',
554 dir = File.expand_path('~/.notmuch/compose')
555 FileUtils.mkdir_p(dir)
556 Tempfile.open(['nm-', '.mail'], dir) do |f|
561 sig_file = File.expand_path('~/.signature')
562 if File.exists?(sig_file)
564 f.write(File.read(sig_file))
569 cur += help_lines.size + 1
571 VIM::command("let s:reply_from='%s'" % $email_address)
572 VIM::command("call s:new_file_buffer('compose', '#{f.path}')")
573 VIM::command("call cursor(#{cur}, 0)")
578 reply = orig.reply do |m|
581 m.to = [orig[:from].to_s, orig[:to].to_s]
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.present.lines.map { |e| e.chomp }
614 cur = lines.count - 1
616 open_compose_helper(lines, cur)
622 lines << "From: #{$email}"
633 open_compose_helper(lines, cur)
637 $curbuf.render do |b|
638 folders = VIM::evaluate('g:notmuch_folders')
639 count_threads = VIM::evaluate('g:notmuch_folders_count_threads') == 1
641 folders.each do |name, search|
642 q = $curbuf.query(search)
643 $exclude_tags.each { |t|
647 count = count_threads ? q.count_threads : q.count_messages
648 b << "%9d %-20s (%s)" % [count, name, search]
653 def search_render(search)
654 date_fmt = VIM::evaluate('g:notmuch_date_format')
655 q = $curbuf.query(search)
656 q.sort = Notmuch::SORT_NEWEST_FIRST
657 $exclude_tags.each { |t|
663 $render = $curbuf.render_staged(t) do |b, items|
665 authors = e.authors.to_utf8.split(/[,|]/).map { |a| author_filter(a) }.join(",")
666 date = Time.at(e.newest_date).strftime(date_fmt)
667 subject = e.messages.first['subject']
669 subject = Mail::Field.new("Subject: " + subject).to_s
671 subject = subject.force_encoding('utf-8')
673 b << "%-12s %3s %-20.20s | %s (%s)" % [date, e.matched_messages, authors, subject, e.tags]
674 $threads << e.thread_id
679 def do_tag(filter, tags)
680 $curbuf.do_write do |db|
682 q.search_messages.each do |e|
684 tags.split.each do |t|
695 e.tags_to_maildir_flags
704 @db = Notmuch::Database.new($db_name)
715 @queries.delete_if { |q| ! q.destroy! }
721 @db = Notmuch::Database.new($db_name)
725 db = Notmuch::Database.new($db_name, :mode => Notmuch::MODE_READ_WRITE)
735 attr_accessor :start, :body_start, :end
736 attr_reader :message_id, :filename, :mail
738 def initialize(msg, mail)
739 @message_id = msg.message_id
740 @filename = msg.filename
744 mail.import_headers(msg) if not $mail_installed
748 "id:%s" % @message_id
752 "id:%s, file:%s" % [@message_id, @filename]
757 def initialize(buffer, enumerable, block)
759 @enumerable = enumerable
763 @b.render { do_next }
767 @last_render - @b.line_number <= $curwin.height
771 items = @enumerable.take($curwin.height * 2)
772 return if items.empty?
773 @block.call @b, items
774 @last_render = @b.count
785 def render_staged(enumerable, &block)
786 StagedRender.new(self, enumerable, block)
792 (1..old_count).each do
804 class Notmuch::Message
810 # workaround for bug in vim's ruby
818 def self.parse(string)
819 return nil if string.empty?
820 return Header.new(string.split(/,\s+/))
828 def initialize(string = nil)
835 if string =~ /(.*?(\r\n|\n))\2/m
836 head, body = $1, $' || '', $2
838 head, body = string, ''
844 @headers[name.to_sym]
848 @headers[name.to_sym] = value
851 def format_header(value)
852 value.to_s.tr('_', '-').gsub(/(\w+)/) { $1.capitalize }
857 @headers.each do |key, value|
858 buffer << "%s: %s\r\n" %
859 [format_header(key), value]
887 r = Mail::Message.new
891 r[:in_reply_to] = self[:message_id]
892 r[:references] = self[:references]
896 HEADERS = [ :from, :to, :cc, :references, :in_reply_to, :reply_to, :message_id ]
898 def import_headers(m)
900 dashed = format_header(e)
901 @headers[e] = Header.parse(m[dashed])
908 if not $mail_installed
909 puts "WARNING: Install the 'mail' gem, without it support is limited"
911 def self.read(filename)
912 Message.new(File.open(filename, 'rb') { |f| f.read })
916 include SimpleMessage
923 return self if not multipart?
924 return text_part || html_part
928 if mime_type != "text/html"
931 IO.popen(VIM::evaluate('exists("g:notmuch_html_converter") ? ' +
932 'g:notmuch_html_converter : "elinks --dump"'), "w+") do |pipe|
933 pipe.write(decode_body)
943 header.fields.each do |f|
944 buffer << "%s: %s\r\n" % [f.name, f.to_s]
955 RUBY_VERSION >= "1.9" ? force_encoding('utf-8') : self
962 call s:search(join(a:000))
968 command -nargs=* NotMuch call s:NotMuch(<f-args>)
970 " vim: set noexpandtab: