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