94eb0bbab2b9ea76e06d21022ee4d75ab52704c4
[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 s:notmuch_show_fold_signatures         = 1
57 let s: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 endfunction
117
118 function! s:NM_cmd_show_next()
119         let info = b:nm_raw_info
120         let lnum = line('.')
121         let cnt = 0
122         for msg in info['msgs']
123                 let cnt = cnt + 1
124                 if lnum >= msg['start']
125                         continue
126                 endif
127
128                 exec printf('norm %dG', msg['start'])
129                 norm zz
130                 return
131         endfor
132         norm qj
133         call <SID>NM_search_display()
134 endfunction
135
136 " s:NM_cmd_show_parse returns the following dictionary:
137 "    'disp':     lines to display
138 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
139 "    'folds':    fold info arrays [ type, start, end ]
140 "    'foldtext': fold text indexed by start line
141 function! s:NM_cmd_show_parse(inlines)
142         let info = { 'disp': [],       
143                    \ 'msgs': [],       
144                    \ 'folds': [],      
145                    \ 'foldtext': {} }  
146         let msg = {}
147         let hdr = {}
148
149         let in_message = 0
150         let in_header = 0
151         let in_body = 0
152         let in_part = ''
153
154         let body_start = -1
155         let part_start = -1
156
157         let mode_type = ''
158         let mode_start = -1
159
160         let inlnum = 0
161         for line in a:inlines
162                 let inlnum = inlnum + 1
163                 let foldinfo = []
164
165                 if strlen(in_part)
166                         let part_end = 0
167
168                         if match(line, s:notmuch_show_part_end_regexp) != -1
169                                 let part_end = len(info['disp'])
170                         else
171                                 call add(info['disp'], line)
172                         endif
173
174                         if in_part == 'text/plain'
175                                 if !part_end && mode_type == ''
176                                         if match(line, s:notmuch_show_signature_regexp) != -1
177                                                 let mode_type = 'sig'
178                                                 let mode_start = len(info['disp'])
179                                         elseif match(line, s:notmuch_show_citation_regexp) != -1
180                                                 let mode_type = 'cit'
181                                                 let mode_start = len(info['disp'])
182                                         endif
183                                 elseif mode_type == 'cit'
184                                         if part_end || match(line, s:notmuch_show_citation_regexp) == -1
185                                                 let outlnum = len(info['disp']) -1
186                                                 let foldinfo = [ mode_type, mode_start, outlnum,
187                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
188                                                 let mode_type = ''
189                                         endif
190                                 elseif mode_type == 'sig'
191                                         let outlnum = len(info['disp'])
192                                         if (outlnum - mode_start) > s:notmuch_show_signature_lines_max
193                                                 echoe 'line ' . outlnum . ' stopped matching'
194                                                 let mode_type = ''
195                                         elseif part_end
196                                                 let foldinfo = [ mode_type, mode_start, outlnum,
197                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
198                                                 let mode_type = ''
199                                         endif
200                                 endif
201                         endif
202
203                         if part_end
204                                 " FIXME: this is a hack for handling two folds being added for one line
205                                 "         we should handle addinga fold in a function
206                                 if len(foldinfo)
207                                         call add(info['folds'], foldinfo[0:2])
208                                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
209                                 endif
210
211                                 let foldinfo = [ 'text', part_start, part_end,
212                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
213                                 let in_part = ''
214                                 call add(info['disp'], '')
215                         endif
216
217                 elseif in_body
218                         if !has_key(msg,'body_start')
219                                 let msg['body_start'] = len(info['disp']) + 1
220                         endif
221                         if match(line, s:notmuch_show_body_end_regexp) != -1
222                                 let body_end = len(info['disp'])
223                                 let foldinfo = [ 'body', body_start, body_end,
224                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
225
226                                 let in_body = 0
227
228                         elseif match(line, s:notmuch_show_part_begin_regexp) != -1
229                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
230                                 let in_part = 'unknown'
231                                 if len(m)
232                                         let in_part = m[2]
233                                 endif
234                                 call add(info['disp'],
235                                          \ printf('--- %s ---', in_part))
236                                 let part_start = len(info['disp']) + 1
237                         endif
238
239                 elseif in_header
240                         if in_header == 1
241                                 let msg['descr'] = line
242                                 call add(info['disp'], line)
243                                 let in_header = 2
244                                 let msg['hdr_start'] = len(info['disp']) + 1
245
246                         else
247                                 if match(line, s:notmuch_show_header_end_regexp) != -1
248                                         let msg['header'] = hdr
249                                         let in_header = 0
250                                         let hdr = {}
251                                 else
252                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
253                                         if len(m)
254                                                 let hdr[m[1]] = m[2]
255                                                 if match(s:notmuch_show_headers, m[1]) != -1
256                                                         call add(info['disp'], line)
257                                                 endif
258                                         endif
259                                 endif
260                         endif
261
262                 elseif in_message
263                         if match(line, s:notmuch_show_message_end_regexp) != -1
264                                 let msg['end'] = len(info['disp'])
265                                 call add(info['disp'], '')
266
267                                 let foldinfo = [ 'match', msg['start'], msg['end'],
268                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
269
270                                 call add(info['msgs'], msg)
271                                 let msg = {}
272                                 let in_message = 0
273                                 let in_header = 0
274                                 let in_body = 0
275                                 let in_part = ''
276
277                         elseif match(line, s:notmuch_show_header_begin_regexp) != -1
278                                 let in_header = 1
279                                 continue
280
281                         elseif match(line, s:notmuch_show_body_begin_regexp) != -1
282                                 let body_start = len(info['disp']) + 1
283                                 let in_body = 1
284                                 continue
285                         endif
286
287                 else
288                         if match(line, s:notmuch_show_message_begin_regexp) != -1
289                                 let msg['start'] = len(info['disp']) + 1
290
291                                 let m = matchlist(line, s:notmuch_show_message_parse_regexp)
292                                 if len(m)
293                                         let msg['id'] = m[1]
294                                         let msg['depth'] = m[2]
295                                         let msg['filename'] = m[3]
296                                 endif
297
298                                 let in_message = 1
299                         endif
300                 endif
301
302                 if len(foldinfo)
303                         call add(info['folds'], foldinfo[0:2])
304                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
305                 endif
306         endfor
307         return info
308 endfunction
309
310 function! s:NM_cmd_show_mkfolds()
311         let info = b:nm_raw_info
312
313         for afold in info['folds']
314                 exec printf('%d,%dfold', afold[1], afold[2])
315                 if (afold[0] == 'sig' && s:notmuch_show_fold_signatures)
316                  \ || (afold[0] == 'cit' && s:notmuch_show_fold_citations)
317                         exec printf('%dfoldclose', afold[1])
318                 else
319                         exec printf('%dfoldopen', afold[1])
320                 endif
321         endfor
322 endfunction
323
324 function! s:NM_cmd_show_mksyntax()
325         let info = b:nm_raw_info
326         let cnt = 0
327         for msg in info['msgs']
328                 let cnt = cnt + 1
329                 let start = msg['start']
330                 let hdr_start = msg['hdr_start']
331                 let body_start = msg['body_start']
332                 let end = msg['end']
333                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
334                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
335                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
336         endfor
337 endfunction
338
339 function! NM_cmd_show_foldtext()
340         let foldtext = b:nm_raw_info['foldtext']
341         return foldtext[v:foldstart]
342 endfunction
343
344
345 " --- helper functions
346
347 function! s:NM_newBuffer(ft, content)
348         enew
349         setlocal buftype=nofile readonly modifiable
350         silent put=a:content
351         keepjumps 0d
352         setlocal nomodifiable
353         execute printf('set filetype=notmuch-%s', a:ft)
354         execute printf('set syntax=notmuch-%s', a:ft)
355 endfunction
356
357 function! s:NM_run(args)
358         let cmd = g:notmuch_cmd . ' ' . join(a:args) . '< /dev/null'
359         let out = system(cmd)
360         if v:shell_error
361                 echohl Error
362                 echo substitute(out, '\n*$', '', '')
363                 echohl None
364                 return ''
365         else
366                 return out
367         endif
368 endfunction
369
370
371 " --- command handler
372
373 function! NotMuch(args)
374         if !strlen(a:args)
375                 call s:NM_cmd_search(['tag:inbox'])
376                 return
377         endif
378
379         echo "blarg!"
380
381         let words = split(a:args)
382         " TODO: handle commands passed as arguments
383 endfunction
384 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
385         return []
386 endfunction
387
388
389 " --- glue
390
391 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
392 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
393
394 " --- hacks, only for development :)
395
396 nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>