added support for archive command
[notmuch] / vim / plugin / notmuch.vim
1 " notmuch.vim plugin --- run notmuch within vim
2 "
3 " Copyright © Carl Worth
4 "
5 " This file is part of Notmuch.
6 "
7 " Notmuch is free software: you can redistribute it and/or modify it
8 " under the terms of the GNU General Public License as published by
9 " the Free Software Foundation, either version 3 of the License, or
10 " (at your option) any later version.
11 "
12 " Notmuch is distributed in the hope that it will be useful, but
13 " WITHOUT ANY WARRANTY; without even the implied warranty of
14 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 " General Public License for more details.
16 "
17 " You should have received a copy of the GNU General Public License
18 " along with Notmuch.  If not, see <http://www.gnu.org/licenses/>.
19 "
20 " Authors: Bart Trojanowski <bart@jukie.net>
21
22 " --- configuration defaults {{{1
23
24 let s:notmuch_defaults = {
25         \ 'g:notmuch_cmd':                           'notmuch'                    ,
26         \ 'g:notmuch_search_reverse':                1                            ,
27         \ 'g:notmuch_show_fold_signatures':          1                            ,
28         \ 'g:notmuch_show_fold_citations':           1                            ,
29         \
30         \ 'g:notmuch_show_message_begin_regexp':     '^\fmessage{'                ,
31         \ 'g:notmuch_show_message_end_regexp':       '^\fmessage}'                ,
32         \ 'g:notmuch_show_header_begin_regexp':      '^\fheader{'                 ,
33         \ 'g:notmuch_show_header_end_regexp':        '^\fheader}'                 ,
34         \ 'g:notmuch_show_body_begin_regexp':        '^\fbody{'                   ,
35         \ 'g:notmuch_show_body_end_regexp':          '^\fbody}'                   ,
36         \ 'g:notmuch_show_attachment_begin_regexp':  '^\fattachment{'             ,
37         \ 'g:notmuch_show_attachment_end_regexp':    '^\fattachment}'             ,
38         \ 'g:notmuch_show_part_begin_regexp':        '^\fpart{'                   ,
39         \ 'g:notmuch_show_part_end_regexp':          '^\fpart}'                   ,
40         \ 'g:notmuch_show_marker_regexp':            '^\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
41         \
42         \ 'g:notmuch_show_message_parse_regexp':     '\(id:[^ ]*\) depth:\([0-9]*\) filename:\(.*\)$',
43         \ 'g:notmuch_show_tags_regexp':              '(\([^)]*\))$'               ,
44         \
45         \ 'g:notmuch_show_signature_regexp':         '^\(-- \?\|_\+\)$'           ,
46         \ 'g:notmuch_show_signature_lines_max':      12                           ,
47         \
48         \ 'g:notmuch_show_citation_regexp':          '^\s*>'                      ,
49         \ }
50
51 " defaults for g:notmuch_initial_search_words
52 " override with: let g:notmuch_initial_search_words = [ ... ]
53 let s:notmuch_initial_search_words_defaults = [
54         \ 'tag:inbox'
55         \ ]
56
57 " defaults for g:notmuch_show_headers
58 " override with: let g:notmuch_show_headers = [ ... ]
59 let s:notmuch_show_headers_defaults = [
60         \ 'Subject',
61         \ 'From'
62         \ ]
63
64 " --- keyboard mapping definitions {{{1
65
66 " --- --- bindings for search screen {{{2
67 let g:notmuch_search_maps = {
68         \ '<Enter>':    ':call <SID>NM_search_show_thread()<CR>',
69         \ 'a':          ':call <SID>NM_search_archive_thread()<CR>',
70         \ 'f':          ':call <SID>NM_search_filter()<CR>',
71         \ 'm':          ':call <SID>NM_new_mail()<CR>',
72         \ 'o':          ':call <SID>NM_search_toggle_order()<CR>',
73         \ 'r':          ':call <SID>NM_search_reply_to_thread()<CR>',
74         \ 's':          ':call <SID>NM_search_prompt()<CR>',
75         \ 'S':          ':call <SID>NM_search_edit()<CR>',
76         \ 't':          ':call <SID>NM_search_filter_by_tag()<CR>',
77         \ '+':          ':call <SID>NM_search_add_tags([])<CR>',
78         \ '-':          ':call <SID>NM_search_remove_tags([])<CR>',
79         \ '=':          ':call <SID>NM_search_refresh_view()<CR>',
80         \ }
81
82 " --- --- bindings for show screen {{{2
83 let g:notmuch_show_maps = {
84         \ 'q':         ':call <SID>NM_cmd_show_quit()<CR>',
85         \ '<C-N>':     ':call <SID>NM_cmd_show_next()<CR>',
86         \ 'c':         ':call <SID>NM_cmd_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
87         \ 's':         ':call <SID>NM_cmd_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
88         \ }
89
90 " --- implement search screen {{{1
91
92 function! s:NM_cmd_search(words)
93         let cmd = ['search']
94         if g:notmuch_search_reverse
95                 let cmd = cmd + ['--reverse']
96         endif
97         let g:notmuch_current_search_words = a:words
98         let data = s:NM_run(cmd + a:words)
99         "let data = substitute(data, '27/27', '25/27', '')
100         "let data = substitute(data, '\[4/4\]', '[0/4]', '')
101         let lines = split(data, "\n")
102         let disp = copy(lines)
103         call map(disp, 'substitute(v:val, "^thread:\\S* ", "", "")' )
104
105         call <SID>NM_newBuffer('search', join(disp, "\n"))
106         let b:nm_raw_lines = lines
107
108         call <SID>NM_set_map(g:notmuch_search_maps)
109         setlocal cursorline
110         setlocal nowrap
111 endfunction
112
113 " --- --- search screen action functions {{{2
114
115 function! s:NM_search_show_thread()
116         let id = <SID>NM_search_find_thread_id()
117         if id != ''
118                 call <SID>NM_cmd_show([id])
119         endif
120 endfunction
121
122 function! s:NM_search_prompt()
123         " TODO: input() can support completion
124         let text = input('NotMuch Search: ')
125         if strlen(text)
126                 call <SID>NM_cmd_search(split(text))
127         endif
128 endfunction
129
130 function! s:NM_search_edit()
131         " TODO: input() can support completion
132         let text = input('NotMuch Search: ', join(g:notmuch_current_search_words, ' '))
133         if strlen(text)
134                 call <SID>NM_cmd_search(split(text))
135         endif
136 endfunction
137
138 function! s:NM_search_archive_thread()
139         call <SID>NM_add_remove_tags('-', ['inbox'])
140         setlocal modifiable
141         s/(\([^)]*\)\<inbox\>\([^)]*\))$/(\1\2)/
142         setlocal nomodifiable
143         norm j
144 endfunction
145
146 function! s:NM_search_filter()
147         echoe 'Not implemented'
148 endfunction
149
150 function! s:NM_new_mail()
151         echoe 'Not implemented'
152 endfunction
153
154 function! s:NM_search_toggle_order()
155         echoe 'Not implemented'
156 endfunction
157
158 function! s:NM_search_reply_to_thread()
159         echoe 'Not implemented'
160 endfunction
161
162 function! s:NM_search_filter_by_tag()
163         echoe 'Not implemented'
164 endfunction
165
166 function! s:NM_search_add_tags(tags)
167         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
168 endfunction
169
170 function! s:NM_search_remove_tags(tags)
171         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
172 endfunction
173
174 function! s:NM_search_refresh_view()
175         let lno = line('.')
176         call <SID>NM_cmd_search(g:notmuch_current_search_words)
177         " FIXME: should find the line of the thread we were on if possible
178         exec printf('norm %dG', lno)
179 endfunction
180
181 " --- --- search screen helper functions {{{2
182
183 function! s:NM_search_find_thread_id()
184         if !exists('b:nm_raw_lines')
185                 echoe 'no b:nm_raw_lines'
186                 return ''
187         else
188                 let line = line('.')
189                 let info = b:nm_raw_lines[line-1]
190                 let what = split(info, '\s\+')[0]
191                 return what
192         endif
193 endfunction
194
195 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
196         if type(a:intags) != type([]) || len(a:intags) == 0
197                 " TODO: input() can support completion
198                 let text = input(a:prompt)
199                 if !strlen(text)
200                         return
201                 endif
202                 call <SID>NM_add_remove_tags(prefix, split(text, ' '))
203         else
204                 call <SID>NM_add_remove_tags(prefix, a:intags)
205         endif
206         call <SID>NM_search_refresh_view()
207 endfunction
208
209 function! s:NM_add_remove_tags(prefix, tags)
210         let id = <SID>NM_search_find_thread_id()
211         if id == ''
212                 echoe 'Eeek! I couldn''t find the thead id!'
213         endif
214         call map(a:tags, 'a:prefix . v:val')
215         " TODO: handle errors
216         call <SID>NM_run(['tag'] + a:tags + ['--', id])
217 endfunction
218
219 " --- implement show screen {{{1
220
221 function! s:NM_cmd_show(words)
222         let prev_bufnr = bufnr('%')
223         let data = s:NM_run(['show'] + a:words)
224         let lines = split(data, "\n")
225
226         let info = s:NM_cmd_show_parse(lines)
227
228         call <SID>NM_newBuffer('show', join(info['disp'], "\n"))
229         setlocal bufhidden=delete
230         let b:nm_raw_info = info
231         let b:nm_prev_bufnr = prev_bufnr
232
233         call <SID>NM_cmd_show_mkfolds()
234         call <SID>NM_cmd_show_mksyntax()
235         call <SID>NM_set_map(g:notmuch_show_maps)
236         setlocal foldtext=NM_cmd_show_foldtext()
237         setlocal fillchars=
238         setlocal foldcolumn=6
239
240 endfunction
241
242 function! s:NM_cmd_show_quit()
243         exec printf(":buffer %d", b:nm_prev_bufnr)
244 endfunction
245
246 function! s:NM_cmd_show_next()
247         let info = b:nm_raw_info
248         let lnum = line('.')
249         let cnt = 0
250         for msg in info['msgs']
251                 let cnt = cnt + 1
252                 if lnum >= msg['start']
253                         continue
254                 endif
255
256                 exec printf('norm %dG', msg['start'])
257                 norm zz
258                 return
259         endfor
260         norm qj
261         call <SID>NM_search_show_thread()
262 endfunction
263
264 function! s:NM_cmd_show_fold_toggle(key, type, fold)
265         let info = b:nm_raw_info
266         let act = 'open'
267         if a:fold
268                 let act = 'close'
269         endif
270         for fld in info['folds']
271                 if fld[0] == a:type
272                         exec printf('%dfold%s', fld[1], act)
273                 endif
274         endfor
275         exec printf('nnoremap <buffer> %s :call <SID>NM_cmd_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
276 endfunction
277
278
279 " s:NM_cmd_show_parse returns the following dictionary:
280 "    'disp':     lines to display
281 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
282 "    'folds':    fold info arrays [ type, start, end ]
283 "    'foldtext': fold text indexed by start line
284 function! s:NM_cmd_show_parse(inlines)
285         let info = { 'disp': [],       
286                    \ 'msgs': [],       
287                    \ 'folds': [],      
288                    \ 'foldtext': {} }  
289         let msg = {}
290         let hdr = {}
291
292         let in_message = 0
293         let in_header = 0
294         let in_body = 0
295         let in_part = ''
296
297         let body_start = -1
298         let part_start = -1
299
300         let mode_type = ''
301         let mode_start = -1
302
303         let inlnum = 0
304         for line in a:inlines
305                 let inlnum = inlnum + 1
306                 let foldinfo = []
307
308                 if strlen(in_part)
309                         let part_end = 0
310
311                         if match(line, g:notmuch_show_part_end_regexp) != -1
312                                 let part_end = len(info['disp'])
313                         else
314                                 call add(info['disp'], line)
315                         endif
316
317                         if in_part == 'text/plain'
318                                 if !part_end && mode_type == ''
319                                         if match(line, g:notmuch_show_signature_regexp) != -1
320                                                 let mode_type = 'sig'
321                                                 let mode_start = len(info['disp'])
322                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
323                                                 let mode_type = 'cit'
324                                                 let mode_start = len(info['disp'])
325                                         endif
326                                 elseif mode_type == 'cit'
327                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
328                                                 let outlnum = len(info['disp'])
329                                                 let foldinfo = [ mode_type, mode_start, outlnum,
330                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
331                                                 let mode_type = ''
332                                         endif
333                                 elseif mode_type == 'sig'
334                                         let outlnum = len(info['disp'])
335                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
336                                                 echoe 'line ' . outlnum . ' stopped matching'
337                                                 let mode_type = ''
338                                         elseif part_end
339                                                 let foldinfo = [ mode_type, mode_start, outlnum,
340                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
341                                                 let mode_type = ''
342                                         endif
343                                 endif
344                         endif
345
346                         if part_end
347                                 " FIXME: this is a hack for handling two folds being added for one line
348                                 "         we should handle addinga fold in a function
349                                 if len(foldinfo)
350                                         call add(info['folds'], foldinfo[0:2])
351                                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
352                                 endif
353
354                                 let foldinfo = [ 'text', part_start, part_end,
355                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
356                                 let in_part = ''
357                                 call add(info['disp'], '')
358                         endif
359
360                 elseif in_body
361                         if !has_key(msg,'body_start')
362                                 let msg['body_start'] = len(info['disp']) + 1
363                         endif
364                         if match(line, g:notmuch_show_body_end_regexp) != -1
365                                 let body_end = len(info['disp'])
366                                 let foldinfo = [ 'body', body_start, body_end,
367                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
368
369                                 let in_body = 0
370
371                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
372                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
373                                 let in_part = 'unknown'
374                                 if len(m)
375                                         let in_part = m[2]
376                                 endif
377                                 call add(info['disp'],
378                                          \ printf('--- %s ---', in_part))
379                                 let part_start = len(info['disp']) + 1
380                         endif
381
382                 elseif in_header
383                         if in_header == 1
384                                 let msg['descr'] = line
385                                 call add(info['disp'], line)
386                                 let in_header = 2
387                                 let msg['hdr_start'] = len(info['disp']) + 1
388
389                         else
390                                 if match(line, g:notmuch_show_header_end_regexp) != -1
391                                         let msg['header'] = hdr
392                                         let in_header = 0
393                                         let hdr = {}
394                                 else
395                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
396                                         if len(m)
397                                                 let hdr[m[1]] = m[2]
398                                                 if match(g:notmuch_show_headers, m[1]) != -1
399                                                         call add(info['disp'], line)
400                                                 endif
401                                         endif
402                                 endif
403                         endif
404
405                 elseif in_message
406                         if match(line, g:notmuch_show_message_end_regexp) != -1
407                                 let msg['end'] = len(info['disp'])
408                                 call add(info['disp'], '')
409
410                                 let foldinfo = [ 'match', msg['start'], msg['end'],
411                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
412
413                                 call add(info['msgs'], msg)
414                                 let msg = {}
415                                 let in_message = 0
416                                 let in_header = 0
417                                 let in_body = 0
418                                 let in_part = ''
419
420                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
421                                 let in_header = 1
422                                 continue
423
424                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
425                                 let body_start = len(info['disp']) + 1
426                                 let in_body = 1
427                                 continue
428                         endif
429
430                 else
431                         if match(line, g:notmuch_show_message_begin_regexp) != -1
432                                 let msg['start'] = len(info['disp']) + 1
433
434                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
435                                 if len(m)
436                                         let msg['id'] = m[1]
437                                         let msg['depth'] = m[2]
438                                         let msg['filename'] = m[3]
439                                 endif
440
441                                 let in_message = 1
442                         endif
443                 endif
444
445                 if len(foldinfo)
446                         call add(info['folds'], foldinfo[0:2])
447                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
448                 endif
449         endfor
450         return info
451 endfunction
452
453 function! s:NM_cmd_show_mkfolds()
454         let info = b:nm_raw_info
455
456         for afold in info['folds']
457                 exec printf('%d,%dfold', afold[1], afold[2])
458                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
459                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
460                         exec printf('%dfoldclose', afold[1])
461                 else
462                         exec printf('%dfoldopen', afold[1])
463                 endif
464         endfor
465 endfunction
466
467 function! s:NM_cmd_show_mksyntax()
468         let info = b:nm_raw_info
469         let cnt = 0
470         for msg in info['msgs']
471                 let cnt = cnt + 1
472                 let start = msg['start']
473                 let hdr_start = msg['hdr_start']
474                 let body_start = msg['body_start']
475                 let end = msg['end']
476                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
477                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
478                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
479         endfor
480 endfunction
481
482 function! NM_cmd_show_foldtext()
483         let foldtext = b:nm_raw_info['foldtext']
484         return foldtext[v:foldstart]
485 endfunction
486
487
488 " --- notmuch helper functions {{{1
489
490 function! s:NM_newBuffer(ft, content)
491         enew
492         setlocal buftype=nofile readonly modifiable
493         silent put=a:content
494         keepjumps 0d
495         setlocal nomodifiable
496         execute printf('set filetype=notmuch-%s', a:ft)
497         execute printf('set syntax=notmuch-%s', a:ft)
498 endfunction
499
500 function! s:NM_run(args)
501         let cmd = g:notmuch_cmd . ' ' . join(a:args) . '< /dev/null'
502         let out = system(cmd)
503         if v:shell_error
504                 echohl Error
505                 echo substitute(out, '\n*$', '', '')
506                 echohl None
507                 return ''
508         else
509                 return out
510         endif
511 endfunction
512
513 " --- process and set the defaults {{{1
514
515 function! NM_set_defaults(force)
516         for [key, dflt] in items(s:notmuch_defaults)
517                 let cmd = ''
518                 if !a:force && exists(key) && type(dflt) == type(eval(key))
519                         continue
520                 elseif type(dflt) == type(0)
521                         let cmd = printf('let %s = %d', key, dflt)
522                 elseif type(dflt) == type('')
523                         let cmd = printf('let %s = ''%s''', key, dflt)
524                 "elseif type(dflt) == type([])
525                 "        let cmd = printf('let %s = %s', key, string(dflt))
526                 else
527                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
528                                                 \ a:force, key, string(dflt))
529                         continue
530                 endif
531                 exec cmd
532         endfor
533 endfunction
534 call NM_set_defaults(0)
535
536 " for some reason NM_set_defaults() didn't work for arrays...
537 if !exists('g:notmuch_show_headers')
538         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
539 endif
540 if !exists('g:notmuch_initial_search_words')
541         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
542 endif
543
544 " this is the default querry
545 let g:notmuch_current_search_words = g:notmuch_initial_search_words
546
547
548 " --- assign keymaps {{{1
549
550 function! s:NM_set_map(maps)
551         for [key, code] in items(a:maps)
552                 exec printf('nnoremap <buffer> %s %s', key, code)
553         endfor
554 endfunction
555
556 " --- command handler {{{1
557
558 function! NotMuch(args)
559         if !strlen(a:args)
560                 call <SID>NM_cmd_search(g:notmuch_current_search_words)
561                 return
562         endif
563
564         echo "blarg!"
565
566         let words = split(a:args)
567         " TODO: handle commands passed as arguments
568 endfunction
569 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
570         return []
571 endfunction
572
573
574 " --- glue {{{1
575
576 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
577 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
578
579 " --- hacks, only for development :) {{{1
580
581 nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
582
583 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :