]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
b78a638236415f79619d0f1005da5bdaec11c1a8
[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 s: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 s: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_search_remove_tags('inbox')
140         norm j
141 endfunction
142
143 function! s:NM_search_filter()
144         echoe 'Not implemented'
145 endfunction
146
147 function! s:NM_new_mail()
148         echoe 'Not implemented'
149 endfunction
150
151 function! s:NM_search_toggle_order()
152         echoe 'Not implemented'
153 endfunction
154
155 function! s:NM_search_reply_to_thread()
156         echoe 'Not implemented'
157 endfunction
158
159 function! s:NM_search_filter_by_tag()
160         echoe 'Not implemented'
161 endfunction
162
163 function! s:NM_search_add_tags(tags)
164         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
165 endfunction
166
167 function! s:NM_search_remove_tags(tags)
168         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
169 endfunction
170
171 function! s:NM_search_refresh_view()
172         let lno = line('.')
173         call s:NM_cmd_search(g:notmuch_current_search_words)
174         " FIXME: should find the line of the thread we were on if possible
175         exec printf('norm %dG', lno)
176 endfunction
177
178 " --- --- search screen helper functions {{{2
179
180 function! s:NM_search_find_thread_id()
181         if !exists('b:nm_raw_lines')
182                 echoe 'no b:nm_raw_lines'
183                 return ''
184         else
185                 let line = line('.')
186                 let info = b:nm_raw_lines[line-1]
187                 let what = split(info, '\s\+')[0]
188                 return what
189         endif
190 endfunction
191
192 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
193         let id = <SID>NM_search_find_thread_id()
194         if id != ''
195                 if type(a:intags) != type([]) || len(a:intags) == 0
196                         " TODO: input() can support completion
197                         let text = input(a:prompt)
198                         if !strlen(text)
199                                 return
200                         endif
201                         let tags = split(text, ' ')
202                 else
203                         let tags = a:intags
204                 endif
205                 call map(tags, 'a:prefix . v:val')
206                 " TODO: handle errors
207                 call <SID>NM_run(['tag'] + tags + ['--', id])
208                 call <SID>NM_search_refresh_view()
209         endif
210 endfunction
211
212 " --- implement show screen {{{1
213
214 function! s:NM_cmd_show(words)
215         let prev_bufnr = bufnr('%')
216         let data = s:NM_run(['show'] + a:words)
217         let lines = split(data, "\n")
218
219         let info = s:NM_cmd_show_parse(lines)
220
221         call s:NM_newBuffer('show', join(info['disp'], "\n"))
222         setlocal bufhidden=delete
223         let b:nm_raw_info = info
224         let b:nm_prev_bufnr = prev_bufnr
225
226         call s:NM_cmd_show_mkfolds()
227         call s:NM_cmd_show_mksyntax()
228         call <SID>NM_set_map(g:notmuch_show_maps)
229         setlocal foldtext=NM_cmd_show_foldtext()
230         setlocal fillchars=
231         setlocal foldcolumn=6
232
233 endfunction
234
235 function! s:NM_cmd_show_quit()
236         exec printf(":buffer %d", b:nm_prev_bufnr)
237 endfunction
238
239 function! s:NM_cmd_show_next()
240         let info = b:nm_raw_info
241         let lnum = line('.')
242         let cnt = 0
243         for msg in info['msgs']
244                 let cnt = cnt + 1
245                 if lnum >= msg['start']
246                         continue
247                 endif
248
249                 exec printf('norm %dG', msg['start'])
250                 norm zz
251                 return
252         endfor
253         norm qj
254         call <SID>NM_search_show_thread()
255 endfunction
256
257 function! s:NM_cmd_show_fold_toggle(key, type, fold)
258         let info = b:nm_raw_info
259         let act = 'open'
260         if a:fold
261                 let act = 'close'
262         endif
263         for fld in info['folds']
264                 if fld[0] == a:type
265                         exec printf('%dfold%s', fld[1], act)
266                 endif
267         endfor
268         exec printf('nnoremap <buffer> %s :call <SID>NM_cmd_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
269 endfunction
270
271
272 " s:NM_cmd_show_parse returns the following dictionary:
273 "    'disp':     lines to display
274 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
275 "    'folds':    fold info arrays [ type, start, end ]
276 "    'foldtext': fold text indexed by start line
277 function! s:NM_cmd_show_parse(inlines)
278         let info = { 'disp': [],       
279                    \ 'msgs': [],       
280                    \ 'folds': [],      
281                    \ 'foldtext': {} }  
282         let msg = {}
283         let hdr = {}
284
285         let in_message = 0
286         let in_header = 0
287         let in_body = 0
288         let in_part = ''
289
290         let body_start = -1
291         let part_start = -1
292
293         let mode_type = ''
294         let mode_start = -1
295
296         let inlnum = 0
297         for line in a:inlines
298                 let inlnum = inlnum + 1
299                 let foldinfo = []
300
301                 if strlen(in_part)
302                         let part_end = 0
303
304                         if match(line, g:notmuch_show_part_end_regexp) != -1
305                                 let part_end = len(info['disp'])
306                         else
307                                 call add(info['disp'], line)
308                         endif
309
310                         if in_part == 'text/plain'
311                                 if !part_end && mode_type == ''
312                                         if match(line, g:notmuch_show_signature_regexp) != -1
313                                                 let mode_type = 'sig'
314                                                 let mode_start = len(info['disp'])
315                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
316                                                 let mode_type = 'cit'
317                                                 let mode_start = len(info['disp'])
318                                         endif
319                                 elseif mode_type == 'cit'
320                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
321                                                 let outlnum = len(info['disp'])
322                                                 let foldinfo = [ mode_type, mode_start, outlnum,
323                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
324                                                 let mode_type = ''
325                                         endif
326                                 elseif mode_type == 'sig'
327                                         let outlnum = len(info['disp'])
328                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
329                                                 echoe 'line ' . outlnum . ' stopped matching'
330                                                 let mode_type = ''
331                                         elseif part_end
332                                                 let foldinfo = [ mode_type, mode_start, outlnum,
333                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
334                                                 let mode_type = ''
335                                         endif
336                                 endif
337                         endif
338
339                         if part_end
340                                 " FIXME: this is a hack for handling two folds being added for one line
341                                 "         we should handle addinga fold in a function
342                                 if len(foldinfo)
343                                         call add(info['folds'], foldinfo[0:2])
344                                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
345                                 endif
346
347                                 let foldinfo = [ 'text', part_start, part_end,
348                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
349                                 let in_part = ''
350                                 call add(info['disp'], '')
351                         endif
352
353                 elseif in_body
354                         if !has_key(msg,'body_start')
355                                 let msg['body_start'] = len(info['disp']) + 1
356                         endif
357                         if match(line, g:notmuch_show_body_end_regexp) != -1
358                                 let body_end = len(info['disp'])
359                                 let foldinfo = [ 'body', body_start, body_end,
360                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
361
362                                 let in_body = 0
363
364                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
365                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
366                                 let in_part = 'unknown'
367                                 if len(m)
368                                         let in_part = m[2]
369                                 endif
370                                 call add(info['disp'],
371                                          \ printf('--- %s ---', in_part))
372                                 let part_start = len(info['disp']) + 1
373                         endif
374
375                 elseif in_header
376                         if in_header == 1
377                                 let msg['descr'] = line
378                                 call add(info['disp'], line)
379                                 let in_header = 2
380                                 let msg['hdr_start'] = len(info['disp']) + 1
381
382                         else
383                                 if match(line, g:notmuch_show_header_end_regexp) != -1
384                                         let msg['header'] = hdr
385                                         let in_header = 0
386                                         let hdr = {}
387                                 else
388                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
389                                         if len(m)
390                                                 let hdr[m[1]] = m[2]
391                                                 if match(g:notmuch_show_headers, m[1]) != -1
392                                                         call add(info['disp'], line)
393                                                 endif
394                                         endif
395                                 endif
396                         endif
397
398                 elseif in_message
399                         if match(line, g:notmuch_show_message_end_regexp) != -1
400                                 let msg['end'] = len(info['disp'])
401                                 call add(info['disp'], '')
402
403                                 let foldinfo = [ 'match', msg['start'], msg['end'],
404                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
405
406                                 call add(info['msgs'], msg)
407                                 let msg = {}
408                                 let in_message = 0
409                                 let in_header = 0
410                                 let in_body = 0
411                                 let in_part = ''
412
413                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
414                                 let in_header = 1
415                                 continue
416
417                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
418                                 let body_start = len(info['disp']) + 1
419                                 let in_body = 1
420                                 continue
421                         endif
422
423                 else
424                         if match(line, g:notmuch_show_message_begin_regexp) != -1
425                                 let msg['start'] = len(info['disp']) + 1
426
427                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
428                                 if len(m)
429                                         let msg['id'] = m[1]
430                                         let msg['depth'] = m[2]
431                                         let msg['filename'] = m[3]
432                                 endif
433
434                                 let in_message = 1
435                         endif
436                 endif
437
438                 if len(foldinfo)
439                         call add(info['folds'], foldinfo[0:2])
440                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
441                 endif
442         endfor
443         return info
444 endfunction
445
446 function! s:NM_cmd_show_mkfolds()
447         let info = b:nm_raw_info
448
449         for afold in info['folds']
450                 exec printf('%d,%dfold', afold[1], afold[2])
451                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
452                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
453                         exec printf('%dfoldclose', afold[1])
454                 else
455                         exec printf('%dfoldopen', afold[1])
456                 endif
457         endfor
458 endfunction
459
460 function! s:NM_cmd_show_mksyntax()
461         let info = b:nm_raw_info
462         let cnt = 0
463         for msg in info['msgs']
464                 let cnt = cnt + 1
465                 let start = msg['start']
466                 let hdr_start = msg['hdr_start']
467                 let body_start = msg['body_start']
468                 let end = msg['end']
469                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
470                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
471                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
472         endfor
473 endfunction
474
475 function! NM_cmd_show_foldtext()
476         let foldtext = b:nm_raw_info['foldtext']
477         return foldtext[v:foldstart]
478 endfunction
479
480
481 " --- notmuch helper functions {{{1
482
483 function! s:NM_newBuffer(ft, content)
484         enew
485         setlocal buftype=nofile readonly modifiable
486         silent put=a:content
487         keepjumps 0d
488         setlocal nomodifiable
489         execute printf('set filetype=notmuch-%s', a:ft)
490         execute printf('set syntax=notmuch-%s', a:ft)
491 endfunction
492
493 function! s:NM_run(args)
494         let cmd = g:notmuch_cmd . ' ' . join(a:args) . '< /dev/null'
495         let out = system(cmd)
496         if v:shell_error
497                 echohl Error
498                 echo substitute(out, '\n*$', '', '')
499                 echohl None
500                 return ''
501         else
502                 return out
503         endif
504 endfunction
505
506 " --- process and set the defaults {{{1
507
508 function! NM_set_defaults(force)
509         for [key, dflt] in items(s:notmuch_defaults)
510                 let cmd = ''
511                 if !a:force && exists(key) && type(dflt) == type(eval(key))
512                         continue
513                 elseif type(dflt) == type(0)
514                         let cmd = printf('let %s = %d', key, dflt)
515                 elseif type(dflt) == type('')
516                         let cmd = printf('let %s = ''%s''', key, dflt)
517                 "elseif type(dflt) == type([])
518                 "        let cmd = printf('let %s = %s', key, string(dflt))
519                 else
520                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
521                                                 \ a:force, key, string(dflt))
522                         continue
523                 endif
524                 exec cmd
525         endfor
526 endfunction
527 call NM_set_defaults(0)
528
529 " for some reason NM_set_defaults() didn't work for arrays...
530 if !exists('g:notmuch_show_headers')
531         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
532 endif
533 if !exists('g:notmuch_initial_search_words')
534         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
535 endif
536
537 " this is the default querry
538 let g:notmuch_current_search_words = g:notmuch_initial_search_words
539
540
541 " --- assign keymaps {{{1
542
543 function! s:NM_set_map(maps)
544         for [key, code] in items(a:maps)
545                 exec printf('nnoremap <buffer> %s %s', key, code)
546         endfor
547 endfunction
548
549 " --- command handler {{{1
550
551 function! NotMuch(args)
552         if !strlen(a:args)
553                 call s:NM_cmd_search(g:notmuch_current_search_words)
554                 return
555         endif
556
557         echo "blarg!"
558
559         let words = split(a:args)
560         " TODO: handle commands passed as arguments
561 endfunction
562 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
563         return []
564 endfunction
565
566
567 " --- glue {{{1
568
569 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
570 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
571
572 " --- hacks, only for development :) {{{1
573
574 nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
575
576 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :