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