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