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