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