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