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