]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
vim: primitive reply to thread
[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_debug':                         0                            ,
27         \
28         \ 'g:notmuch_search_newest_first':           1                            ,
29         \ 'g:notmuch_search_from_column_width':      20                           ,
30         \
31         \ 'g:notmuch_show_fold_signatures':          1                            ,
32         \ 'g:notmuch_show_fold_citations':           1                            ,
33         \ 'g:notmuch_show_fold_bodies':              0                            ,
34         \ 'g:notmuch_show_fold_headers':             1                            ,
35         \
36         \ 'g:notmuch_show_message_begin_regexp':     '\fmessage{'                ,
37         \ 'g:notmuch_show_message_end_regexp':       '\fmessage}'                ,
38         \ 'g:notmuch_show_header_begin_regexp':      '\fheader{'                 ,
39         \ 'g:notmuch_show_header_end_regexp':        '\fheader}'                 ,
40         \ 'g:notmuch_show_body_begin_regexp':        '\fbody{'                   ,
41         \ 'g:notmuch_show_body_end_regexp':          '\fbody}'                   ,
42         \ 'g:notmuch_show_attachment_begin_regexp':  '\fattachment{'             ,
43         \ 'g:notmuch_show_attachment_end_regexp':    '\fattachment}'             ,
44         \ 'g:notmuch_show_part_begin_regexp':        '\fpart{'                   ,
45         \ 'g:notmuch_show_part_end_regexp':          '\fpart}'                   ,
46         \ 'g:notmuch_show_marker_regexp':            '\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
47         \
48         \ 'g:notmuch_show_message_parse_regexp':     '\(id:[^ ]*\) depth:\([0-9]*\) match:\([0-9]*\) filename:\(.*\)$',
49         \ 'g:notmuch_show_tags_regexp':              '(\([^)]*\))$'               ,
50         \
51         \ 'g:notmuch_show_signature_regexp':         '^\(-- \?\|_\+\)$'           ,
52         \ 'g:notmuch_show_signature_lines_max':      12                           ,
53         \
54         \ 'g:notmuch_show_citation_regexp':          '^\s*>'                      ,
55         \
56         \ 'g:notmuch_compose_insert_mode_start':     1                            ,
57         \ 'g:notmuch_compose_header_help':           1                            ,
58         \ 'g:notmuch_compose_temp_file_dir':         '~/.notmuch/compose/'        ,
59         \ }
60
61 " defaults for g:notmuch_initial_search_words
62 " override with: let g:notmuch_initial_search_words = [ ... ]
63 let s:notmuch_initial_search_words_defaults = [
64         \ 'tag:inbox and tag:unread',
65         \ ]
66
67 " defaults for g:notmuch_show_headers
68 " override with: let g:notmuch_show_headers = [ ... ]
69 let s:notmuch_show_headers_defaults = [
70         \ 'Subject',
71         \ 'To',
72         \ 'Cc',
73         \ 'Bcc',
74         \ 'Date',
75         \ ]
76
77 " defaults for g:notmuch_folders
78 " override with: let g:notmuch_folders = [ ... ]
79 let s:notmuch_folders_defaults = [
80         \ [ 'new',    'tag:inbox and tag:unread' ],
81         \ [ 'inbox',  'tag:inbox'                ],
82         \ [ 'unread', 'tag:unread'               ],
83         \ ]
84
85 " defaults for g:notmuch_signature
86 " override with: let g:notmuch_signature = [ ... ]
87 let s:notmuch_signature_defaults = [
88         \ '',
89         \ '-- ',
90         \ 'email sent from notmuch.vim plugin'
91         \ ]
92
93 " defaults for g:notmuch_compose_headers
94 " override with: let g:notmuch_compose_headers = [ ... ]
95 let s:notmuch_compose_headers_defaults = [
96         \ 'From',
97         \ 'To',
98         \ 'Cc',
99         \ 'Bcc',
100         \ 'Subject'
101         \ ]
102
103 " --- keyboard mapping definitions {{{1
104
105 " --- --- bindings for folders mode {{{2
106
107 let g:notmuch_folders_maps = {
108         \ 'm':          ':call <SID>NM_new_mail()<CR>',
109         \ 's':          ':call <SID>NM_search_prompt()<CR>',
110         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
111         \ '=':          ':call <SID>NM_folders_refresh_view()<CR>',
112         \ '<Enter>':    ':call <SID>NM_folders_show_search()<CR>',
113         \ }
114
115 " --- --- bindings for search screen {{{2
116 let g:notmuch_search_maps = {
117         \ '<Enter>':    ':call <SID>NM_search_show_thread()<CR>',
118         \ '<C-]>':      ':call <SID>NM_search_expand(''<cword>'')<CR>',
119         \ 'a':          ':call <SID>NM_search_archive_thread()<CR>',
120         \ 'f':          ':call <SID>NM_search_filter()<CR>',
121         \ 'm':          ':call <SID>NM_new_mail()<CR>',
122         \ 'o':          ':call <SID>NM_search_toggle_order()<CR>',
123         \ 'r':          ':call <SID>NM_search_reply_to_thread()<CR>',
124         \ 's':          ':call <SID>NM_search_prompt()<CR>',
125         \ ',s':         ':call <SID>NM_search_edit()<CR>',
126         \ 't':          ':call <SID>NM_search_filter_by_tag()<CR>',
127         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
128         \ '+':          ':call <SID>NM_search_add_tags([])<CR>',
129         \ '-':          ':call <SID>NM_search_remove_tags([])<CR>',
130         \ '=':          ':call <SID>NM_search_refresh_view()<CR>',
131         \ '?':          ':echo <SID>NM_search_thread_id() . ''  @ '' . join(<SID>NM_get_search_words())<CR>',
132         \ }
133
134 " --- --- bindings for show screen {{{2
135 let g:notmuch_show_maps = {
136         \ '<C-P>':      ':call <SID>NM_show_previous(1, 0)<CR>',
137         \ '<C-N>':      ':call <SID>NM_show_next(1, 0)<CR>',
138         \ '<C-]>':      ':call <SID>NM_search_expand(''<cword>'')<CR>',
139         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
140         \
141         \ 'b':          ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
142         \ 'c':          ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
143         \ 'h':          ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
144         \ 's':          ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
145         \
146         \ 'a':          ':call <SID>NM_show_archive_thread()<CR>',
147         \ 'A':          ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
148         \ 'N':          ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
149         \ 'v':          ':call <SID>NM_show_view_all_mime_parts()<CR>',
150         \ '+':          ':call <SID>NM_show_add_tag()<CR>',
151         \ '-':          ':call <SID>NM_show_remove_tag()<CR>',
152         \ '<Space>':    ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
153         \ '\|':         ':call <SID>NM_show_pipe_message()<CR>',
154         \
155         \ '<S-Tab>':    ':call <SID>NM_show_previous_fold()<CR>',
156         \ '<Tab>':      ':call <SID>NM_show_next_fold()<CR>',
157         \ '<Enter>':    ':call <SID>NM_show_toggle_fold()<CR>',
158         \
159         \ 'r':          ':call <SID>NM_show_reply()<CR>',
160         \ 'm':          ':call <SID>NM_new_mail()<CR>',
161         \ '?':          ':echo <SID>NM_show_message_id() . ''  @ '' . join(<SID>NM_get_search_words())<CR>',
162         \ }
163
164 " --- --- bindings for compose screen {{{2
165 let g:notmuch_compose_nmaps = {
166         \ ',s':         ':call <SID>NM_compose_send()<CR>',
167         \ ',a':         ':call <SID>NM_compose_attach()<CR>',
168         \ ',q':         ':call <SID>NM_kill_this_buffer()<CR>',
169         \ '<Tab>':      ':call <SID>NM_compose_next_entry_area()<CR>',
170         \ }
171 let g:notmuch_compose_imaps = {
172         \ '<Tab>':      '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
173         \ }
174
175 " --- implement folders screen {{{1
176
177 function! s:NM_cmd_folders(words)
178         if len(a:words)
179                 throw 'Not exapecting any arguments for folders command.'
180         endif
181         let cmd = ['count']
182         let disp = []
183         let searches = []
184         for entry in g:notmuch_folders
185                 let [ name, search ] = entry
186                 let data = s:NM_run(cmd + [search])
187                 let cnt = matchlist(data, '\(\d\+\)')[1]
188                 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
189                 call add(searches, search)
190         endfor
191
192         call <SID>NM_newBuffer('', 'folders', join(disp, "\n"))
193         let b:nm_searches = searches
194         let b:nm_timestamp = reltime()
195
196         call <SID>NM_cmd_folders_mksyntax()
197         call <SID>NM_set_map('n', g:notmuch_folders_maps)
198         setlocal cursorline
199         setlocal nowrap
200 endfunction
201
202 function! s:NM_cmd_folders_mksyntax()
203 endfunction
204
205 " --- --- folders screen action functions {{{2
206
207 function! s:NM_folders_refresh_view()
208         let lno = line('.')
209         setlocal bufhidden=delete
210         call s:NM_cmd_folders([])
211         exec printf('norm %dG', lno)
212 endfunction
213
214 function! s:NM_folders_show_search()
215         let line = line('.')
216         let search = b:nm_searches[line-1]
217
218         let prev_bufnr = bufnr('%')
219         setlocal bufhidden=hide
220         call <SID>NM_cmd_search([search])
221         setlocal bufhidden=delete
222         let b:nm_prev_bufnr = prev_bufnr
223 endfunction
224
225
226 " --- implement search screen {{{1
227
228 function! s:NM_cmd_search(words)
229         let cmd = ['search']
230         if g:notmuch_search_newest_first
231                 let cmd = cmd + ['--sort=newest-first']
232         else
233                 let cmd = cmd + ['--sort=oldest-first']
234         endif
235         let data = s:NM_run(cmd + a:words)
236         let lines = split(data, "\n")
237         let disp = copy(lines)
238         call map(disp, 's:NM_cmd_search_fmtline(v:val)')
239
240         call <SID>NM_newBuffer('', 'search', join(disp, "\n"))
241         let b:nm_raw_lines = lines
242         let b:nm_search_words = a:words
243
244         call <SID>NM_cmd_search_mksyntax()
245         call <SID>NM_set_map('n', g:notmuch_search_maps)
246         setlocal cursorline
247         setlocal nowrap
248 endfunction
249 function! s:NM_cmd_search_fmtline(line)
250         let m = matchlist(a:line, '^\(thread:\S\+\)\s\([^]]\+\]\) \([^;]\+\); \(.*\) (\([^(]*\))$')
251         if !len(m)
252                 return 'ERROR PARSING: ' . a:line
253         endif
254         let max = g:notmuch_search_from_column_width
255         let from = m[3]
256         if strlen(from) >= max
257                 let from = substitute(m[3][0:max-4], '[^A-Za-z1-9_]*$', '', '') . '...'
258         endif
259         return printf('%-20s %-20s | %s (%s)', m[2], from, m[4], m[5])
260 endfunction
261 function! s:NM_cmd_search_mksyntax()
262         syntax clear nmSearchFrom
263         exec printf('syntax match nmSearchFrom /\(\] \)\@<=.\{%d\}/ oneline contained', g:notmuch_search_from_column_width)
264 endfunction
265
266 " --- --- search screen action functions {{{2
267
268 function! s:NM_search_show_thread()
269         let id = <SID>NM_search_thread_id()
270         if id != ''
271                 let words = [id]
272                 if exists('b:nm_search_words')
273                         let words = ['('] + b:nm_search_words + [')', 'AND', id]
274                 endif
275                 if len(words)
276                         call <SID>NM_cmd_show(words)
277                 endif
278         endif
279 endfunction
280
281 function! s:NM_search_prompt()
282         " TODO: input() can support completion
283         let text = input('NotMuch Search: ')
284         if strlen(text)
285                 let tags = split(text)
286         else
287                 let tags = s:notmuch_initial_search_words_defaults
288         endif
289         let prev_bufnr = bufnr('%')
290         if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
291                 " TODO: we intend to replace the current buffer,
292                 "       ... maybe we could just clear it
293                 let prev_bufnr = b:nm_prev_bufnr
294                 setlocal bufhidden=delete
295         else
296                 setlocal bufhidden=hide
297         endif
298         call <SID>NM_cmd_search(tags)
299         setlocal bufhidden=delete
300         let b:nm_prev_bufnr = prev_bufnr
301 endfunction
302
303 function! s:NM_search_edit()
304         " TODO: input() can support completion
305         let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
306         if strlen(text)
307                 call <SID>NM_cmd_search(split(text))
308         endif
309 endfunction
310
311 function! s:NM_search_archive_thread()
312         call <SID>NM_add_remove_tags_on_screen('', '-', ['inbox'])
313         call <SID>NM_add_remove_tags([], '-', ['inbox'])
314         norm j
315 endfunction
316
317 function! s:NM_search_filter()
318         call <SID>NM_search_filter_helper('Filter: ', '', '')
319 endfunction
320
321 function! s:NM_search_filter_by_tag()
322         call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
323 endfunction
324
325 function! s:NM_search_filter_helper(prompt, prefix, joiner)
326         " TODO: input() can support completion
327         let text = substitute(input(a:prompt), '\v(^\s*|\s*$|\n)', '', 'g')
328         if !strlen(text)
329                 return
330         endif
331
332         let tags = b:nm_search_words + ['AND']
333                  \ + <SID>NM_combine_tags(a:prefix, split(text), a:joiner, '()')
334
335         let prev_bufnr = bufnr('%')
336         setlocal bufhidden=hide
337         call <SID>NM_cmd_search(tags)
338         setlocal bufhidden=delete
339         let b:nm_prev_bufnr = prev_bufnr
340 endfunction
341
342 function! s:NM_search_toggle_order()
343         let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
344         " FIXME: maybe this would be better done w/o reading re-reading the lines
345         "         reversing the b:nm_raw_lines and the buffer lines would be better
346         call <SID>NM_search_refresh_view()
347 endfunction
348
349 function! s:NM_search_reply_to_thread()
350         let cmd = ['reply']
351         call add(cmd, <SID>NM_search_thread_id())
352         call add(cmd, 'AND')
353         call extend(cmd, <SID>NM_get_search_words())
354
355         let data = <SID>NM_run(cmd)
356         let lines = split(data, "\n")
357         call <SID>NM_newComposeBuffer(lines, 0)
358 endfunction
359
360 function! s:NM_search_add_tags(tags)
361         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
362 endfunction
363
364 function! s:NM_search_remove_tags(tags)
365         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
366 endfunction
367
368 function! s:NM_search_refresh_view()
369         let lno = line('.')
370         let prev_bufnr = b:nm_prev_bufnr
371         setlocal bufhidden=delete
372         call <SID>NM_cmd_search(b:nm_search_words)
373         let b:nm_prev_bufnr = prev_bufnr
374         " FIXME: should find the line of the thread we were on if possible
375         exec printf('norm %dG', lno)
376 endfunction
377
378 " --- --- search screen helper functions {{{2
379
380 function! s:NM_search_thread_id()
381         if !exists('b:nm_raw_lines')
382                 throw 'Eeek! no b:nm_raw_lines'
383         endif
384         let mnum = line('.') - 1
385         if len(b:nm_raw_lines) <= mnum
386                 return ''
387         endif
388         let info = b:nm_raw_lines[mnum]
389         let what = split(info, '\s\+')[0]
390         return what
391 endfunction
392
393 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
394         if type(a:intags) != type([]) || len(a:intags) == 0
395                 " TODO: input() can support completion
396                 let text = input(a:prompt)
397                 if !strlen(text)
398                         return
399                 endif
400                 let tags = split(text, ' ')
401         else
402                 let tags = a:intags
403         endif
404         call <SID>NM_add_remove_tags([], a:prefix, tags)
405         call <SID>NM_add_remove_tags_on_screen('', a:prefix, tags)
406 endfunction
407
408 " --- implement show screen {{{1
409
410 function! s:NM_cmd_show(words)
411         let prev_bufnr = bufnr('%')
412         let data = s:NM_run(['show'] + a:words)
413         let lines = split(data, "\n")
414
415         let info = s:NM_cmd_show_parse(lines)
416
417         setlocal bufhidden=hide
418         call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
419         setlocal bufhidden=delete
420         let b:nm_search_words = a:words
421         let b:nm_raw_info = info
422         let b:nm_prev_bufnr = prev_bufnr
423
424         call <SID>NM_cmd_show_mkfolds()
425         call <SID>NM_cmd_show_mksyntax()
426         call <SID>NM_set_map('n', g:notmuch_show_maps)
427         setlocal foldtext=NM_cmd_show_foldtext()
428         setlocal fillchars=
429         setlocal foldcolumn=6
430
431 endfunction
432
433 function! s:NM_show_previous(can_change_thread, find_matching)
434         let info = b:nm_raw_info
435         let lnum = line('.')
436         for msg in reverse(copy(info['msgs']))
437                 if a:find_matching && msg['match'] == '0'
438                         continue
439                 endif
440                 if lnum <= msg['start']
441                         continue
442                 endif
443
444                 exec printf('norm %dGzt', msg['start'])
445                 " TODO: try to fit the message on screen
446                 return
447         endfor
448         if !a:can_change_thread
449                 return
450         endif
451         call <SID>NM_kill_this_buffer()
452         if line('.') > 1
453                 norm k
454                 call <SID>NM_search_show_thread()
455                 norm G
456                 call <SID>NM_show_previous(0, a:find_matching)
457         else
458                 echo 'No more messages.'
459         endif
460 endfunction
461
462 function! s:NM_show_next(can_change_thread, find_matching)
463         let info = b:nm_raw_info
464         let lnum = line('.')
465         for msg in info['msgs']
466                 if a:find_matching && msg['match'] == '0'
467                         continue
468                 endif
469                 if lnum >= msg['start']
470                         continue
471                 endif
472
473                 exec printf('norm %dGzt', msg['start'])
474                 " TODO: try to fit the message on screen
475                 return
476         endfor
477         if a:can_change_thread
478                 call <SID>NM_show_next_thread()
479         endif
480 endfunction
481
482 function! s:NM_show_next_thread()
483         call <SID>NM_kill_this_buffer()
484         if line('.') != line('$')
485                 norm j
486                 call <SID>NM_search_show_thread()
487         else
488                 echo 'No more messages.'
489         endif
490 endfunction
491
492 function! s:NM_show_archive_thread()
493         echo 'not implemented'
494 endfunction
495
496 function! s:NM_show_mark_read_then_archive_thread()
497         echo 'not implemented'
498 endfunction
499
500 function! s:NM_show_mark_read_then_next_open_message()
501         echo 'not implemented'
502 endfunction
503
504 function! s:NM_show_previous_message()
505         echo 'not implemented'
506 endfunction
507
508 function! s:NM_show_reply()
509         echo 'not implemented'
510 endfunction
511
512 function! s:NM_show_view_all_mime_parts()
513         echo 'not implemented'
514 endfunction
515
516 function! s:NM_show_view_raw_message()
517         echo 'not implemented'
518 endfunction
519
520 function! s:NM_show_add_tag()
521         echo 'not implemented'
522 endfunction
523
524 function! s:NM_show_remove_tag()
525         echo 'not implemented'
526 endfunction
527
528 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
529 " otherwise go to next message
530 " any message that is viewed entirely has inbox and unread tags removed
531 function! s:NM_show_advance_marking_read_and_archiving()
532         let advance_tags = ['unread', 'inbox']
533
534         let vis_top = line('w0')
535         let vis_bot = line('w$')
536
537         let msg_top = <SID>NM_show_get_message_for_line(vis_top)
538         if !has_key(msg_top,'id')
539                 throw "No top visible message."
540         endif
541
542         " if the top message is the last message, just expunge the entire thread and move on
543         if msg_top['end'] == line('$')
544                 let ids = []
545                 for msg in b:nm_raw_info['msgs']
546                         if has_key(msg,'match') && msg['match'] != '0'
547                                 call add(ids, msg['id'])
548                         endif
549                 endfor
550                 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
551                          \ + ['AND']
552                          \ + <SID>NM_combine_tags('', ids, 'OR', '()')
553                 call <SID>NM_add_remove_tags(filter, '-', advance_tags)
554                 call <SID>NM_show_next(1, 1)
555                 return
556         endif
557
558         let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
559         if !has_key(msg_bot,'id')
560                 throw "No bottom visible message."
561         endif
562
563         " if entire message fits on the screen, read/archive it, move to the next one
564         if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
565                 call <SID>NM_add_remove_tags_on_screen(msg_top['start'], '-', advance_tags)
566                 exec printf('norm %dG', vis_top)
567                 call <SID>NM_show_next(0, 1)
568                 if has_key(msg_top,'match') && msg_top['match'] != '0'
569                         redraw
570                         " do this last to hide the latency
571                         let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
572                                  \ + ['AND', msg_top['id']]
573                         call <SID>NM_add_remove_tags(filter, '-', advance_tags)
574                 endif
575                 return
576         endif
577
578         " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
579         let jmp = winheight(winnr()) / 2
580         let max = msg_bot['end'] - vis_bot
581         if jmp > max
582                 let jmp = max
583         endif
584         exec printf('norm %dGzt', vis_top + jmp)
585         return
586 endfunction
587
588 function! s:NM_show_pipe_message()
589         echo 'not implemented'
590 endfunction
591
592 function! s:NM_show_previous_fold()
593         echo 'not implemented'
594 endfunction
595
596 function! s:NM_show_next_fold()
597         echo 'not implemented'
598 endfunction
599
600 function! s:NM_show_toggle_fold()
601         echo 'not implemented'
602 endfunction
603
604
605 " --- --- show screen helper functions {{{2
606
607 function! s:NM_show_get_message_for_line(line)
608         for msg in b:nm_raw_info['msgs']
609                 if a:line > msg['end']
610                         continue
611                 endif
612                 return msg
613         endfor
614         return {}
615 endfunction
616
617 function! s:NM_show_message_id()
618         if !exists('b:nm_raw_info')
619                 throw 'Eeek! no b:nm_raw_info'
620         endif
621         let msg = <SID>NM_show_get_message_for_line(line('.'))
622         if has_key(msg,'id')
623                 return msg['id']
624         endif
625         return ''
626 endfunction
627
628 function! s:NM_show_fold_toggle(key, type, fold)
629         let info = b:nm_raw_info
630         let act = 'open'
631         if a:fold
632                 let act = 'close'
633         endif
634         for fld in info['folds']
635                 if fld[0] == a:type
636                         exec printf('%dfold%s', fld[1], act)
637                 endif
638         endfor
639         exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
640 endfunction
641
642
643 " s:NM_cmd_show_parse returns the following dictionary:
644 "    'disp':     lines to display
645 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
646 "    'folds':    fold info arrays [ type, start, end ]
647 "    'foldtext': fold text indexed by start line
648 function! s:NM_cmd_show_parse(inlines)
649         let info = { 'disp': [],       
650                    \ 'msgs': [],       
651                    \ 'folds': [],      
652                    \ 'foldtext': {} }  
653         let msg = {}
654         let hdr = {}
655
656         let in_message = 0
657         let in_header = 0
658         let in_body = 0
659         let in_part = ''
660
661         let body_start = -1
662         let part_start = -1
663
664         let mode_type = ''
665         let mode_start = -1
666
667         let inlnum = 0
668         for line in a:inlines
669                 let inlnum = inlnum + 1
670                 let foldinfo = []
671
672                 if strlen(in_part)
673                         let part_end = 0
674
675                         if match(line, g:notmuch_show_part_end_regexp) != -1
676                                 let part_end = len(info['disp'])
677                         else
678                                 call add(info['disp'], line)
679                         endif
680
681                         if in_part == 'text/plain'
682                                 if !part_end && mode_type == ''
683                                         if match(line, g:notmuch_show_signature_regexp) != -1
684                                                 let mode_type = 'sig'
685                                                 let mode_start = len(info['disp'])
686                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
687                                                 let mode_type = 'cit'
688                                                 let mode_start = len(info['disp'])
689                                         endif
690                                 elseif mode_type == 'cit'
691                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
692                                                 let outlnum = len(info['disp'])
693                                                 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
694                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
695                                                 let mode_type = ''
696                                         endif
697                                 elseif mode_type == 'sig'
698                                         let outlnum = len(info['disp'])
699                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
700                                                 let mode_type = ''
701                                         elseif part_end
702                                                 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
703                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
704                                                 let mode_type = ''
705                                         endif
706                                 endif
707                         endif
708
709                         if part_end
710                                 " FIXME: this is a hack for handling two folds being added for one line
711                                 "         we should handle addinga fold in a function
712                                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
713                                         call add(info['folds'], foldinfo[0:3])
714                                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
715                                 endif
716
717                                 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
718                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
719                                 let in_part = ''
720                                 call add(info['disp'], '')
721                         endif
722
723                 elseif in_body
724                         if !has_key(msg,'body_start')
725                                 let msg['body_start'] = len(info['disp']) + 1
726                         endif
727                         if match(line, g:notmuch_show_body_end_regexp) != -1
728                                 let body_end = len(info['disp'])
729                                 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
730                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
731
732                                 let in_body = 0
733
734                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
735                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
736                                 let in_part = 'unknown'
737                                 if len(m)
738                                         let in_part = m[2]
739                                 endif
740                                 call add(info['disp'],
741                                          \ printf('--- %s ---', in_part))
742                                 let part_start = len(info['disp']) + 1
743                         endif
744
745                 elseif in_header
746                         if in_header == 1
747                                 let msg['descr'] = line
748                                 call add(info['disp'], line)
749                                 let in_header = 2
750                                 let msg['hdr_start'] = len(info['disp']) + 1
751
752                         else
753                                 if match(line, g:notmuch_show_header_end_regexp) != -1
754                                         let hdr_start = msg['hdr_start']+1
755                                         let hdr_end = len(info['disp'])
756                                         let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
757                                                \ printf('[ %d-line headers.  Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
758                                         let msg['header'] = hdr
759                                         let in_header = 0
760                                         let hdr = {}
761                                 else
762                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
763                                         if len(m)
764                                                 let hdr[m[1]] = m[2]
765                                                 if match(g:notmuch_show_headers, m[1]) != -1
766                                                         call add(info['disp'], line)
767                                                 endif
768                                         endif
769                                 endif
770                         endif
771
772                 elseif in_message
773                         if match(line, g:notmuch_show_message_end_regexp) != -1
774                                 let msg['end'] = len(info['disp'])
775                                 call add(info['disp'], '')
776
777                                 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
778                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
779
780                                 call add(info['msgs'], msg)
781                                 let msg = {}
782                                 let in_message = 0
783                                 let in_header = 0
784                                 let in_body = 0
785                                 let in_part = ''
786
787                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
788                                 let in_header = 1
789                                 continue
790
791                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
792                                 let body_start = len(info['disp']) + 1
793                                 let in_body = 1
794                                 continue
795                         endif
796
797                 else
798                         if match(line, g:notmuch_show_message_begin_regexp) != -1
799                                 let msg['start'] = len(info['disp']) + 1
800
801                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
802                                 if len(m)
803                                         let msg['id'] = m[1]
804                                         let msg['depth'] = m[2]
805                                         let msg['match'] = m[3]
806                                         let msg['filename'] = m[4]
807                                 endif
808
809                                 let in_message = 1
810                         endif
811                 endif
812
813                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
814                         call add(info['folds'], foldinfo[0:3])
815                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
816                 endif
817         endfor
818         return info
819 endfunction
820
821 function! s:NM_cmd_show_mkfolds()
822         let info = b:nm_raw_info
823
824         for afold in info['folds']
825                 exec printf('%d,%dfold', afold[1], afold[2])
826                 let state = 'open'
827                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
828                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
829                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
830                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
831                         let state = 'close'
832                 elseif afold[0] == 'msg'
833                         let idx = afold[3]
834                         let msg = info['msgs'][idx]
835                         if has_key(msg,'match') && msg['match'] == '0'
836                                 let state = 'close'
837                         endif
838                 endif
839                 exec printf('%dfold%s', afold[1], state)
840         endfor
841 endfunction
842
843 function! s:NM_cmd_show_mksyntax()
844         let info = b:nm_raw_info
845         let cnt = 0
846         for msg in info['msgs']
847                 let cnt = cnt + 1
848                 let start = msg['start']
849                 let hdr_start = msg['hdr_start']
850                 let body_start = msg['body_start']
851                 let end = msg['end']
852                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
853                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
854                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
855         endfor
856 endfunction
857
858 function! NM_cmd_show_foldtext()
859         let foldtext = b:nm_raw_info['foldtext']
860         return foldtext[v:foldstart]
861 endfunction
862
863
864 " --- implement compose screen {{{1
865
866 function! s:NM_cmd_compose(words, body_lines)
867         let lines = []
868         let start_on_line = 0
869
870         let hdrs = { }
871         for word in a:words
872                 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
873                 if !len(m)
874                         throw 'Eeek! bad parameter ''' . string(word) . ''''
875                 endif
876                 let key = substitute(m[1], '\<\w', '\U&', 'g')
877                 if !has_key(hdrs, key)
878                         let hdrs[key] = []
879                 endif
880                 if strlen(m[2])
881                         call add(hdrs[key], m[2])
882                 endif
883         endfor
884
885         if !has_key(hdrs, 'From') || !len(hdrs['From'])
886                 let me = <SID>NM_compose_get_user_email()
887                 let hdrs['From'] = [ me ]
888         endif
889
890         for key in g:notmuch_compose_headers
891                 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
892                 call add(lines, key . ': ' . text)
893                 if !start_on_line && !strlen(text)
894                         let start_on_line = len(lines)
895                 endif
896         endfor
897
898         for [key,val] in items(hdrs)
899                 if match(g:notmuch_compose_headers, key) == -1
900                         let line = key . ': ' . join(val, ', ')
901                         call add(lines, line)
902                 endif
903         endfor
904
905         call add(lines, '')
906         if !start_on_line
907                 let start_on_line = len(lines) + 1
908         endif
909
910         if len(a:body_lines)
911                 call extend(lines, a:body_lines)
912         else
913                 call extend(lines, [ '', '' ])
914         endif
915
916         call <SID>NM_newComposeBuffer(lines, start_on_line)
917 endfunction
918
919 function! s:NM_compose_send()
920         call <SID>NM_assert_buffer_type('compose')
921         let fname = expand('%')
922         let lnum = 1
923         let line = getline(lnum)
924         let hdrs = {}
925         let lst_hdr = ''
926         while match(line, '^$') == -1
927                 if match(line, '^Notmuch-Help:') != -1
928                         " skip it
929                 elseif strlen(lst_hdr) && match(line, '^\s') != -1
930                         let hdrs[lst_hdr][-1] = hdrs[lst_hdr][-1] . substitute(line, '^\s*', ' ', '')
931                 else
932                         let m = matchlist(line, '^\(\w[^:]*\):\s*\(.*\)\s*$')
933                         if !len(m)
934                                 cursor(lnum, 0)
935                                 throw printf('Eeek! invalid header on line %d', lnum)
936                         endif
937                         let key = substitute(m[1], '\<\w', '\U&', 'g')
938                         if strlen(m[2])
939                                 if !has_key(hdrs, key)
940                                         let hdrs[key] = []
941                                 endif
942                                 call add(hdrs[key], m[2])
943                         endif
944                         let lst_hdr = key
945                 endif
946                 let lnum = lnum + 1
947                 let line = getline(lnum)
948         endwhile
949         let body_starts = lnum
950
951         "[-a header] [-b bcc-addr] [-c cc-addr] [-s subject] to-addr
952         let cmd = ['mail']
953         let tos = []
954         for [key, vals] in items(hdrs)
955                 if key == 'To'
956                         call extend(tos, vals)
957                 elseif key == 'Bcc'
958                         for adr in vals
959                                 call add(cmd, '-b')
960                                 call add(cmd, adr)
961                         endfor
962                 elseif key == 'Cc'
963                         for adr in vals
964                                 call add(cmd, '-c')
965                                 call add(cmd, adr)
966                         endfor
967                 elseif key == 'Subject'
968                         for txt in vals
969                                 call add(cmd, '-s')
970                                 call add(cmd, txt)
971                         endfor
972                 else
973                         for val in vals
974                                 call add(cmd, '-a')
975                                 call add(cmd, key . ': ' . val)
976                         endfor
977                 endif
978         endfor
979         call extend(cmd, tos)
980
981         " TODO: make sure we have at least one target
982         " TODO: ask about empty jubject, etc
983
984         exec printf('0,%dd', body_starts)
985         write
986
987         call map(cmd, 's:NM_shell_escape(v:val)')
988         let cmdtxt = join(cmd) . '< ' . fname
989         let out = system(cmdtxt)
990         let err = v:shell_error
991         if err
992                 undo
993                 write
994                 call <SID>NM_newBuffer('new', 'error',
995                             \ "While running...\n" .
996                             \ '  ' . cmdtxt . "\n" .
997                             \ "\n" .
998                             \ "Failed with...\n" .
999                             \ substitute(out, '^', '  ', 'g'))
1000                 echohl Error
1001                 echo 'Eeek! unable to send mail'
1002                 echohl None
1003                 return
1004         endif
1005
1006         if !exists('b:nm_prev_bufnr')
1007                 bdelete
1008         else
1009                 let prev_bufnr = b:nm_prev_bufnr
1010                 bdelete
1011                 if prev_bufnr == bufnr('%')
1012                         exec printf("buffer %d", prev_bufnr)
1013                 endif
1014         endif
1015         call delete(fname)
1016         echo 'Mail sent successfully.'
1017 endfunction
1018
1019 function! s:NM_compose_attach()
1020         echo 'not implemented'
1021 endfunction
1022
1023 function! s:NM_compose_next_entry_area()
1024         let lnum = line('.')
1025         let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1026         if lnum < hdr_end
1027                 let lnum = lnum + 1
1028                 let line = getline(lnum)
1029                 if match(line, '^\([^:]\+\):\s*$') == -1
1030                         call cursor(lnum, strlen(line) + 1)
1031                         return ''
1032                 endif
1033                 while match(getline(lnum+1), '^\s') != -1
1034                         let lnum = lnum + 1
1035                 endwhile
1036                 call cursor(lnum, strlen(getline(lnum)) + 1)
1037                 return ''
1038
1039         elseif lnum == hdr_end
1040                 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1041                 return ''
1042         endif
1043         if mode() == 'i'
1044                 if !getbufvar(bufnr('.'), '&et')
1045                         return "\t"
1046                 endif
1047                 let space = ''
1048                 let shiftwidth = a:shiftwidth
1049                 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1050                 " we assume no one has shiftwidth set to more than 40 :)
1051                 return '                                        '[0:shiftwidth]
1052         endif
1053 endfunction
1054
1055 " --- --- compose screen helper functions {{{2
1056
1057 function! s:NM_compose_get_user_email()
1058         let name = substitute(system('id -u -n'), '\v(^\s*|\s*$|\n)', '', 'g')
1059         let fqdn = substitute(system('hostname -f'), '\v(^\s*|\s*$|\n)', '', 'g')
1060
1061         " TODO: do this properly
1062         return name . '@' . fqdn
1063 endfunction
1064
1065 function! s:NM_compose_find_line_match(start, pattern, failure)
1066         let lnum = a:start
1067         let lend = line('$')
1068         while lnum < lend
1069                 if match(getline(lnum), a:pattern) != -1
1070                         return lnum
1071                 endif
1072                 let lnum = lnum + 1
1073         endwhile
1074         return a:failure
1075 endfunction
1076
1077
1078 " --- notmuch helper functions {{{1
1079
1080 function! s:NM_newBuffer(how, type, content)
1081         if strlen(a:how)
1082                 exec a:how
1083         else
1084                 enew
1085         endif
1086         setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1087         silent put=a:content
1088         keepjumps 0d
1089         setlocal nomodifiable
1090         execute printf('set filetype=notmuch-%s', a:type)
1091         execute printf('set syntax=notmuch-%s', a:type)
1092         let b:nm_type = a:type
1093 endfunction
1094
1095 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1096         let fdir = expand(a:fdir)
1097         if !isdirectory(fdir)
1098                 call mkdir(fdir, 'p')
1099         endif
1100         let file_name = <SID>NM_mktemp(fdir, a:fname)
1101         if writefile(a:lines, file_name)
1102                 throw 'Eeek! couldn''t write to temporary file ' . file_name
1103         endif
1104         exec printf('edit %s', file_name)
1105         setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1106         execute printf('set filetype=notmuch-%s', a:type)
1107         execute printf('set syntax=notmuch-%s', a:type)
1108         let b:nm_type = a:type
1109 endfunction
1110
1111 function! s:NM_newComposeBuffer(lines, start_on_line)
1112         let lines = a:lines
1113         let start_on_line = a:start_on_line
1114         let real_hdr_start = 1
1115         if g:notmuch_compose_header_help
1116                 let help_lines = [
1117                   \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1118                   \ 'Notmuch-Help:   ,a    - attach a file',
1119                   \ 'Notmuch-Help:   ,s    - send the message (Notmuch-Help lines will be removed)',
1120                   \ 'Notmuch-Help:   ,q    - abort the message',
1121                   \ 'Notmuch-Help:   <Tab> - skip through header lines',
1122                   \ ]
1123                 call extend(lines, help_lines, 0)
1124                 let real_hdr_start = len(help_lines)
1125                 if start_on_line > 0
1126                         let start_on_line = start_on_line + len(help_lines)
1127                 endif
1128         endif
1129         call extend(lines, g:notmuch_signature)
1130
1131
1132         let prev_bufnr = bufnr('%')
1133         setlocal bufhidden=hide
1134         call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1135                                   \ 'compose', lines)
1136         setlocal bufhidden=hide
1137         let b:nm_prev_bufnr = prev_bufnr
1138
1139         call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1140         call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1141
1142         if start_on_line > 0 && start_on_line <= len(lines)
1143                 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1144         else
1145                 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1146                 call <SID>NM_compose_next_entry_area()
1147         endif
1148
1149         if g:notmuch_compose_insert_mode_start
1150                 startinsert!
1151         endif
1152         echo 'Type your message, use <TAB> to jump to next header and then body.'
1153 endfunction
1154
1155 function! s:NM_assert_buffer_type(type)
1156         if !exists('b:nm_type') || b:nm_type != a:type
1157                 throw printf('Eeek! expected type %s, but got %s.', a:type,
1158                             \ exists(b:nm_type) ? b:nm_type : 'something else')
1159         endif
1160 endfunction
1161
1162 function! s:NM_mktemp(dir, name)
1163         let time_stamp = strftime('%Y%m%d-%H%M%S')
1164         let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1165         " TODO: check if it exists, try again
1166         return file_name
1167 endfunction
1168
1169 function! s:NM_shell_escape(word)
1170         " TODO: use shellescape()
1171         let word = substitute(a:word, '''', '\\''', 'g')
1172         return '''' . word . ''''
1173 endfunction
1174
1175 " this function was taken from git.vim, then fixed up
1176 " http://github.com/motemen/git-vim
1177 function! s:NM_shell_split(cmd)
1178         let l:split_cmd = []
1179         let cmd = a:cmd
1180         let iStart = 0
1181         while 1
1182                 let t = match(cmd, '\S', iStart)
1183                 if t < iStart
1184                         break
1185                 endif
1186                 let iStart = t
1187
1188                 let iSpace = match(cmd, '\v(\s|$)', iStart)
1189                 if iSpace < iStart
1190                         break
1191                 endif
1192
1193                 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1194                 if iQuote1 > iSpace || iQuote1 < iStart
1195                         let iEnd = iSpace - 1
1196                         let l:split_cmd += [ cmd[iStart : iEnd] ]
1197                 else
1198                         let q = cmd[iQuote1]
1199                         let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1200                         if iQuote2 < iQuote1
1201                                 throw 'No matching ' . q . ' quote'
1202                         endif
1203                         let iEnd = iQuote2
1204                         let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1205                 endif
1206
1207
1208                 let iStart = iEnd + 1
1209         endwhile
1210
1211         return l:split_cmd
1212 endfunction
1213
1214
1215 function! s:NM_run(args)
1216         let words = a:args
1217         call map(words, 's:NM_shell_escape(v:val)')
1218         let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1219
1220         let start = reltime()
1221         let out = system(cmd)
1222         let err = v:shell_error
1223         let delta = reltime(start)
1224
1225         if exists('g:notmuch_debug') && g:notmuch_debug
1226                 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1227         endif
1228
1229         if err
1230                 echohl Error
1231                 echo substitute(out, '\n*$', '', '')
1232                 echohl None
1233                 return ''
1234         else
1235                 return out
1236         endif
1237 endfunction
1238
1239 " --- external mail handling helpers {{{1
1240
1241 function! s:NM_new_mail()
1242         call <SID>NM_cmd_compose([], [])
1243 endfunction
1244
1245 " --- tag manipulation helpers {{{1
1246
1247 " used to combine an array of words with prefixes and separators
1248 " example:
1249 "     NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1250 "  -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1251 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1252         let res = []
1253         for word in a:words
1254                 if len(res) && strlen(a:separator)
1255                         call add(res, a:separator)
1256                 endif
1257                 call add(res, a:word_prefix . word)
1258         endfor
1259         if len(res) > 1 && strlen(a:brackets)
1260                 if strlen(a:brackets) != 2
1261                         throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1262                 endif
1263                 call insert(res, a:brackets[0])
1264                 call add(res, a:brackets[1])
1265         endif
1266         return res
1267 endfunction
1268
1269 " --- other helpers {{{1
1270
1271 function! s:NM_get_search_words()
1272         if !exists('b:nm_search_words')
1273                 throw 'Eeek! no b:nm_search_words'
1274         endif
1275         return b:nm_search_words
1276 endfunction
1277
1278 function! s:NM_kill_this_buffer()
1279         if exists('b:nm_prev_bufnr')
1280                 let prev_bufnr = b:nm_prev_bufnr
1281                 bdelete!
1282                 exec printf("buffer %d", prev_bufnr)
1283         else
1284                 echo "This is the last buffer; use :q<CR> to quit."
1285         endif
1286 endfunction
1287
1288 function! s:NM_search_expand(arg)
1289         let word = expand(a:arg)
1290         let prev_bufnr = bufnr('%')
1291         setlocal bufhidden=hide
1292         call <SID>NM_cmd_search([word])
1293         setlocal bufhidden=delete
1294         let b:nm_prev_bufnr = prev_bufnr
1295 endfunction
1296
1297 function! s:NM_add_remove_tags(filter, prefix, tags)
1298         let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1299         if !len(filter)
1300                 throw 'Eeek! I couldn''t find the thead id!'
1301         endif
1302         call map(a:tags, 'a:prefix . v:val')
1303         let args = ['tag']
1304         call extend(args, a:tags)
1305         call add(args, '--')
1306         call extend(args, filter)
1307         " TODO: handle errors
1308         call <SID>NM_run(args)
1309 endfunction
1310
1311 function! s:NM_add_remove_tags_on_screen(online, prefix, tags)
1312         setlocal modifiable
1313         if a:prefix == '-'
1314                 for tagname in a:tags
1315                         exec printf('silent! %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', string(a:online), tagname)
1316                 endfor
1317         else
1318                 for tagname in a:tags
1319                         exec printf('silent! %ss/(\([^)]*\))$/(\1 %s)/', string(a:online), tagname)
1320                 endfor
1321         endif
1322         setlocal nomodifiable
1323 endfunction
1324
1325 " --- process and set the defaults {{{1
1326
1327 function! NM_set_defaults(force)
1328         for [key, dflt] in items(s:notmuch_defaults)
1329                 let cmd = ''
1330                 if !a:force && exists(key) && type(dflt) == type(eval(key))
1331                         continue
1332                 elseif type(dflt) == type(0)
1333                         let cmd = printf('let %s = %d', key, dflt)
1334                 elseif type(dflt) == type('')
1335                         let cmd = printf('let %s = ''%s''', key, dflt)
1336                 " FIXME: not sure why this didn't work when dflt is an array
1337                 "elseif type(dflt) == type([])
1338                 "        let cmd = printf('let %s = %s', key, string(dflt))
1339                 else
1340                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1341                                                 \ a:force, key, string(dflt))
1342                         continue
1343                 endif
1344                 exec cmd
1345         endfor
1346 endfunction
1347 call NM_set_defaults(0)
1348
1349 " for some reason NM_set_defaults() didn't work for arrays...
1350 if !exists('g:notmuch_show_headers')
1351         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1352 endif
1353 if !exists('g:notmuch_initial_search_words')
1354         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1355 endif
1356 if !exists('g:notmuch_folders')
1357         let g:notmuch_folders = s:notmuch_folders_defaults
1358 endif
1359
1360 if !exists('g:notmuch_signature')
1361         let g:notmuch_signature = s:notmuch_signature_defaults
1362 endif
1363 if !exists('g:notmuch_compose_headers')
1364         let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1365 endif
1366
1367 " --- assign keymaps {{{1
1368
1369 function! s:NM_set_map(type, maps)
1370         nmapclear
1371         for [key, code] in items(a:maps)
1372                 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1373         endfor
1374         " --- this is a hack for development :)
1375         nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1376 endfunction
1377
1378 " --- command handler {{{1
1379
1380 function! NotMuch(args)
1381         let args = a:args
1382         if !strlen(args)
1383                 let args = 'folders'
1384         endif
1385
1386         let words = <SID>NM_shell_split(args)
1387         if words[0] == 'folders' || words[0] == 'f'
1388                 let words = words[1:]
1389                 call <SID>NM_cmd_folders(words)
1390
1391         elseif words[0] == 'search' || words[0] == 's'
1392                 if len(words) > 1
1393                         let words = words[1:]
1394                 elseif exists('b:nm_search_words')
1395                         let words = b:nm_search_words
1396                 else
1397                         let words = g:notmuch_initial_search_words
1398                 endif
1399                 call <SID>NM_cmd_search(words)
1400
1401         elseif words[0] == 'show'
1402                 echoe 'show is not yet implemented.'
1403
1404         elseif words[0] == 'new' || words[0] == 'compose'
1405                 let words = words[1:]
1406                 call <SID>NM_cmd_compose(words, [])
1407         endif
1408 endfunction
1409 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1410         return []
1411 endfunction
1412
1413
1414 " --- glue {{{1
1415
1416 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1417 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1418
1419 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :