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