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