]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
vim: refactor tagging stuff
[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_tag([], ['-inbox'])
312         norm j
313 endfunction
314
315 function! s:NM_search_mark_read_then_archive_thread()
316         call <SID>NM_tag([], ['-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 map(tags, 'a:prefix . v:val')
408         call <SID>NM_tag([], tags)
409 endfunction
410
411 " --- implement show screen {{{1
412
413 function! s:NM_cmd_show(words)
414         let prev_bufnr = bufnr('%')
415         let data = s:NM_run(['show', '--entire-thread'] + a:words)
416         let lines = split(data, "\n")
417
418         let info = s:NM_cmd_show_parse(lines)
419
420         setlocal bufhidden=hide
421         call <SID>NM_newBuffer('', 'show', join(info['disp'], "\n"))
422         setlocal bufhidden=delete
423         let b:nm_search_words = a:words
424         let b:nm_raw_info = info
425         let b:nm_prev_bufnr = prev_bufnr
426
427         call <SID>NM_cmd_show_mkfolds()
428         call <SID>NM_cmd_show_mksyntax()
429         call <SID>NM_set_map('n', g:notmuch_show_maps)
430         setlocal foldtext=NM_cmd_show_foldtext()
431         setlocal fillchars=
432         setlocal foldcolumn=6
433
434 endfunction
435
436 function! s:NM_show_previous(can_change_thread, find_matching)
437         let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
438         let info = b:nm_raw_info
439         let lnum = line('.')
440         for msg in reverse(copy(info['msgs']))
441                 if a:find_matching && msg['match'] == '0'
442                         continue
443                 endif
444                 if lnum <= msg['start']
445                         continue
446                 endif
447
448                 exec printf('norm %dGzt', msg['start'])
449                 " TODO: try to fit the message on screen
450                 return
451         endfor
452         if !a:can_change_thread
453                 return
454         endif
455         call <SID>NM_kill_this_buffer()
456         if line('.') > 1
457                 norm k
458                 call <SID>NM_search_show_thread(everything)
459                 norm G
460                 call <SID>NM_show_previous(0, a:find_matching)
461         else
462                 echo 'No more messages.'
463         endif
464 endfunction
465
466 function! s:NM_show_next(can_change_thread, find_matching)
467         let info = b:nm_raw_info
468         let lnum = line('.')
469         for msg in info['msgs']
470                 if a:find_matching && msg['match'] == '0'
471                         continue
472                 endif
473                 if lnum >= msg['start']
474                         continue
475                 endif
476
477                 exec printf('norm %dGzt', msg['start'])
478                 " TODO: try to fit the message on screen
479                 return
480         endfor
481         if a:can_change_thread
482                 call <SID>NM_show_next_thread()
483         endif
484 endfunction
485
486 function! s:NM_show_next_thread()
487         let everything = exists('b:nm_show_everything') ? b:nm_show_everything : 0
488         call <SID>NM_kill_this_buffer()
489         if line('.') != line('$')
490                 norm j
491                 call <SID>NM_search_show_thread(everything)
492         else
493                 echo 'No more messages.'
494         endif
495 endfunction
496
497 function! s:NM_show_archive_thread()
498         echo 'not implemented'
499 endfunction
500
501 function! s:NM_show_mark_read_then_archive_thread()
502         call <SID>NM_tag(b:nm_search_words, ['-unread', '-inbox'])
503         call <SID>NM_show_next_thread()
504 endfunction
505
506 function! s:NM_show_mark_read_then_next_open_message()
507         echo 'not implemented'
508 endfunction
509
510 function! s:NM_show_previous_message()
511         echo 'not implemented'
512 endfunction
513
514 function! s:NM_show_reply()
515         let cmd = ['reply']
516         call add(cmd, <SID>NM_show_message_id())
517         call add(cmd, 'AND')
518         call extend(cmd, <SID>NM_get_search_words())
519
520         let data = <SID>NM_run(cmd)
521         let lines = split(data, "\n")
522         call <SID>NM_newComposeBuffer(lines, 0)
523 endfunction
524
525 function! s:NM_show_view_all_mime_parts()
526         echo 'not implemented'
527 endfunction
528
529 function! s:NM_show_view_raw_message()
530         echo 'not implemented'
531 endfunction
532
533 function! s:NM_show_add_tag()
534         echo 'not implemented'
535 endfunction
536
537 function! s:NM_show_remove_tag()
538         echo 'not implemented'
539 endfunction
540
541 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
542 " otherwise go to next message
543 " any message that is viewed entirely has inbox and unread tags removed
544 function! s:NM_show_advance_marking_read_and_archiving()
545         let advance_tags = ['unread', 'inbox']
546
547         let vis_top = line('w0')
548         let vis_bot = line('w$')
549
550         let msg_top = <SID>NM_show_get_message_for_line(vis_top)
551         if !has_key(msg_top,'id')
552                 throw "No top visible message."
553         endif
554
555         " if the top message is the last message, just expunge the entire thread and move on
556         if msg_top['end'] == line('$')
557                 let ids = []
558                 for msg in b:nm_raw_info['msgs']
559                         if has_key(msg,'match') && msg['match'] != '0'
560                                 call add(ids, msg['id'])
561                         endif
562                 endfor
563                 let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
564                          \ + ['AND']
565                          \ + <SID>NM_combine_tags('', ids, 'OR', '()')
566                 call map(advance_tags, '"+" . v:val')
567                 call <SID>NM_tag(filter, advance_tags)
568                 call <SID>NM_show_next(1, 1)
569                 return
570         endif
571
572         let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
573         if !has_key(msg_bot,'id')
574                 throw "No bottom visible message."
575         endif
576
577         " if entire message fits on the screen, read/archive it, move to the next one
578         if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
579                 exec printf('norm %dG', vis_top)
580                 call <SID>NM_show_next(0, 1)
581                 if has_key(msg_top,'match') && msg_top['match'] != '0'
582                         redraw
583                         " do this last to hide the latency
584                         let filter = <SID>NM_combine_tags('tag:', advance_tags, 'OR', '()')
585                                  \ + ['AND', msg_top['id']]
586                         call map(advance_tags, '"-" . v:val')
587                         call <SID>NM_tag(filter, advance_tags)
588                 endif
589                 return
590         endif
591
592         " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
593         let jmp = winheight(winnr()) / 2
594         let max = msg_bot['end'] - vis_bot
595         if jmp > max
596                 let jmp = max
597         endif
598         exec printf('norm %dGzt', vis_top + jmp)
599         return
600 endfunction
601
602 function! s:NM_show_pipe_message()
603         echo 'not implemented'
604 endfunction
605
606 function! s:NM_show_previous_fold()
607         echo 'not implemented'
608 endfunction
609
610 function! s:NM_show_next_fold()
611         echo 'not implemented'
612 endfunction
613
614 function! s:NM_show_toggle_fold()
615         echo 'not implemented'
616 endfunction
617
618
619 " --- --- show screen helper functions {{{2
620
621 function! s:NM_show_get_message_for_line(line)
622         for msg in b:nm_raw_info['msgs']
623                 if a:line > msg['end']
624                         continue
625                 endif
626                 return msg
627         endfor
628         return {}
629 endfunction
630
631 function! s:NM_show_message_id()
632         if !exists('b:nm_raw_info')
633                 throw 'Eeek! no b:nm_raw_info'
634         endif
635         let msg = <SID>NM_show_get_message_for_line(line('.'))
636         if has_key(msg,'id')
637                 return msg['id']
638         endif
639         return ''
640 endfunction
641
642 function! s:NM_show_fold_toggle(key, type, fold)
643         let info = b:nm_raw_info
644         let act = 'open'
645         if a:fold
646                 let act = 'close'
647         endif
648         for fld in info['folds']
649                 if fld[0] != a:type
650                         continue
651                 endif
652                 "let idx = fld[3]
653                 "let msg = info['msgs'][idx]
654                 "if has_key(msg,'match') && msg['match'] == '0'
655                 "        continue
656                 "endif
657                 let cls = foldclosed(fld[1])
658                 if cls != -1 && cls != fld[1]
659                         continue
660                 endif
661                 exec printf('%dfold%s', fld[1], act)
662         endfor
663         exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
664 endfunction
665
666
667 " s:NM_cmd_show_parse returns the following dictionary:
668 "    'disp':     lines to display
669 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
670 "    'folds':    fold info arrays [ type, start, end ]
671 "    'foldtext': fold text indexed by start line
672 function! s:NM_cmd_show_parse(inlines)
673         let info = { 'disp': [],       
674                    \ 'msgs': [],       
675                    \ 'folds': [],      
676                    \ 'foldtext': {} }  
677         let msg = {}
678         let hdr = {}
679
680         let in_message = 0
681         let in_header = 0
682         let in_body = 0
683         let in_part = ''
684
685         let body_start = -1
686         let part_start = -1
687
688         let mode_type = ''
689         let mode_start = -1
690
691         let inlnum = 0
692         for line in a:inlines
693                 let inlnum = inlnum + 1
694                 let foldinfo = []
695
696                 if strlen(in_part)
697                         let part_end = 0
698
699                         if match(line, g:notmuch_show_part_end_regexp) != -1
700                                 let part_end = len(info['disp'])
701                         else
702                                 call add(info['disp'], line)
703                         endif
704
705                         if in_part == 'text/plain'
706                                 if !part_end && mode_type == ''
707                                         if match(line, g:notmuch_show_signature_regexp) != -1
708                                                 let mode_type = 'sig'
709                                                 let mode_start = len(info['disp'])
710                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
711                                                 let mode_type = 'cit'
712                                                 let mode_start = len(info['disp'])
713                                         endif
714                                 elseif mode_type == 'cit'
715                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
716                                                 let outlnum = len(info['disp'])
717                                                 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
718                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
719                                                 let mode_type = ''
720                                         endif
721                                 elseif mode_type == 'sig'
722                                         let outlnum = len(info['disp'])
723                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
724                                                 let mode_type = ''
725                                         elseif part_end
726                                                 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
727                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
728                                                 let mode_type = ''
729                                         endif
730                                 endif
731                         endif
732
733                         if part_end
734                                 " FIXME: this is a hack for handling two folds being added for one line
735                                 "         we should handle addinga fold in a function
736                                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
737                                         call add(info['folds'], foldinfo[0:3])
738                                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
739                                 endif
740
741                                 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
742                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
743                                 let in_part = ''
744                                 call add(info['disp'], '')
745                         endif
746
747                 elseif in_body
748                         if !has_key(msg,'body_start')
749                                 let msg['body_start'] = len(info['disp']) + 1
750                         endif
751                         if match(line, g:notmuch_show_body_end_regexp) != -1
752                                 let body_end = len(info['disp'])
753                                 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
754                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
755
756                                 let in_body = 0
757
758                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
759                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
760                                 let in_part = 'unknown'
761                                 if len(m)
762                                         let in_part = m[2]
763                                 endif
764                                 call add(info['disp'],
765                                          \ printf('--- %s ---', in_part))
766                                 let part_start = len(info['disp']) + 1
767                         endif
768
769                 elseif in_header
770                         if in_header == 1
771                                 let msg['descr'] = line
772                                 call add(info['disp'], line)
773                                 let in_header = 2
774                                 let msg['hdr_start'] = len(info['disp']) + 1
775
776                         else
777                                 if match(line, g:notmuch_show_header_end_regexp) != -1
778                                         let hdr_start = msg['hdr_start']+1
779                                         let hdr_end = len(info['disp'])
780                                         let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
781                                                \ printf('[ %d-line headers.  Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
782                                         let msg['header'] = hdr
783                                         let in_header = 0
784                                         let hdr = {}
785                                 else
786                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
787                                         if len(m)
788                                                 let hdr[m[1]] = m[2]
789                                                 if match(g:notmuch_show_headers, m[1]) != -1
790                                                         call add(info['disp'], line)
791                                                 endif
792                                         endif
793                                 endif
794                         endif
795
796                 elseif in_message
797                         if match(line, g:notmuch_show_message_end_regexp) != -1
798                                 let msg['end'] = len(info['disp'])
799                                 call add(info['disp'], '')
800
801                                 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
802                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
803
804                                 call add(info['msgs'], msg)
805                                 let msg = {}
806                                 let in_message = 0
807                                 let in_header = 0
808                                 let in_body = 0
809                                 let in_part = ''
810
811                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
812                                 let in_header = 1
813                                 continue
814
815                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
816                                 let body_start = len(info['disp']) + 1
817                                 let in_body = 1
818                                 continue
819                         endif
820
821                 else
822                         if match(line, g:notmuch_show_message_begin_regexp) != -1
823                                 let msg['start'] = len(info['disp']) + 1
824
825                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
826                                 if len(m)
827                                         let msg['id'] = m[1]
828                                         let msg['depth'] = m[2]
829                                         let msg['match'] = m[3]
830                                         let msg['filename'] = m[4]
831                                 endif
832
833                                 let in_message = 1
834                         endif
835                 endif
836
837                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
838                         call add(info['folds'], foldinfo[0:3])
839                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
840                 endif
841         endfor
842         return info
843 endfunction
844
845 function! s:NM_cmd_show_mkfolds()
846         let info = b:nm_raw_info
847
848         for afold in info['folds']
849                 exec printf('%d,%dfold', afold[1], afold[2])
850                 let state = 'open'
851                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
852                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
853                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
854                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
855                         let state = 'close'
856                 elseif afold[0] == 'msg'
857                         let idx = afold[3]
858                         let msg = info['msgs'][idx]
859                         if has_key(msg,'match') && msg['match'] == '0'
860                                 let state = 'close'
861                         endif
862                 endif
863                 exec printf('%dfold%s', afold[1], state)
864         endfor
865 endfunction
866
867 function! s:NM_cmd_show_mksyntax()
868         let info = b:nm_raw_info
869         let cnt = 0
870         for msg in info['msgs']
871                 let cnt = cnt + 1
872                 let start = msg['start']
873                 let hdr_start = msg['hdr_start']
874                 let body_start = msg['body_start']
875                 let end = msg['end']
876                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
877                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
878                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
879         endfor
880 endfunction
881
882 function! NM_cmd_show_foldtext()
883         let foldtext = b:nm_raw_info['foldtext']
884         return foldtext[v:foldstart]
885 endfunction
886
887
888 " --- implement compose screen {{{1
889
890 function! s:NM_cmd_compose(words, body_lines)
891         let lines = []
892         let start_on_line = 0
893
894         let hdrs = { }
895         for word in a:words
896                 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
897                 if !len(m)
898                         throw 'Eeek! bad parameter ''' . string(word) . ''''
899                 endif
900                 let key = substitute(m[1], '\<\w', '\U&', 'g')
901                 if !has_key(hdrs, key)
902                         let hdrs[key] = []
903                 endif
904                 if strlen(m[2])
905                         call add(hdrs[key], m[2])
906                 endif
907         endfor
908
909         if !has_key(hdrs, 'From') || !len(hdrs['From'])
910                 let me = <SID>NM_compose_get_user_email()
911                 let hdrs['From'] = [ me ]
912         endif
913
914         for key in g:notmuch_compose_headers
915                 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
916                 call add(lines, key . ': ' . text)
917                 if !start_on_line && !strlen(text)
918                         let start_on_line = len(lines)
919                 endif
920         endfor
921
922         for [key,val] in items(hdrs)
923                 if match(g:notmuch_compose_headers, key) == -1
924                         let line = key . ': ' . join(val, ', ')
925                         call add(lines, line)
926                 endif
927         endfor
928
929         call add(lines, '')
930         if !start_on_line
931                 let start_on_line = len(lines) + 1
932         endif
933
934         if len(a:body_lines)
935                 call extend(lines, a:body_lines)
936         else
937                 call extend(lines, [ '', '' ])
938         endif
939
940         call <SID>NM_newComposeBuffer(lines, start_on_line)
941 endfunction
942
943 function! s:NM_compose_send()
944         call <SID>NM_assert_buffer_type('compose')
945         let fname = expand('%')
946         let lnum = 1
947         let line = getline(lnum)
948         let lst_hdr = ''
949         while match(line, '^$') == -1
950                 if match(line, '^Notmuch-Help:') == -1
951                         let hdr_starts = lnum - 1
952                         break
953                 endif
954                 let lnum = lnum + 1
955                 let line = getline(lnum)
956         endwhile
957
958         exec printf(':0,%dd', hdr_starts)
959         write
960
961         let cmdtxt = 'mailx -t < ' . fname
962         let out = system(cmdtxt)
963         let err = v:shell_error
964         if err
965                 undo
966                 write
967                 call <SID>NM_newBuffer('new', 'error',
968                             \ "While running...\n" .
969                             \ '  ' . cmdtxt . "\n" .
970                             \ "\n" .
971                             \ "Failed with...\n" .
972                             \ substitute(out, '^', '  ', 'g'))
973                 echohl Error
974                 echo 'Eeek! unable to send mail'
975                 echohl None
976                 return
977         endif
978
979         if !exists('b:nm_prev_bufnr')
980                 bdelete
981         else
982                 let prev_bufnr = b:nm_prev_bufnr
983                 bdelete
984                 if prev_bufnr == bufnr('%')
985                         exec printf("buffer %d", prev_bufnr)
986                 endif
987         endif
988         call delete(fname)
989         echo 'Mail sent successfully.'
990 endfunction
991
992 function! s:NM_compose_attach()
993         echo 'not implemented'
994 endfunction
995
996 function! s:NM_compose_next_entry_area()
997         let lnum = line('.')
998         let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
999         if lnum < hdr_end
1000                 let lnum = lnum + 1
1001                 let line = getline(lnum)
1002                 if match(line, '^\([^:]\+\):\s*$') == -1
1003                         call cursor(lnum, strlen(line) + 1)
1004                         return ''
1005                 endif
1006                 while match(getline(lnum+1), '^\s') != -1
1007                         let lnum = lnum + 1
1008                 endwhile
1009                 call cursor(lnum, strlen(getline(lnum)) + 1)
1010                 return ''
1011
1012         elseif lnum == hdr_end
1013                 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1014                 return ''
1015         endif
1016         if mode() == 'i'
1017                 if !getbufvar(bufnr('.'), '&et')
1018                         return "\t"
1019                 endif
1020                 let space = ''
1021                 let shiftwidth = a:shiftwidth
1022                 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1023                 " we assume no one has shiftwidth set to more than 40 :)
1024                 return '                                        '[0:shiftwidth]
1025         endif
1026 endfunction
1027
1028 " --- --- compose screen helper functions {{{2
1029
1030 function! s:NM_compose_get_user_email()
1031         " TODO: do this properly (still), i.e., allow for multiple email accounts
1032         let email = substitute(system('notmuch config get user.primary_email'), '\v(^\s*|\s*$|\n)', '', 'g')
1033         return email
1034 endfunction
1035
1036 function! s:NM_compose_find_line_match(start, pattern, failure)
1037         let lnum = a:start
1038         let lend = line('$')
1039         while lnum < lend
1040                 if match(getline(lnum), a:pattern) != -1
1041                         return lnum
1042                 endif
1043                 let lnum = lnum + 1
1044         endwhile
1045         return a:failure
1046 endfunction
1047
1048
1049 " --- notmuch helper functions {{{1
1050
1051 function! s:NM_newBuffer(how, type, content)
1052         if strlen(a:how)
1053                 exec a:how
1054         else
1055                 enew
1056         endif
1057         setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1058         silent put=a:content
1059         keepjumps 0d
1060         setlocal nomodifiable
1061         execute printf('set filetype=notmuch-%s', a:type)
1062         execute printf('set syntax=notmuch-%s', a:type)
1063         let b:nm_type = a:type
1064 endfunction
1065
1066 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1067         let fdir = expand(a:fdir)
1068         if !isdirectory(fdir)
1069                 call mkdir(fdir, 'p')
1070         endif
1071         let file_name = <SID>NM_mktemp(fdir, a:fname)
1072         if writefile(a:lines, file_name)
1073                 throw 'Eeek! couldn''t write to temporary file ' . file_name
1074         endif
1075         exec printf('edit %s', file_name)
1076         setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1077         execute printf('set filetype=notmuch-%s', a:type)
1078         execute printf('set syntax=notmuch-%s', a:type)
1079         let b:nm_type = a:type
1080 endfunction
1081
1082 function! s:NM_newComposeBuffer(lines, start_on_line)
1083         let lines = a:lines
1084         let start_on_line = a:start_on_line
1085         let real_hdr_start = 1
1086         if g:notmuch_compose_header_help
1087                 let help_lines = [
1088                   \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
1089                   \ 'Notmuch-Help:   ,a    - attach a file',
1090                   \ 'Notmuch-Help:   ,s    - send the message (Notmuch-Help lines will be removed)',
1091                   \ 'Notmuch-Help:   ,q    - abort the message',
1092                   \ 'Notmuch-Help:   <Tab> - skip through header lines',
1093                   \ ]
1094                 call extend(lines, help_lines, 0)
1095                 let real_hdr_start = len(help_lines)
1096                 if start_on_line > 0
1097                         let start_on_line = start_on_line + len(help_lines)
1098                 endif
1099         endif
1100         call extend(lines, g:notmuch_signature)
1101
1102
1103         let prev_bufnr = bufnr('%')
1104         setlocal bufhidden=hide
1105         call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
1106                                   \ 'compose', lines)
1107         setlocal bufhidden=hide
1108         let b:nm_prev_bufnr = prev_bufnr
1109
1110         call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
1111         call <SID>NM_set_map('i', g:notmuch_compose_imaps)
1112
1113         if start_on_line > 0 && start_on_line <= len(lines)
1114                 call cursor(start_on_line, strlen(getline(start_on_line)) + 1)
1115         else
1116                 call cursor(real_hdr_start, strlen(getline(real_hdr_start)) + 1)
1117                 call <SID>NM_compose_next_entry_area()
1118         endif
1119
1120         if g:notmuch_compose_insert_mode_start
1121                 startinsert!
1122         endif
1123         echo 'Type your message, use <TAB> to jump to next header and then body.'
1124 endfunction
1125
1126 function! s:NM_assert_buffer_type(type)
1127         if !exists('b:nm_type') || b:nm_type != a:type
1128                 throw printf('Eeek! expected type %s, but got %s.', a:type,
1129                             \ exists(b:nm_type) ? b:nm_type : 'something else')
1130         endif
1131 endfunction
1132
1133 function! s:NM_mktemp(dir, name)
1134         let time_stamp = strftime('%Y%m%d-%H%M%S')
1135         let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1136         " TODO: check if it exists, try again
1137         return file_name
1138 endfunction
1139
1140 function! s:NM_shell_escape(word)
1141         " TODO: use shellescape()
1142         let word = substitute(a:word, '''', '\\''', 'g')
1143         return '''' . word . ''''
1144 endfunction
1145
1146 " this function was taken from git.vim, then fixed up
1147 " http://github.com/motemen/git-vim
1148 function! s:NM_shell_split(cmd)
1149         let l:split_cmd = []
1150         let cmd = a:cmd
1151         let iStart = 0
1152         while 1
1153                 let t = match(cmd, '\S', iStart)
1154                 if t < iStart
1155                         break
1156                 endif
1157                 let iStart = t
1158
1159                 let iSpace = match(cmd, '\v(\s|$)', iStart)
1160                 if iSpace < iStart
1161                         break
1162                 endif
1163
1164                 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1165                 if iQuote1 > iSpace || iQuote1 < iStart
1166                         let iEnd = iSpace - 1
1167                         let l:split_cmd += [ cmd[iStart : iEnd] ]
1168                 else
1169                         let q = cmd[iQuote1]
1170                         let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1171                         if iQuote2 < iQuote1
1172                                 throw 'No matching ' . q . ' quote'
1173                         endif
1174                         let iEnd = iQuote2
1175                         let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1176                 endif
1177
1178
1179                 let iStart = iEnd + 1
1180         endwhile
1181
1182         return l:split_cmd
1183 endfunction
1184
1185
1186 function! s:NM_run(args)
1187         let words = a:args
1188         call map(words, 's:NM_shell_escape(v:val)')
1189         let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1190
1191         if exists('g:notmuch_debug') && g:notmuch_debug
1192                 let start = reltime()
1193                 let out = system(cmd)
1194                 let err = v:shell_error
1195                 let delta = reltime(start)
1196
1197                 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1198         else
1199                 let out = system(cmd)
1200                 let err = v:shell_error
1201         endif
1202
1203         if err
1204                 echohl Error
1205                 echo substitute(out, '\n*$', '', '')
1206                 echohl None
1207                 return ''
1208         else
1209                 return out
1210         endif
1211 endfunction
1212
1213 " --- external mail handling helpers {{{1
1214
1215 function! s:NM_new_mail()
1216         call <SID>NM_cmd_compose([], [])
1217 endfunction
1218
1219 " --- tag manipulation helpers {{{1
1220
1221 " used to combine an array of words with prefixes and separators
1222 " example:
1223 "     NM_combine_tags('tag:', ['one', 'two', 'three'], 'OR', '()')
1224 "  -> ['(', 'tag:one', 'OR', 'tag:two', 'OR', 'tag:three', ')']
1225 function! s:NM_combine_tags(word_prefix, words, separator, brackets)
1226         let res = []
1227         for word in a:words
1228                 if len(res) && strlen(a:separator)
1229                         call add(res, a:separator)
1230                 endif
1231                 call add(res, a:word_prefix . word)
1232         endfor
1233         if len(res) > 1 && strlen(a:brackets)
1234                 if strlen(a:brackets) != 2
1235                         throw 'Eeek! brackets arg to NM_combine_tags must be 2 chars'
1236                 endif
1237                 call insert(res, a:brackets[0])
1238                 call add(res, a:brackets[1])
1239         endif
1240         return res
1241 endfunction
1242
1243 " --- other helpers {{{1
1244
1245 function! s:NM_get_search_words()
1246         if !exists('b:nm_search_words')
1247                 throw 'Eeek! no b:nm_search_words'
1248         endif
1249         return b:nm_search_words
1250 endfunction
1251
1252 function! s:NM_kill_this_buffer()
1253         if exists('b:nm_prev_bufnr')
1254                 let prev_bufnr = b:nm_prev_bufnr
1255                 bdelete!
1256                 exec printf("buffer %d", prev_bufnr)
1257         else
1258                 echo "This is the last buffer; use :q<CR> to quit."
1259         endif
1260 endfunction
1261
1262 function! s:NM_search_expand(arg)
1263         let word = expand(a:arg)
1264         let prev_bufnr = bufnr('%')
1265         setlocal bufhidden=hide
1266         call <SID>NM_cmd_search([word])
1267         setlocal bufhidden=delete
1268         let b:nm_prev_bufnr = prev_bufnr
1269 endfunction
1270
1271 function! s:NM_tag(filter, tags)
1272         let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1273         if !len(filter)
1274                 throw 'Eeek! I couldn''t find the thead id!'
1275         endif
1276         let args = ['tag']
1277         call extend(args, a:tags)
1278         call add(args, '--')
1279         call extend(args, filter)
1280         " TODO: handle errors
1281         call <SID>NM_run(args)
1282 endfunction
1283
1284 " --- process and set the defaults {{{1
1285
1286 function! NM_set_defaults(force)
1287         for [key, dflt] in items(s:notmuch_defaults)
1288                 let cmd = ''
1289                 if !a:force && exists(key) && type(dflt) == type(eval(key))
1290                         continue
1291                 elseif type(dflt) == type(0)
1292                         let cmd = printf('let %s = %d', key, dflt)
1293                 elseif type(dflt) == type('')
1294                         let cmd = printf('let %s = ''%s''', key, dflt)
1295                 " FIXME: not sure why this didn't work when dflt is an array
1296                 "elseif type(dflt) == type([])
1297                 "        let cmd = printf('let %s = %s', key, string(dflt))
1298                 else
1299                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1300                                                 \ a:force, key, string(dflt))
1301                         continue
1302                 endif
1303                 exec cmd
1304         endfor
1305 endfunction
1306 call NM_set_defaults(0)
1307
1308 " for some reason NM_set_defaults() didn't work for arrays...
1309 if !exists('g:notmuch_show_headers')
1310         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1311 endif
1312 if !exists('g:notmuch_initial_search_words')
1313         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1314 endif
1315 if !exists('g:notmuch_folders')
1316         let g:notmuch_folders = s:notmuch_folders_defaults
1317 endif
1318
1319 if !exists('g:notmuch_signature')
1320         let g:notmuch_signature = s:notmuch_signature_defaults
1321 endif
1322 if !exists('g:notmuch_compose_headers')
1323         let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1324 endif
1325
1326 " --- assign keymaps {{{1
1327
1328 function! s:NM_set_map(type, maps)
1329         nmapclear
1330         for [key, code] in items(a:maps)
1331                 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1332         endfor
1333         " --- this is a hack for development :)
1334         nnoremap ,nmr :runtime! plugin/notmuch.vim<CR>
1335 endfunction
1336
1337 " --- command handler {{{1
1338
1339 function! NotMuch(args)
1340         let args = a:args
1341         if !strlen(args)
1342                 let args = 'folders'
1343         endif
1344
1345         let words = <SID>NM_shell_split(args)
1346         if words[0] == 'folders' || words[0] == 'f'
1347                 let words = words[1:]
1348                 call <SID>NM_cmd_folders(words)
1349
1350         elseif words[0] == 'search' || words[0] == 's'
1351                 if len(words) > 1
1352                         let words = words[1:]
1353                 elseif exists('b:nm_search_words')
1354                         let words = b:nm_search_words
1355                 else
1356                         let words = g:notmuch_initial_search_words
1357                 endif
1358                 call <SID>NM_cmd_search(words)
1359
1360         elseif words[0] == 'show'
1361                 echoe 'show is not yet implemented.'
1362
1363         elseif words[0] == 'new' || words[0] == 'compose'
1364                 let words = words[1:]
1365                 call <SID>NM_cmd_compose(words, [])
1366         endif
1367 endfunction
1368 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1369         return []
1370 endfunction
1371
1372
1373 " --- glue {{{1
1374
1375 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1376 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1377
1378 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :