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