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