remove some debug code from NM_cmd_search()
[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         \
27         \ 'g:notmuch_search_newest_first':           1                            ,
28         \ 'g:notmuch_search_from_column_width':      20                           ,
29         \
30         \ 'g:notmuch_show_fold_signatures':          1                            ,
31         \ 'g:notmuch_show_fold_citations':           1                            ,
32         \ 'g:notmuch_show_fold_bodies':              0                            ,
33         \ 'g:notmuch_show_fold_headers':             1                            ,
34         \
35         \ 'g:notmuch_show_message_begin_regexp':     '^\fmessage{'                ,
36         \ 'g:notmuch_show_message_end_regexp':       '^\fmessage}'                ,
37         \ 'g:notmuch_show_header_begin_regexp':      '^\fheader{'                 ,
38         \ 'g:notmuch_show_header_end_regexp':        '^\fheader}'                 ,
39         \ 'g:notmuch_show_body_begin_regexp':        '^\fbody{'                   ,
40         \ 'g:notmuch_show_body_end_regexp':          '^\fbody}'                   ,
41         \ 'g:notmuch_show_attachment_begin_regexp':  '^\fattachment{'             ,
42         \ 'g:notmuch_show_attachment_end_regexp':    '^\fattachment}'             ,
43         \ 'g:notmuch_show_part_begin_regexp':        '^\fpart{'                   ,
44         \ 'g:notmuch_show_part_end_regexp':          '^\fpart}'                   ,
45         \ 'g:notmuch_show_marker_regexp':            '^\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
46         \
47         \ 'g:notmuch_show_message_parse_regexp':     '\(id:[^ ]*\) depth:\([0-9]*\) filename:\(.*\)$',
48         \ 'g:notmuch_show_tags_regexp':              '(\([^)]*\))$'               ,
49         \
50         \ 'g:notmuch_show_signature_regexp':         '^\(-- \?\|_\+\)$'           ,
51         \ 'g:notmuch_show_signature_lines_max':      12                           ,
52         \
53         \ 'g:notmuch_show_citation_regexp':          '^\s*>'                      ,
54         \ }
55
56 " defaults for g:notmuch_initial_search_words
57 " override with: let g:notmuch_initial_search_words = [ ... ]
58 let s:notmuch_initial_search_words_defaults = [
59         \ 'tag:inbox and tag:unread',
60         \ ]
61
62 " defaults for g:notmuch_show_headers
63 " override with: let g:notmuch_show_headers = [ ... ]
64 let s:notmuch_show_headers_defaults = [
65         \ 'Subject',
66         \ 'To',
67         \ 'Cc',
68         \ 'Bcc',
69         \ 'Date',
70         \ ]
71
72 " --- keyboard mapping definitions {{{1
73
74 " --- --- bindings for search screen {{{2
75 let g:notmuch_search_maps = {
76         \ '<Enter>':    ':call <SID>NM_search_show_thread()<CR>',
77         \ 'a':          ':call <SID>NM_search_archive_thread()<CR>',
78         \ 'f':          ':call <SID>NM_search_filter()<CR>',
79         \ 'm':          ':call <SID>NM_new_mail()<CR>',
80         \ 'o':          ':call <SID>NM_search_toggle_order()<CR>',
81         \ 'r':          ':call <SID>NM_search_reply_to_thread()<CR>',
82         \ 's':          ':call <SID>NM_search_prompt()<CR>',
83         \ 'S':          ':call <SID>NM_search_edit()<CR>',
84         \ 't':          ':call <SID>NM_search_filter_by_tag()<CR>',
85         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
86         \ '+':          ':call <SID>NM_search_add_tags([])<CR>',
87         \ '-':          ':call <SID>NM_search_remove_tags([])<CR>',
88         \ '=':          ':call <SID>NM_search_refresh_view()<CR>',
89         \ }
90
91 " --- --- bindings for show screen {{{2
92 let g:notmuch_show_maps = {
93         \ '<C-P>':      ':call <SID>NM_show_previous(1)<CR>',
94         \ '<C-N>':      ':call <SID>NM_show_next(1)<CR>',
95         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
96         \
97         \ 'b':          ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
98         \ 'c':          ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
99         \ 'h':          ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
100         \ 's':          ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
101         \
102         \ 'a':          ':call <SID>NM_show_archive_thread()<CR>',
103         \ 'A':          ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
104         \ 'N':          ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
105         \ 'v':          ':call <SID>NM_show_view_all_mime_parts()<CR>',
106         \ '+':          ':call <SID>NM_show_add_tag()<CR>',
107         \ '-':          ':call <SID>NM_show_remove_tag()<CR>',
108         \ '<Space>':    ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
109         \ '\|':         ':call <SID>NM_show_pipe_message()<CR>',
110         \
111         \ 'r':          ':call <SID>NM_show_reply()<CR>',
112         \ 'm':          ':call <SID>NM_new_mail()<CR>',
113         \ }
114
115
116 " --- implement search screen {{{1
117
118 function! s:NM_cmd_search(words)
119         let cmd = ['search']
120         if g:notmuch_search_newest_first
121                 let cmd = cmd + ['--sort=newest-first']
122         else
123                 let cmd = cmd + ['--sort=oldest-first']
124         endif
125         let data = s:NM_run(cmd + a:words)
126         let lines = split(data, "\n")
127         let disp = copy(lines)
128         call map(disp, 's:NM_cmd_search_fmtline(v:val)')
129
130         call <SID>NM_newBuffer('search', join(disp, "\n"))
131         let b:nm_raw_lines = lines
132         let b:nm_search_words = a:words
133
134         call <SID>NM_cmd_search_mksyntax()
135         call <SID>NM_set_map(g:notmuch_search_maps)
136         setlocal cursorline
137         setlocal nowrap
138 endfunction
139 function! s:NM_cmd_search_fmtline(line)
140         let m = matchlist(a:line, '^\(thread:\S\+\)\s\([^]]\+\]\) \([^;]\+\); \(.*\) (\([^(]*\))$')
141         if !len(m)
142                 return 'ERROR PARSING: ' . a:line
143         endif
144         let max = g:notmuch_search_from_column_width
145         let from = m[3]
146         if strlen(from) >= max
147                 let from = m[3][0:max-4] . '...'
148         endif
149         return printf('%s %-20s | %s (%s)', m[2], from, m[4], m[5])
150 endfunction
151 function! s:NM_cmd_search_mksyntax()
152         syntax clear nmSearchFrom
153         "syntax region nmSearchFrom start='\]\@<=' end='.'me=e+5,he=e+5,re=e+5 oneline contained
154         "syntax match nmSearchFrom /\]\@<=.\{10\}/ oneline contained
155         exec printf('syntax match nmSearchFrom /\(\] \)\@<=.\{%d\}/ oneline contained', g:notmuch_search_from_column_width)
156         "exec printf('syntax region nmSearchFrom start=''\%%%dv'' end=''\%%%dv'' oneline contained', 20, 30)
157 endfunction
158
159 " --- --- search screen action functions {{{2
160
161 function! s:NM_search_show_thread()
162         let id = <SID>NM_search_find_thread_id()
163         if id != ''
164                 call <SID>NM_cmd_show([id])
165         endif
166 endfunction
167
168 function! s:NM_search_prompt()
169         " TODO: input() can support completion
170         let text = input('NotMuch Search: ')
171         if strlen(text)
172                 let tags = split(text)
173         else
174                 let tags = s:notmuch_initial_search_words_defaults
175         endif
176         setlocal bufhidden=delete
177         call <SID>NM_cmd_search(tags)
178 endfunction
179
180 function! s:NM_search_edit()
181         " TODO: input() can support completion
182         let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
183         if strlen(text)
184                 call <SID>NM_cmd_search(split(text))
185         endif
186 endfunction
187
188 function! s:NM_search_archive_thread()
189         call <SID>NM_add_remove_tags_on_screen('-', ['inbox'])
190         call <SID>NM_add_remove_tags('-', ['inbox'])
191         norm j
192 endfunction
193
194 function! s:NM_search_filter()
195         call <SID>NM_search_filter_helper('Filter: ', '')
196 endfunction
197
198 function! s:NM_search_filter_by_tag()
199         call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:')
200 endfunction
201
202 function! s:NM_search_filter_helper(prompt, prefix)
203         " TODO: input() can support completion
204         let text = input(a:prompt)
205         if !strlen(text)
206                 return
207         endif
208
209         let tags = split(text)
210         map(tags, 'and a:prefix . v:val')
211         let tags = b:nm_search_words + tags
212         echo tags
213
214         let prev_bufnr = bufnr('%')
215         setlocal bufhidden=hide
216         call <SID>NM_cmd_search(tags)
217         setlocal bufhidden=delete
218         let b:nm_prev_bufnr = prev_bufnr
219 endfunction
220
221 function! s:NM_search_toggle_order()
222         let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
223         " FIXME: maybe this would be better done w/o reading re-reading the lines
224         "         reversing the b:nm_raw_lines and the buffer lines would be better
225         call <SID>NM_search_refresh_view()
226 endfunction
227
228 function! s:NM_search_reply_to_thread()
229         echo 'not implemented'
230 endfunction
231
232 function! s:NM_search_add_tags(tags)
233         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
234 endfunction
235
236 function! s:NM_search_remove_tags(tags)
237         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
238 endfunction
239
240 function! s:NM_search_refresh_view()
241         let lno = line('.')
242         setlocal bufhidden=delete
243         call <SID>NM_cmd_search(b:nm_search_words)
244         " FIXME: should find the line of the thread we were on if possible
245         exec printf('norm %dG', lno)
246 endfunction
247
248 " --- --- search screen helper functions {{{2
249
250 function! s:NM_search_find_thread_id()
251         if !exists('b:nm_raw_lines')
252                 echoe 'no b:nm_raw_lines'
253                 return ''
254         else
255                 let line = line('.')
256                 let info = b:nm_raw_lines[line-1]
257                 let what = split(info, '\s\+')[0]
258                 return what
259         endif
260 endfunction
261
262 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
263         if type(a:intags) != type([]) || len(a:intags) == 0
264                 " TODO: input() can support completion
265                 let text = input(a:prompt)
266                 if !strlen(text)
267                         return
268                 endif
269                 let tags = split(text, ' ')
270         else
271                 let tags = a:intags
272         endif
273         call <SID>NM_add_remove_tags(a:prefix, tags)
274         call <SID>NM_add_remove_tags_on_screen(a:prefix, tags)
275 endfunction
276
277 " --- implement show screen {{{1
278
279 function! s:NM_cmd_show(words)
280         let prev_bufnr = bufnr('%')
281         let data = s:NM_run(['show'] + a:words)
282         let lines = split(data, "\n")
283
284         let info = s:NM_cmd_show_parse(lines)
285
286         setlocal bufhidden=hide
287         call <SID>NM_newBuffer('show', join(info['disp'], "\n"))
288         setlocal bufhidden=delete
289         let b:nm_raw_info = info
290         let b:nm_prev_bufnr = prev_bufnr
291
292         call <SID>NM_cmd_show_mkfolds()
293         call <SID>NM_cmd_show_mksyntax()
294         call <SID>NM_set_map(g:notmuch_show_maps)
295         setlocal foldtext=NM_cmd_show_foldtext()
296         setlocal fillchars=
297         setlocal foldcolumn=6
298
299 endfunction
300
301 function! s:NM_show_previous(can_change_thread)
302         let info = b:nm_raw_info
303         let lnum = line('.')
304         for msg in reverse(copy(info['msgs']))
305                 if lnum <= msg['start']
306                         continue
307                 endif
308
309                 exec printf('norm %dG', msg['start'])
310                 " TODO: try to fit the message on screen
311                 norm zz
312                 return
313         endfor
314         if !a:can_change_thread
315                 return
316         endif
317         call <SID>NM_kill_this_buffer()
318         if line('.') != line('0')
319                 norm k
320                 call <SID>NM_search_show_thread()
321                 norm G
322                 call <SID>NM_show_previous(0)
323         else
324                 echo 'No more messages.'
325         endif
326 endfunction
327
328 function! s:NM_show_next(can_change_thread)
329         let info = b:nm_raw_info
330         let lnum = line('.')
331         for msg in info['msgs']
332                 if lnum >= msg['start']
333                         continue
334                 endif
335
336                 exec printf('norm %dG', msg['start'])
337                 " TODO: try to fit the message on screen
338                 norm zz
339                 return
340         endfor
341         if !a:can_change_thread
342                 return
343         endif
344         call <SID>NM_kill_this_buffer()
345         if line('.') != line('$')
346                 norm j
347                 call <SID>NM_search_show_thread()
348         else
349                 echo 'No more messages.'
350         endif
351 endfunction
352
353 function! s:NM_show_archive_thread()
354         echo 'not implemented'
355 endfunction
356
357 function! s:NM_show_mark_read_then_archive_thread()
358         echo 'not implemented'
359 endfunction
360
361 function! s:NM_show_next_message()
362         echo 'not implemented'
363 endfunction
364
365 function! s:NM_show_mark_read_then_next_open_message()
366         echo 'not implemented'
367 endfunction
368
369 function! s:NM_show_previous_message()
370         echo 'not implemented'
371 endfunction
372
373 function! s:NM_show_reply()
374         echo 'not implemented'
375 endfunction
376
377 function! s:NM_show_view_all_mime_parts()
378         echo 'not implemented'
379 endfunction
380
381 function! s:NM_show_view_raw_message()
382         echo 'not implemented'
383 endfunction
384
385 function! s:NM_show_add_tag()
386         echo 'not implemented'
387 endfunction
388
389 function! s:NM_show_remove_tag()
390         echo 'not implemented'
391 endfunction
392
393 function! s:NM_show_advance_marking_read_and_archiving()
394         echo 'not implemented'
395 endfunction
396
397 function! s:NM_show_pipe_message()
398         echo 'not implemented'
399 endfunction
400
401 " --- --- search screen helper functions {{{2
402
403 function! s:NM_show_fold_toggle(key, type, fold)
404         let info = b:nm_raw_info
405         let act = 'open'
406         if a:fold
407                 let act = 'close'
408         endif
409         for fld in info['folds']
410                 if fld[0] == a:type
411                         exec printf('%dfold%s', fld[1], act)
412                 endif
413         endfor
414         exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
415 endfunction
416
417
418 " s:NM_cmd_show_parse returns the following dictionary:
419 "    'disp':     lines to display
420 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
421 "    'folds':    fold info arrays [ type, start, end ]
422 "    'foldtext': fold text indexed by start line
423 function! s:NM_cmd_show_parse(inlines)
424         let info = { 'disp': [],       
425                    \ 'msgs': [],       
426                    \ 'folds': [],      
427                    \ 'foldtext': {} }  
428         let msg = {}
429         let hdr = {}
430
431         let in_message = 0
432         let in_header = 0
433         let in_body = 0
434         let in_part = ''
435
436         let body_start = -1
437         let part_start = -1
438
439         let mode_type = ''
440         let mode_start = -1
441
442         let inlnum = 0
443         for line in a:inlines
444                 let inlnum = inlnum + 1
445                 let foldinfo = []
446
447                 if strlen(in_part)
448                         let part_end = 0
449
450                         if match(line, g:notmuch_show_part_end_regexp) != -1
451                                 let part_end = len(info['disp'])
452                         else
453                                 call add(info['disp'], line)
454                         endif
455
456                         if in_part == 'text/plain'
457                                 if !part_end && mode_type == ''
458                                         if match(line, g:notmuch_show_signature_regexp) != -1
459                                                 let mode_type = 'sig'
460                                                 let mode_start = len(info['disp'])
461                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
462                                                 let mode_type = 'cit'
463                                                 let mode_start = len(info['disp'])
464                                         endif
465                                 elseif mode_type == 'cit'
466                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
467                                                 let outlnum = len(info['disp'])
468                                                 if mode_start != outlnum
469                                                         let foldinfo = [ mode_type, mode_start, outlnum-1,
470                                                                        \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
471                                                 endif
472                                                 let mode_type = ''
473                                         endif
474                                 elseif mode_type == 'sig'
475                                         let outlnum = len(info['disp'])
476                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
477                                                 let mode_type = ''
478                                         elseif part_end
479                                                 if mode_start != outlnum
480                                                         let foldinfo = [ mode_type, mode_start, outlnum-1,
481                                                                        \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
482                                                 endif
483                                                 let mode_type = ''
484                                         endif
485                                 endif
486                         endif
487
488                         if part_end
489                                 " FIXME: this is a hack for handling two folds being added for one line
490                                 "         we should handle addinga fold in a function
491                                 if len(foldinfo)
492                                         call add(info['folds'], foldinfo[0:2])
493                                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
494                                 endif
495
496                                 let foldinfo = [ 'text', part_start, part_end,
497                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
498                                 let in_part = ''
499                                 call add(info['disp'], '')
500                         endif
501
502                 elseif in_body
503                         if !has_key(msg,'body_start')
504                                 let msg['body_start'] = len(info['disp']) + 1
505                         endif
506                         if match(line, g:notmuch_show_body_end_regexp) != -1
507                                 let body_end = len(info['disp'])
508                                 let foldinfo = [ 'bdy', body_start, body_end,
509                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
510
511                                 let in_body = 0
512
513                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
514                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
515                                 let in_part = 'unknown'
516                                 if len(m)
517                                         let in_part = m[2]
518                                 endif
519                                 call add(info['disp'],
520                                          \ printf('--- %s ---', in_part))
521                                 let part_start = len(info['disp']) + 1
522                         endif
523
524                 elseif in_header
525                         if in_header == 1
526                                 let msg['descr'] = line
527                                 call add(info['disp'], line)
528                                 let in_header = 2
529                                 let msg['hdr_start'] = len(info['disp']) + 1
530
531                         else
532                                 if match(line, g:notmuch_show_header_end_regexp) != -1
533                                         let hdr_start = msg['hdr_start']+1
534                                         let hdr_end = len(info['disp'])
535                                         let foldinfo = [ 'hdr', hdr_start, hdr_end,
536                                                \ printf('[ %d-line headers.  Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
537                                         let msg['header'] = hdr
538                                         let in_header = 0
539                                         let hdr = {}
540                                 else
541                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
542                                         if len(m)
543                                                 let hdr[m[1]] = m[2]
544                                                 if match(g:notmuch_show_headers, m[1]) != -1
545                                                         call add(info['disp'], line)
546                                                 endif
547                                         endif
548                                 endif
549                         endif
550
551                 elseif in_message
552                         if match(line, g:notmuch_show_message_end_regexp) != -1
553                                 let msg['end'] = len(info['disp'])
554                                 call add(info['disp'], '')
555
556                                 let foldinfo = [ 'msg', msg['start'], msg['end'],
557                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
558
559                                 call add(info['msgs'], msg)
560                                 let msg = {}
561                                 let in_message = 0
562                                 let in_header = 0
563                                 let in_body = 0
564                                 let in_part = ''
565
566                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
567                                 let in_header = 1
568                                 continue
569
570                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
571                                 let body_start = len(info['disp']) + 1
572                                 let in_body = 1
573                                 continue
574                         endif
575
576                 else
577                         if match(line, g:notmuch_show_message_begin_regexp) != -1
578                                 let msg['start'] = len(info['disp']) + 1
579
580                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
581                                 if len(m)
582                                         let msg['id'] = m[1]
583                                         let msg['depth'] = m[2]
584                                         let msg['filename'] = m[3]
585                                 endif
586
587                                 let in_message = 1
588                         endif
589                 endif
590
591                 if len(foldinfo)
592                         call add(info['folds'], foldinfo[0:2])
593                         let info['foldtext'][foldinfo[1]] = foldinfo[3]
594                 endif
595         endfor
596         return info
597 endfunction
598
599 function! s:NM_cmd_show_mkfolds()
600         let info = b:nm_raw_info
601
602         for afold in info['folds']
603                 exec printf('%d,%dfold', afold[1], afold[2])
604                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
605                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
606                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
607                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
608                         exec printf('%dfoldclose', afold[1])
609                 else
610                         exec printf('%dfoldopen', afold[1])
611                 endif
612         endfor
613 endfunction
614
615 function! s:NM_cmd_show_mksyntax()
616         let info = b:nm_raw_info
617         let cnt = 0
618         for msg in info['msgs']
619                 let cnt = cnt + 1
620                 let start = msg['start']
621                 let hdr_start = msg['hdr_start']
622                 let body_start = msg['body_start']
623                 let end = msg['end']
624                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
625                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
626                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
627         endfor
628 endfunction
629
630 function! NM_cmd_show_foldtext()
631         let foldtext = b:nm_raw_info['foldtext']
632         return foldtext[v:foldstart]
633 endfunction
634
635
636 " --- notmuch helper functions {{{1
637
638 function! s:NM_newBuffer(ft, content)
639         enew
640         setlocal buftype=nofile readonly modifiable
641         silent put=a:content
642         keepjumps 0d
643         setlocal nomodifiable
644         execute printf('set filetype=notmuch-%s', a:ft)
645         execute printf('set syntax=notmuch-%s', a:ft)
646 endfunction
647
648 function! s:NM_run(args)
649         let cmd = g:notmuch_cmd . ' ' . join(a:args) . '< /dev/null'
650
651         let start = reltime()
652         let out = system(cmd)
653         let err = v:shell_error
654         let delta = reltime(start)
655
656         echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
657
658         if err
659                 echohl Error
660                 echo substitute(out, '\n*$', '', '')
661                 echohl None
662                 return ''
663         else
664                 return out
665         endif
666 endfunction
667
668 " --- external mail handling helpers {{{1
669
670 function! s:NM_new_mail()
671         echo 'not implemented'
672 endfunction
673
674 " --- other helpers {{{1
675
676 function! s:NM_kill_this_buffer()
677         if exists('b:nm_prev_bufnr')
678                 setlocal bufhidden=delete
679                 exec printf(":buffer %d", b:nm_prev_bufnr)
680         else
681                 echo "Nothing to kill."
682         endif
683 endfunction
684
685 function! s:NM_add_remove_tags(prefix, tags)
686         let id = <SID>NM_search_find_thread_id()
687         if id == ''
688                 echoe 'Eeek! I couldn''t find the thead id!'
689         endif
690         call map(a:tags, 'a:prefix . v:val')
691         " TODO: handle errors
692         call <SID>NM_run(['tag'] + a:tags + ['--', id])
693 endfunction
694
695 function! s:NM_add_remove_tags_on_screen(prefix, tags)
696         let online = ''
697         setlocal modifiable
698         if a:prefix == '-'
699                 for tagname in a:tags
700                         exec printf('silent %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', online, tagname)
701                 endfor
702         else
703                 for tagname in a:tags
704                         exec printf('silent %ss/(\([^)]*\)\([^)]*\))$/(\1 %s)/', online, tagname)
705                 endfor
706         endif
707         setlocal nomodifiable
708 endfunction
709
710 " --- process and set the defaults {{{1
711
712 function! NM_set_defaults(force)
713         for [key, dflt] in items(s:notmuch_defaults)
714                 let cmd = ''
715                 if !a:force && exists(key) && type(dflt) == type(eval(key))
716                         continue
717                 elseif type(dflt) == type(0)
718                         let cmd = printf('let %s = %d', key, dflt)
719                 elseif type(dflt) == type('')
720                         let cmd = printf('let %s = ''%s''', key, dflt)
721                 "elseif type(dflt) == type([])
722                 "        let cmd = printf('let %s = %s', key, string(dflt))
723                 else
724                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
725                                                 \ a:force, key, string(dflt))
726                         continue
727                 endif
728                 exec cmd
729         endfor
730 endfunction
731 call NM_set_defaults(0)
732
733 " for some reason NM_set_defaults() didn't work for arrays...
734 if !exists('g:notmuch_show_headers')
735         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
736 endif
737 if !exists('g:notmuch_initial_search_words')
738         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
739 endif
740
741
742 " --- assign keymaps {{{1
743
744 function! s:NM_set_map(maps)
745         nmapclear
746         for [key, code] in items(a:maps)
747                 exec printf('nnoremap <buffer> %s %s', key, code)
748         endfor
749         " --- this is a hack for development :)
750         nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
751 endfunction
752
753 " --- command handler {{{1
754
755 function! NotMuch(args)
756         if !strlen(a:args)
757                 if exists('b:nm_search_words')
758                         let words = b:nm_search_words
759                 else
760                         let words = g:notmuch_initial_search_words
761                 endif
762                 call <SID>NM_cmd_search(words)
763                 return
764         endif
765
766         echo "blarg!"
767
768         let words = split(a:args)
769         " TODO: handle commands passed as arguments
770 endfunction
771 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
772         return []
773 endfunction
774
775
776 " --- glue {{{1
777
778 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
779 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
780
781 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :