]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
vim: cleanup error messages
[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()<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_show_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_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_search_words()
632         if !exists('b:nm_words')
633                 throw 'Eeek! no b:nm_words'
634         endif
635         return b:nm_words
636 endfunction
637
638 function! s:NM_show_fold_toggle(key, type, fold)
639         let info = b:nm_raw_info
640         let act = 'open'
641         if a:fold
642                 let act = 'close'
643         endif
644         for fld in info['folds']
645                 if fld[0] == a:type
646                         exec printf('%dfold%s', fld[1], act)
647                 endif
648         endfor
649         exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
650 endfunction
651
652
653 " s:NM_cmd_show_parse returns the following dictionary:
654 "    'disp':     lines to display
655 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
656 "    'folds':    fold info arrays [ type, start, end ]
657 "    'foldtext': fold text indexed by start line
658 function! s:NM_cmd_show_parse(inlines)
659         let info = { 'disp': [],       
660                    \ 'msgs': [],       
661                    \ 'folds': [],      
662                    \ 'foldtext': {} }  
663         let msg = {}
664         let hdr = {}
665
666         let in_message = 0
667         let in_header = 0
668         let in_body = 0
669         let in_part = ''
670
671         let body_start = -1
672         let part_start = -1
673
674         let mode_type = ''
675         let mode_start = -1
676
677         let inlnum = 0
678         for line in a:inlines
679                 let inlnum = inlnum + 1
680                 let foldinfo = []
681
682                 if strlen(in_part)
683                         let part_end = 0
684
685                         if match(line, g:notmuch_show_part_end_regexp) != -1
686                                 let part_end = len(info['disp'])
687                         else
688                                 call add(info['disp'], line)
689                         endif
690
691                         if in_part == 'text/plain'
692                                 if !part_end && mode_type == ''
693                                         if match(line, g:notmuch_show_signature_regexp) != -1
694                                                 let mode_type = 'sig'
695                                                 let mode_start = len(info['disp'])
696                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
697                                                 let mode_type = 'cit'
698                                                 let mode_start = len(info['disp'])
699                                         endif
700                                 elseif mode_type == 'cit'
701                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
702                                                 let outlnum = len(info['disp'])
703                                                 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
704                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
705                                                 let mode_type = ''
706                                         endif
707                                 elseif mode_type == 'sig'
708                                         let outlnum = len(info['disp'])
709                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
710                                                 let mode_type = ''
711                                         elseif part_end
712                                                 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
713                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
714                                                 let mode_type = ''
715                                         endif
716                                 endif
717                         endif
718
719                         if part_end
720                                 " FIXME: this is a hack for handling two folds being added for one line
721                                 "         we should handle addinga fold in a function
722                                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
723                                         call add(info['folds'], foldinfo[0:3])
724                                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
725                                 endif
726
727                                 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
728                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
729                                 let in_part = ''
730                                 call add(info['disp'], '')
731                         endif
732
733                 elseif in_body
734                         if !has_key(msg,'body_start')
735                                 let msg['body_start'] = len(info['disp']) + 1
736                         endif
737                         if match(line, g:notmuch_show_body_end_regexp) != -1
738                                 let body_end = len(info['disp'])
739                                 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
740                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
741
742                                 let in_body = 0
743
744                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
745                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
746                                 let in_part = 'unknown'
747                                 if len(m)
748                                         let in_part = m[2]
749                                 endif
750                                 call add(info['disp'],
751                                          \ printf('--- %s ---', in_part))
752                                 let part_start = len(info['disp']) + 1
753                         endif
754
755                 elseif in_header
756                         if in_header == 1
757                                 let msg['descr'] = line
758                                 call add(info['disp'], line)
759                                 let in_header = 2
760                                 let msg['hdr_start'] = len(info['disp']) + 1
761
762                         else
763                                 if match(line, g:notmuch_show_header_end_regexp) != -1
764                                         let hdr_start = msg['hdr_start']+1
765                                         let hdr_end = len(info['disp'])
766                                         let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
767                                                \ printf('[ %d-line headers.  Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
768                                         let msg['header'] = hdr
769                                         let in_header = 0
770                                         let hdr = {}
771                                 else
772                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
773                                         if len(m)
774                                                 let hdr[m[1]] = m[2]
775                                                 if match(g:notmuch_show_headers, m[1]) != -1
776                                                         call add(info['disp'], line)
777                                                 endif
778                                         endif
779                                 endif
780                         endif
781
782                 elseif in_message
783                         if match(line, g:notmuch_show_message_end_regexp) != -1
784                                 let msg['end'] = len(info['disp'])
785                                 call add(info['disp'], '')
786
787                                 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
788                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
789
790                                 call add(info['msgs'], msg)
791                                 let msg = {}
792                                 let in_message = 0
793                                 let in_header = 0
794                                 let in_body = 0
795                                 let in_part = ''
796
797                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
798                                 let in_header = 1
799                                 continue
800
801                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
802                                 let body_start = len(info['disp']) + 1
803                                 let in_body = 1
804                                 continue
805                         endif
806
807                 else
808                         if match(line, g:notmuch_show_message_begin_regexp) != -1
809                                 let msg['start'] = len(info['disp']) + 1
810
811                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
812                                 if len(m)
813                                         let msg['id'] = m[1]
814                                         let msg['depth'] = m[2]
815                                         let msg['match'] = m[3]
816                                         let msg['filename'] = m[4]
817                                 endif
818
819                                 let in_message = 1
820                         endif
821                 endif
822
823                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
824                         call add(info['folds'], foldinfo[0:3])
825                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
826                 endif
827         endfor
828         return info
829 endfunction
830
831 function! s:NM_cmd_show_mkfolds()
832         let info = b:nm_raw_info
833
834         for afold in info['folds']
835                 exec printf('%d,%dfold', afold[1], afold[2])
836                 let state = 'open'
837                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
838                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
839                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
840                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
841                         let state = 'close'
842                 elseif afold[0] == 'msg'
843                         let idx = afold[3]
844                         let msg = info['msgs'][idx]
845                         if has_key(msg,'match') && msg['match'] == '0'
846                                 let state = 'close'
847                         endif
848                 endif
849                 exec printf('%dfold%s', afold[1], state)
850         endfor
851 endfunction
852
853 function! s:NM_cmd_show_mksyntax()
854         let info = b:nm_raw_info
855         let cnt = 0
856         for msg in info['msgs']
857                 let cnt = cnt + 1
858                 let start = msg['start']
859                 let hdr_start = msg['hdr_start']
860                 let body_start = msg['body_start']
861                 let end = msg['end']
862                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
863                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
864                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
865         endfor
866 endfunction
867
868 function! NM_cmd_show_foldtext()
869         let foldtext = b:nm_raw_info['foldtext']
870         return foldtext[v:foldstart]
871 endfunction
872
873
874 " --- implement compose screen {{{1
875
876 function! s:NM_cmd_compose(words, body_lines)
877         let lines = !g:notmuch_compose_header_help ? [] : [
878                   \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
879                   \ 'Notmuch-Help:   ,a    - attach a file',
880                   \ 'Notmuch-Help:   ,s    - send the message (Notmuch-Help lines will be removed)',
881                   \ 'Notmuch-Help:   ,q    - abort the message',
882                   \ 'Notmuch-Help:   <Tab> - skip through header lines',
883                   \ ]
884         let start_on_line = 0
885
886         let hdrs = { }
887         for word in a:words
888                 let m = matchlist(word, '^\(\w[^:]*\):\s*\(.*\)\s*$')
889                 if !len(m)
890                         throw 'Eeek! bad parameter ''' . string(word) . ''''
891                 endif
892                 let key = substitute(m[1], '\<\w', '\U&', 'g')
893                 if !has_key(hdrs, key)
894                         let hdrs[key] = []
895                 endif
896                 if strlen(m[2])
897                         call add(hdrs[key], m[2])
898                 endif
899         endfor
900
901         if !has_key(hdrs, 'From') || !len(hdrs['From'])
902                 let me = <SID>NM_compose_get_user_email()
903                 let hdrs['From'] = [ me ]
904         endif
905
906         for key in g:notmuch_compose_headers
907                 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
908                 call add(lines, key . ': ' . text)
909                 if !start_on_line && !strlen(text)
910                         let start_on_line = len(lines)
911                 endif
912         endfor
913
914         for [key,val] in items(hdrs)
915                 if match(g:notmuch_compose_headers, key) == -1
916                         let line = key . ': ' . join(val, ', ')
917                         call add(lines, line)
918                 endif
919         endfor
920
921         call extend(lines, [ '', '' ])
922         if !start_on_line
923                 let start_on_line = len(lines) + 1
924         endif
925
926         if len(a:body_lines)
927                 call extend(lines, a:body_lines)
928         else
929                 call add(lines, '')
930         endif
931         call extend(lines, g:notmuch_signature)
932
933         let prev_bufnr = bufnr('%')
934         setlocal bufhidden=hide
935         call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
936                                   \ 'compose', lines)
937         setlocal bufhidden=hide
938         let b:nm_prev_bufnr = prev_bufnr
939
940         call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
941         call <SID>NM_set_map('i', g:notmuch_compose_imaps)
942
943         call cursor(start_on_line, strlen(start_on_line) + 1)
944         if g:notmuch_compose_insert_mode_start
945                 startinsert!
946         endif
947         echo 'Type your message, use <TAB> to jump to next header and then body.'
948 endfunction
949
950 function! s:NM_compose_send()
951         call <SID>NM_assert_buffer_type('compose')
952         let fname = expand('%')
953         let lnum = 1
954         let line = getline(lnum)
955         let hdrs = {}
956         let lst_hdr = ''
957         while match(line, '^$') == -1
958                 if match(line, '^Notmuch-Help:') != -1
959                         " skip it
960                 elseif strlen(lst_hdr) && match(line, '^\s') != -1
961                         let hdrs[lst_hdr][-1] = hdrs[lst_hdr][-1] . substitute(line, '^\s*', ' ', '')
962                 else
963                         let m = matchlist(line, '^\(\w[^:]*\):\s*\(.*\)\s*$')
964                         if !len(m)
965                                 cursor(lnum, 0)
966                                 throw printf('Eeek! invalid header on line %d', lnum)
967                         endif
968                         let key = substitute(m[1], '\<\w', '\U&', 'g')
969                         if strlen(m[2])
970                                 if !has_key(hdrs, key)
971                                         let hdrs[key] = []
972                                 endif
973                                 call add(hdrs[key], m[2])
974                         endif
975                         let lst_hdr = key
976                 endif
977                 let lnum = lnum + 1
978                 let line = getline(lnum)
979         endwhile
980         let body_starts = lnum + 1
981         exec printf('0,%dd', body_starts)
982         write
983
984         "[-a header] [-b bcc-addr] [-c cc-addr] [-s subject] to-addr
985         let cmd = ['mail']
986         let tos = []
987         for [key, vals] in items(hdrs)
988                 if key == 'To'
989                         call extend(tos, vals)
990                 elseif key == 'Bcc'
991                         for adr in vals
992                                 call add(cmd, '-b')
993                                 call add(cmd, adr)
994                         endfor
995                 elseif key == 'Cc'
996                         for adr in vals
997                                 call add(cmd, '-c')
998                                 call add(cmd, adr)
999                         endfor
1000                 elseif key == 'Subject'
1001                         for txt in vals
1002                                 call add(cmd, '-s')
1003                                 call add(cmd, txt)
1004                         endfor
1005                 else
1006                         for val in vals
1007                                 call add(cmd, '-a')
1008                                 call add(cmd, key . ': ' . val)
1009                         endfor
1010                 endif
1011         endfor
1012         call extend(cmd, tos)
1013
1014         call map(cmd, 's:NM_shell_escape(v:val)')
1015         let cmdtxt = join(cmd) . '< ' . fname
1016         let out = system(cmdtxt)
1017         let err = v:shell_error
1018         if err
1019                 undo
1020                 write
1021                 call <SID>NM_newBuffer('new', 'error',
1022                             \ "While running...\n" .
1023                             \ '  ' . cmdtxt . "\n" .
1024                             \ "\n" .
1025                             \ "Failed with...\n" .
1026                             \ substitute(out, '^', '  ', 'g'))
1027                 echohl Error
1028                 echo 'Eeek! unable to send mail'
1029                 echohl None
1030                 return
1031         endif
1032
1033         if !exists('b:nm_prev_bufnr')
1034                 bdelete
1035         else
1036                 let prev_bufnr = b:nm_prev_bufnr
1037                 bdelete
1038                 if prev_bufnr == bufnr('%')
1039                         exec printf("buffer %d", prev_bufnr)
1040                 endif
1041         endif
1042         call delete(fname)
1043         echo 'Mail sent successfully.'
1044 endfunction
1045
1046 function! s:NM_compose_attach()
1047         echo 'not implemented'
1048 endfunction
1049
1050 function! s:NM_compose_next_entry_area()
1051         let lnum = line('.')
1052         let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
1053         if lnum < hdr_end
1054                 let lnum = lnum + 1
1055                 let line = getline(lnum)
1056                 if match(line, '^\([^:]\+\):\s*$') == -1
1057                         call cursor(lnum, strlen(line) + 1)
1058                         return ''
1059                 endif
1060                 while match(getline(lnum+1), '^\s') != -1
1061                         let lnum = lnum + 1
1062                 endwhile
1063                 call cursor(lnum, strlen(getline(lnum)) + 1)
1064                 return ''
1065
1066         elseif lnum == hdr_end
1067                 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
1068                 return ''
1069         endif
1070         if mode() == 'i'
1071                 if !getbufvar(bufnr('.'), '&et')
1072                         return "\t"
1073                 endif
1074                 let space = ''
1075                 let shiftwidth = a:shiftwidth
1076                 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
1077                 " we assume no one has shiftwidth set to more than 40 :)
1078                 return '                                        '[0:shiftwidth]
1079         endif
1080 endfunction
1081
1082 " --- --- compose screen helper functions {{{2
1083
1084 function! s:NM_compose_get_user_email()
1085         let name = substitute(system('id -u -n'), '\v(^\s*|\s*$|\n)', '', 'g')
1086         let fqdn = substitute(system('hostname -f'), '\v(^\s*|\s*$|\n)', '', 'g')
1087
1088         " TODO: do this properly
1089         return name . '@' . fqdn
1090 endfunction
1091
1092 function! s:NM_compose_find_line_match(start, pattern, failure)
1093         let lnum = a:start
1094         let lend = line('$')
1095         while lnum < lend
1096                 if match(getline(lnum), a:pattern) != -1
1097                         return lnum
1098                 endif
1099                 let lnum = lnum + 1
1100         endwhile
1101         return a:failure
1102 endfunction
1103
1104
1105 " --- notmuch helper functions {{{1
1106
1107 function! s:NM_newBuffer(how, type, content)
1108         if strlen(a:how)
1109                 exec a:how
1110         else
1111                 enew
1112         endif
1113         setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1114         silent put=a:content
1115         keepjumps 0d
1116         setlocal nomodifiable
1117         execute printf('set filetype=notmuch-%s', a:type)
1118         execute printf('set syntax=notmuch-%s', a:type)
1119         let b:nm_type = a:type
1120 endfunction
1121
1122 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1123         let fdir = expand(a:fdir)
1124         if !isdirectory(fdir)
1125                 call mkdir(fdir, 'p')
1126         endif
1127         let file_name = <SID>NM_mktemp(fdir, a:fname)
1128         if writefile(a:lines, file_name)
1129                 throw 'Eeek! couldn''t write to temporary file ' . file_name
1130         endif
1131         exec printf('edit %s', file_name)
1132         setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1133         execute printf('set filetype=notmuch-%s', a:type)
1134         execute printf('set syntax=notmuch-%s', a:type)
1135         let b:nm_type = a:type
1136 endfunction
1137
1138 function! s:NM_assert_buffer_type(type)
1139         if !exists('b:nm_type') || b:nm_type != a:type
1140                 throw printf('Eeek! expected type %s, but got %s.', a:type,
1141                             \ exists(b:nm_type) ? b:nm_type : 'something else')
1142         endif
1143 endfunction
1144
1145 function! s:NM_mktemp(dir, name)
1146         let time_stamp = strftime('%Y%m%d-%H%M%S')
1147         let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1148         " TODO: check if it exists, try again
1149         return file_name
1150 endfunction
1151
1152 function! s:NM_shell_escape(word)
1153         " TODO: use shellescape()
1154         let word = substitute(a:word, '''', '\\''', 'g')
1155         return '''' . word . ''''
1156 endfunction
1157
1158 " this function was taken from git.vim, then fixed up
1159 " http://github.com/motemen/git-vim
1160 function! s:NM_shell_split(cmd)
1161         let l:split_cmd = []
1162         let cmd = a:cmd
1163         let iStart = 0
1164         while 1
1165                 let t = match(cmd, '\S', iStart)
1166                 if t < iStart
1167                         break
1168                 endif
1169                 let iStart = t
1170
1171                 let iSpace = match(cmd, '\v(\s|$)', iStart)
1172                 if iSpace < iStart
1173                         break
1174                 endif
1175
1176                 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1177                 if iQuote1 > iSpace || iQuote1 < iStart
1178                         let iEnd = iSpace - 1
1179                         let l:split_cmd += [ cmd[iStart : iEnd] ]
1180                 else
1181                         let q = cmd[iQuote1]
1182                         let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1183                         if iQuote2 < iQuote1
1184                                 throw 'No matching ' . q . ' quote'
1185                         endif
1186                         let iEnd = iQuote2
1187                         let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1188                 endif
1189
1190
1191                 let iStart = iEnd + 1
1192         endwhile
1193
1194         return l:split_cmd
1195 endfunction
1196
1197
1198 function! s:NM_run(args)
1199         let words = a:args
1200         call map(words, 's:NM_shell_escape(v:val)')
1201         let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1202
1203         let start = reltime()
1204         let out = system(cmd)
1205         let err = v:shell_error
1206         let delta = reltime(start)
1207
1208         if exists('g:notmuch_debug') && g:notmuch_debug
1209                 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1210         endif
1211
1212         if err
1213                 echohl Error
1214                 echo substitute(out, '\n*$', '', '')
1215                 echohl None
1216                 return ''
1217         else
1218                 return out
1219         endif
1220 endfunction
1221
1222 " --- external mail handling helpers {{{1
1223
1224 function! s:NM_new_mail()
1225         echo 'not implemented'
1226 endfunction
1227
1228 " --- other helpers {{{1
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 :