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