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