]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
341f3370dad8d821062a0bb3aa87c50b17cbaf50
[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_header_help':           1                            ,
57         \ 'g:notmuch_compose_temp_file_dir':         '~/.notmuch/compose/'        ,
58         \ }
59
60 " defaults for g:notmuch_initial_search_words
61 " override with: let g:notmuch_initial_search_words = [ ... ]
62 let s:notmuch_initial_search_words_defaults = [
63         \ 'tag:inbox and tag:unread',
64         \ ]
65
66 " defaults for g:notmuch_show_headers
67 " override with: let g:notmuch_show_headers = [ ... ]
68 let s:notmuch_show_headers_defaults = [
69         \ 'Subject',
70         \ 'To',
71         \ 'Cc',
72         \ 'Bcc',
73         \ 'Date',
74         \ ]
75
76 " defaults for g:notmuch_folders
77 " override with: let g:notmuch_folders = [ ... ]
78 let s:notmuch_folders_defaults = [
79         \ [ 'new',    'tag:inbox and tag:unread' ],
80         \ [ 'inbox',  'tag:inbox'                ],
81         \ [ 'unread', 'tag:unread'               ],
82         \ ]
83
84 " defaults for g:notmuch_signature
85 " override with: let g:notmuch_signature = [ ... ]
86 let s:notmuch_signature_defaults = [
87         \ '',
88         \ '-- ',
89         \ 'email sent from notmuch.vim plugin'
90         \ ]
91
92 " defaults for g:notmuch_compose_headers
93 " override with: let g:notmuch_compose_headers = [ ... ]
94 let s:notmuch_compose_headers_defaults = [
95         \ 'From',
96         \ 'To',
97         \ 'Cc',
98         \ 'Bcc',
99         \ 'Subject'
100         \ ]
101
102 " --- keyboard mapping definitions {{{1
103
104 " --- --- bindings for folders mode {{{2
105
106 let g:notmuch_folders_maps = {
107         \ 's':          ':call <SID>NM_search_prompt()<CR>',
108         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
109         \ '=':          ':call <SID>NM_folders_refresh_view()<CR>',
110         \ '<Enter>':    ':call <SID>NM_folders_show_search()<CR>',
111         \ }
112
113 " --- --- bindings for search screen {{{2
114 let g:notmuch_search_maps = {
115         \ '<Enter>':    ':call <SID>NM_search_show_thread()<CR>',
116         \ '<C-]>':      ':call <SID>NM_search_expand(''<cword>'')<CR>',
117         \ 'a':          ':call <SID>NM_search_archive_thread()<CR>',
118         \ 'f':          ':call <SID>NM_search_filter()<CR>',
119         \ 'm':          ':call <SID>NM_new_mail()<CR>',
120         \ 'o':          ':call <SID>NM_search_toggle_order()<CR>',
121         \ 'r':          ':call <SID>NM_search_reply_to_thread()<CR>',
122         \ 's':          ':call <SID>NM_search_prompt()<CR>',
123         \ ',s':         ':call <SID>NM_search_edit()<CR>',
124         \ 't':          ':call <SID>NM_search_filter_by_tag()<CR>',
125         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
126         \ '+':          ':call <SID>NM_search_add_tags([])<CR>',
127         \ '-':          ':call <SID>NM_search_remove_tags([])<CR>',
128         \ '=':          ':call <SID>NM_search_refresh_view()<CR>',
129         \ '?':          ':echo <SID>NM_search_thread_id()<CR>',
130         \ }
131
132 " --- --- bindings for show screen {{{2
133 let g:notmuch_show_maps = {
134         \ '<C-P>':      ':call <SID>NM_show_previous(1, 0)<CR>',
135         \ '<C-N>':      ':call <SID>NM_show_next(1, 0)<CR>',
136         \ '<C-]>':      ':call <SID>NM_search_expand(''<cword>'')<CR>',
137         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
138         \
139         \ 'b':          ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
140         \ 'c':          ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
141         \ 'h':          ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
142         \ 's':          ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
143         \
144         \ 'a':          ':call <SID>NM_show_archive_thread()<CR>',
145         \ 'A':          ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
146         \ 'N':          ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
147         \ 'v':          ':call <SID>NM_show_view_all_mime_parts()<CR>',
148         \ '+':          ':call <SID>NM_show_add_tag()<CR>',
149         \ '-':          ':call <SID>NM_show_remove_tag()<CR>',
150         \ '<Space>':    ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
151         \ '\|':         ':call <SID>NM_show_pipe_message()<CR>',
152         \
153         \ '<S-Tab>':    ':call <SID>NM_show_previous_fold()<CR>',
154         \ '<Tab>':      ':call <SID>NM_show_next_fold()<CR>',
155         \ '<Enter>':    ':call <SID>NM_show_toggle_fold()<CR>',
156         \
157         \ 'r':          ':call <SID>NM_show_reply()<CR>',
158         \ 'm':          ':call <SID>NM_new_mail()<CR>',
159         \ '?':          ':echo <SID>NM_show_message_id() . ''  @ '' . join(<SID>NM_show_search_words())<CR>',
160         \ }
161
162 " --- --- bindings for compose screen {{{2
163 let g:notmuch_compose_nmaps = {
164         \ ',s':         ':call <SID>NM_compose_send()<CR>',
165         \ ',a':         ':call <SID>NM_compose_attach()<CR>',
166         \ ',q':         ':call <SID>NM_kill_this_buffer()<CR>',
167         \ '<Tab>':      ':call <SID>NM_compose_next_entry_area()<CR>',
168         \ }
169 let g:notmuch_compose_imaps = {
170         \ '<Tab>':      '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
171         \ }
172
173 " --- implement folders screen {{{1
174
175 function! s:NM_cmd_folders(words)
176         if len(a:words)
177                 echoe 'Not exapecting any arguments for folders command.'
178         endif
179         let cmd = ['count']
180         let disp = []
181         let searches = []
182         for entry in g:notmuch_folders
183                 let [ name, search ] = entry
184                 let data = s:NM_run(cmd + [search])
185                 let cnt = matchlist(data, '\(\d\+\)')[1]
186                 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
187                 call add(searches, search)
188         endfor
189
190         call <SID>NM_newBuffer('folders', join(disp, "\n"))
191         let b:nm_searches = searches
192         let b:nm_timestamp = reltime()
193
194         call <SID>NM_cmd_folders_mksyntax()
195         call <SID>NM_set_map('n', g:notmuch_folders_maps)
196         setlocal cursorline
197         setlocal nowrap
198 endfunction
199
200 function! s:NM_cmd_folders_mksyntax()
201 endfunction
202
203 " --- --- folders screen action functions {{{2
204
205 function! s:NM_folders_refresh_view()
206         let lno = line('.')
207         setlocal bufhidden=delete
208         call s:NM_cmd_folders([])
209         exec printf('norm %dG', lno)
210 endfunction
211
212 function! s:NM_folders_show_search()
213         let line = line('.')
214         let search = b:nm_searches[line-1]
215
216         let prev_bufnr = bufnr('%')
217         setlocal bufhidden=hide
218         call <SID>NM_cmd_search([search])
219         setlocal bufhidden=delete
220         let b:nm_prev_bufnr = prev_bufnr
221 endfunction
222
223
224 " --- implement search screen {{{1
225
226 function! s:NM_cmd_search(words)
227         let cmd = ['search']
228         if g:notmuch_search_newest_first
229                 let cmd = cmd + ['--sort=newest-first']
230         else
231                 let cmd = cmd + ['--sort=oldest-first']
232         endif
233         let data = s:NM_run(cmd + a:words)
234         let lines = split(data, "\n")
235         let disp = copy(lines)
236         call map(disp, 's:NM_cmd_search_fmtline(v:val)')
237
238         call <SID>NM_newBuffer('search', join(disp, "\n"))
239         let b:nm_raw_lines = lines
240         let b:nm_search_words = a:words
241
242         call <SID>NM_cmd_search_mksyntax()
243         call <SID>NM_set_map('n', g:notmuch_search_maps)
244         setlocal cursorline
245         setlocal nowrap
246 endfunction
247 function! s:NM_cmd_search_fmtline(line)
248         let m = matchlist(a:line, '^\(thread:\S\+\)\s\([^]]\+\]\) \([^;]\+\); \(.*\) (\([^(]*\))$')
249         if !len(m)
250                 return 'ERROR PARSING: ' . a:line
251         endif
252         let max = g:notmuch_search_from_column_width
253         let from = m[3]
254         if strlen(from) >= max
255                 let from = substitute(m[3][0:max-4], '[^A-Za-z1-9_]*$', '', '') . '...'
256         endif
257         return printf('%-20s %-20s | %s (%s)', m[2], from, m[4], m[5])
258 endfunction
259 function! s:NM_cmd_search_mksyntax()
260         syntax clear nmSearchFrom
261         exec printf('syntax match nmSearchFrom /\(\] \)\@<=.\{%d\}/ oneline contained', g:notmuch_search_from_column_width)
262 endfunction
263
264 " --- --- search screen action functions {{{2
265
266 function! s:NM_search_show_thread()
267         let id = <SID>NM_search_thread_id()
268         if id != ''
269                 let words = [id]
270                 if exists('b:nm_search_words')
271                         let words = ['('] + b:nm_search_words + [')', 'and', id]
272                 endif
273                 if len(words)
274                         call <SID>NM_cmd_show(words)
275                 endif
276         endif
277 endfunction
278
279 function! s:NM_search_prompt()
280         " TODO: input() can support completion
281         let text = input('NotMuch Search: ')
282         if strlen(text)
283                 let tags = split(text)
284         else
285                 let tags = s:notmuch_initial_search_words_defaults
286         endif
287         let prev_bufnr = bufnr('%')
288         if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
289                 " TODO: we intend to replace the current buffer,
290                 "       ... maybe we could just clear it
291                 let prev_bufnr = b:nm_prev_bufnr
292                 setlocal bufhidden=delete
293         else
294                 setlocal bufhidden=hide
295         endif
296         call <SID>NM_cmd_search(tags)
297         setlocal bufhidden=delete
298         let b:nm_prev_bufnr = prev_bufnr
299 endfunction
300
301 function! s:NM_search_edit()
302         " TODO: input() can support completion
303         let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
304         if strlen(text)
305                 call <SID>NM_cmd_search(split(text))
306         endif
307 endfunction
308
309 function! s:NM_search_archive_thread()
310         call <SID>NM_add_remove_tags_on_screen('', '-', ['inbox'])
311         call <SID>NM_add_remove_tags([], '-', ['inbox'])
312         norm j
313 endfunction
314
315 function! s:NM_search_filter()
316         call <SID>NM_search_filter_helper('Filter: ', '', '')
317 endfunction
318
319 function! s:NM_search_filter_by_tag()
320         call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
321 endfunction
322
323 function! s:NM_search_filter_helper(prompt, prefix, joiner)
324         " TODO: input() can support completion
325         let text = input(a:prompt)
326         if !strlen(text)
327                 return
328         endif
329
330         let tags = split(text)
331         if strlen(a:prefix)
332                 call map(tags, 'a:prefix . v:val')
333         endif
334         if strlen(a:joiner)
335                 let idx = len(tags) - 1
336                 while idx > 0
337                         call insert(tags, a:joiner, idx)
338                         let idx = idx - 1
339                 endwhile
340         endif
341         let tags = b:nm_search_words + ['and', '('] + tags + [')']
342
343         let prev_bufnr = bufnr('%')
344         setlocal bufhidden=hide
345         call <SID>NM_cmd_search(tags)
346         setlocal bufhidden=delete
347         let b:nm_prev_bufnr = prev_bufnr
348 endfunction
349
350 function! s:NM_search_toggle_order()
351         let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
352         " FIXME: maybe this would be better done w/o reading re-reading the lines
353         "         reversing the b:nm_raw_lines and the buffer lines would be better
354         call <SID>NM_search_refresh_view()
355 endfunction
356
357 function! s:NM_search_reply_to_thread()
358         echo 'not implemented'
359 endfunction
360
361 function! s:NM_search_add_tags(tags)
362         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
363 endfunction
364
365 function! s:NM_search_remove_tags(tags)
366         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
367 endfunction
368
369 function! s:NM_search_refresh_view()
370         let lno = line('.')
371         let prev_bufnr = b:nm_prev_bufnr
372         setlocal bufhidden=delete
373         call <SID>NM_cmd_search(b:nm_search_words)
374         let b:nm_prev_bufnr = prev_bufnr
375         " FIXME: should find the line of the thread we were on if possible
376         exec printf('norm %dG', lno)
377 endfunction
378
379 " --- --- search screen helper functions {{{2
380
381 function! s:NM_search_thread_id()
382         if !exists('b:nm_raw_lines')
383                 echoe 'no b:nm_raw_lines'
384                 return ''
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                 echoe 'no b:nm_raw_info'
624                 return ''
625         endif
626         let msg = <SID>NM_show_get_message_for_line(line('.'))
627         if has_key(msg,'id')
628                 return msg['id']
629         endif
630         return ''
631 endfunction
632
633 function! s:NM_show_search_words()
634         if !exists('b:nm_words')
635                 echoe 'no b:nm_words'
636                 return []
637         endif
638         return b:nm_words
639 endfunction
640
641 function! s:NM_show_fold_toggle(key, type, fold)
642         let info = b:nm_raw_info
643         let act = 'open'
644         if a:fold
645                 let act = 'close'
646         endif
647         for fld in info['folds']
648                 if fld[0] == a:type
649                         exec printf('%dfold%s', fld[1], act)
650                 endif
651         endfor
652         exec printf('nnoremap <buffer> %s :call <SID>NM_show_fold_toggle(''%s'', ''%s'', %d)<CR>', a:key, a:key, a:type, !a:fold)
653 endfunction
654
655
656 " s:NM_cmd_show_parse returns the following dictionary:
657 "    'disp':     lines to display
658 "    'msgs':     message info dicts { start, end, id, depth, filename, descr, header }
659 "    'folds':    fold info arrays [ type, start, end ]
660 "    'foldtext': fold text indexed by start line
661 function! s:NM_cmd_show_parse(inlines)
662         let info = { 'disp': [],       
663                    \ 'msgs': [],       
664                    \ 'folds': [],      
665                    \ 'foldtext': {} }  
666         let msg = {}
667         let hdr = {}
668
669         let in_message = 0
670         let in_header = 0
671         let in_body = 0
672         let in_part = ''
673
674         let body_start = -1
675         let part_start = -1
676
677         let mode_type = ''
678         let mode_start = -1
679
680         let inlnum = 0
681         for line in a:inlines
682                 let inlnum = inlnum + 1
683                 let foldinfo = []
684
685                 if strlen(in_part)
686                         let part_end = 0
687
688                         if match(line, g:notmuch_show_part_end_regexp) != -1
689                                 let part_end = len(info['disp'])
690                         else
691                                 call add(info['disp'], line)
692                         endif
693
694                         if in_part == 'text/plain'
695                                 if !part_end && mode_type == ''
696                                         if match(line, g:notmuch_show_signature_regexp) != -1
697                                                 let mode_type = 'sig'
698                                                 let mode_start = len(info['disp'])
699                                         elseif match(line, g:notmuch_show_citation_regexp) != -1
700                                                 let mode_type = 'cit'
701                                                 let mode_start = len(info['disp'])
702                                         endif
703                                 elseif mode_type == 'cit'
704                                         if part_end || match(line, g:notmuch_show_citation_regexp) == -1
705                                                 let outlnum = len(info['disp'])
706                                                 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
707                                                                \ printf('[ %d-line citation.  Press "c" to show. ]', outlnum - mode_start) ]
708                                                 let mode_type = ''
709                                         endif
710                                 elseif mode_type == 'sig'
711                                         let outlnum = len(info['disp'])
712                                         if (outlnum - mode_start) > g:notmuch_show_signature_lines_max
713                                                 let mode_type = ''
714                                         elseif part_end
715                                                 let foldinfo = [ mode_type, mode_start, outlnum-1, len(info['msgs']),
716                                                                \ printf('[ %d-line signature.  Press "s" to show. ]', outlnum - mode_start) ]
717                                                 let mode_type = ''
718                                         endif
719                                 endif
720                         endif
721
722                         if part_end
723                                 " FIXME: this is a hack for handling two folds being added for one line
724                                 "         we should handle addinga fold in a function
725                                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
726                                         call add(info['folds'], foldinfo[0:3])
727                                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
728                                 endif
729
730                                 let foldinfo = [ 'text', part_start, part_end, len(info['msgs']),
731                                                \ printf('[ %d-line %s.  Press "p" to show. ]', part_end - part_start, in_part) ]
732                                 let in_part = ''
733                                 call add(info['disp'], '')
734                         endif
735
736                 elseif in_body
737                         if !has_key(msg,'body_start')
738                                 let msg['body_start'] = len(info['disp']) + 1
739                         endif
740                         if match(line, g:notmuch_show_body_end_regexp) != -1
741                                 let body_end = len(info['disp'])
742                                 let foldinfo = [ 'bdy', body_start, body_end, len(info['msgs']),
743                                                \ printf('[ BODY %d - %d lines ]', len(info['msgs']), body_end - body_start) ]
744
745                                 let in_body = 0
746
747                         elseif match(line, g:notmuch_show_part_begin_regexp) != -1
748                                 let m = matchlist(line, 'ID: \(\d\+\), Content-type: \(\S\+\)')
749                                 let in_part = 'unknown'
750                                 if len(m)
751                                         let in_part = m[2]
752                                 endif
753                                 call add(info['disp'],
754                                          \ printf('--- %s ---', in_part))
755                                 let part_start = len(info['disp']) + 1
756                         endif
757
758                 elseif in_header
759                         if in_header == 1
760                                 let msg['descr'] = line
761                                 call add(info['disp'], line)
762                                 let in_header = 2
763                                 let msg['hdr_start'] = len(info['disp']) + 1
764
765                         else
766                                 if match(line, g:notmuch_show_header_end_regexp) != -1
767                                         let hdr_start = msg['hdr_start']+1
768                                         let hdr_end = len(info['disp'])
769                                         let foldinfo = [ 'hdr', hdr_start, hdr_end, len(info['msgs']),
770                                                \ printf('[ %d-line headers.  Press "h" to show. ]', hdr_end + 1 - hdr_start) ]
771                                         let msg['header'] = hdr
772                                         let in_header = 0
773                                         let hdr = {}
774                                 else
775                                         let m = matchlist(line, '^\(\w\+\):\s*\(.*\)$')
776                                         if len(m)
777                                                 let hdr[m[1]] = m[2]
778                                                 if match(g:notmuch_show_headers, m[1]) != -1
779                                                         call add(info['disp'], line)
780                                                 endif
781                                         endif
782                                 endif
783                         endif
784
785                 elseif in_message
786                         if match(line, g:notmuch_show_message_end_regexp) != -1
787                                 let msg['end'] = len(info['disp'])
788                                 call add(info['disp'], '')
789
790                                 let foldinfo = [ 'msg', msg['start'], msg['end'], len(info['msgs']),
791                                                \ printf('[ MSG %d - %s ]', len(info['msgs']), msg['descr']) ]
792
793                                 call add(info['msgs'], msg)
794                                 let msg = {}
795                                 let in_message = 0
796                                 let in_header = 0
797                                 let in_body = 0
798                                 let in_part = ''
799
800                         elseif match(line, g:notmuch_show_header_begin_regexp) != -1
801                                 let in_header = 1
802                                 continue
803
804                         elseif match(line, g:notmuch_show_body_begin_regexp) != -1
805                                 let body_start = len(info['disp']) + 1
806                                 let in_body = 1
807                                 continue
808                         endif
809
810                 else
811                         if match(line, g:notmuch_show_message_begin_regexp) != -1
812                                 let msg['start'] = len(info['disp']) + 1
813
814                                 let m = matchlist(line, g:notmuch_show_message_parse_regexp)
815                                 if len(m)
816                                         let msg['id'] = m[1]
817                                         let msg['depth'] = m[2]
818                                         let msg['match'] = m[3]
819                                         let msg['filename'] = m[4]
820                                 endif
821
822                                 let in_message = 1
823                         endif
824                 endif
825
826                 if len(foldinfo) && foldinfo[1] < foldinfo[2]
827                         call add(info['folds'], foldinfo[0:3])
828                         let info['foldtext'][foldinfo[1]] = foldinfo[4]
829                 endif
830         endfor
831         return info
832 endfunction
833
834 function! s:NM_cmd_show_mkfolds()
835         let info = b:nm_raw_info
836
837         for afold in info['folds']
838                 exec printf('%d,%dfold', afold[1], afold[2])
839                 let state = 'open'
840                 if (afold[0] == 'sig' && g:notmuch_show_fold_signatures)
841                  \ || (afold[0] == 'cit' && g:notmuch_show_fold_citations)
842                  \ || (afold[0] == 'bdy' && g:notmuch_show_fold_bodies)
843                  \ || (afold[0] == 'hdr' && g:notmuch_show_fold_headers)
844                         let state = 'close'
845                 elseif afold[0] == 'msg'
846                         let idx = afold[3]
847                         let msg = info['msgs'][idx]
848                         if has_key(msg,'match') && msg['match'] == '0'
849                                 let state = 'close'
850                         endif
851                 endif
852                 exec printf('%dfold%s', afold[1], state)
853         endfor
854 endfunction
855
856 function! s:NM_cmd_show_mksyntax()
857         let info = b:nm_raw_info
858         let cnt = 0
859         for msg in info['msgs']
860                 let cnt = cnt + 1
861                 let start = msg['start']
862                 let hdr_start = msg['hdr_start']
863                 let body_start = msg['body_start']
864                 let end = msg['end']
865                 exec printf('syntax region nmShowMsg%dDesc start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgDesc', cnt, start, start+1)
866                 exec printf('syntax region nmShowMsg%dHead start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgHead', cnt, hdr_start, body_start)
867                 exec printf('syntax region nmShowMsg%dBody start=''\%%%dl'' end=''\%%%dl'' contains=@nmShowMsgBody', cnt, body_start, end)
868         endfor
869 endfunction
870
871 function! NM_cmd_show_foldtext()
872         let foldtext = b:nm_raw_info['foldtext']
873         return foldtext[v:foldstart]
874 endfunction
875
876
877 " --- implement compose screen {{{1
878
879 function! s:NM_cmd_compose(words, body_lines)
880         let lines = !g:notmuch_compose_header_help ? [] : [
881                   \ 'Notmuch-Help: Type in your message here; to help you use these bindings:',
882                   \ 'Notmuch-Help:   ,a    - attach a file',
883                   \ 'Notmuch-Help:   ,s    - send the message (Notmuch-Help lines will be removed)',
884                   \ 'Notmuch-Help:   ,q    - abort the message',
885                   \ 'Notmuch-Help:   <Tab> - skip through header lines',
886                   \ ]
887         let start_on_line = 0
888
889         let hdrs = { }
890         for word in a:words
891                 let m = matchlist(word, '^\([^:]\+\):\s*\(.*\)\s*$')
892                 if !len(m)
893                         throw 'Eeek! bad parameter ''' . string(word) . ''''
894                 endif
895                 let key = substitute(m[1], '\<\w', '\U&', 'g')
896                 if !has_key(hdrs, key)
897                         let hdrs[key] = []
898                 endif
899                 if strlen(m[2])
900                         call add(hdrs[key], m[2])
901                 endif
902         endfor
903
904         if !has_key(hdrs, 'From') || !len(hdrs['From'])
905                 let me = <SID>NM_compose_get_user_email()
906                 let hdrs['From'] = [ me ]
907         endif
908
909         for key in g:notmuch_compose_headers
910                 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
911                 call add(lines, key . ': ' . text)
912                 if !start_on_line && !strlen(text)
913                         let start_on_line = len(lines)
914                 endif
915         endfor
916
917         for [key,val] in items(hdrs)
918                 if match(g:notmuch_compose_headers, key) == -1
919                         let line = key . ': ' . join(val, ', ')
920                         call add(lines, line)
921                 endif
922         endfor
923
924         call extend(lines, [ '', '' ])
925         if !start_on_line
926                 let start_on_line = len(lines) + 1
927         endif
928
929         if len(a:body_lines)
930                 call extend(lines, a:body_lines)
931         else
932                 call add(lines, '')
933         endif
934         call extend(lines, g:notmuch_signature)
935
936         let prev_bufnr = bufnr('%')
937         setlocal bufhidden=hide
938         call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
939                                   \ 'compose', lines)
940         setlocal bufhidden=hide
941
942         call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
943         call <SID>NM_set_map('i', g:notmuch_compose_imaps)
944
945         call cursor(start_on_line, strlen(start_on_line) + 1)
946         startinsert!
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         echo 'not implemented'
952 endfunction
953
954 function! s:NM_compose_attach()
955         echo 'not implemented'
956 endfunction
957
958 function! s:NM_compose_next_entry_area()
959         let lnum = line('.')
960         let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
961         echo 'header end = ' . string(hdr_end)
962         if lnum < hdr_end
963                 let lnum = lnum + 1
964                 let line = getline(lnum)
965                 if match(line, '^\([^:]\+\):\s*$') == -1
966                         call cursor(lnum, strlen(line) + 1)
967                         return ''
968                 endif
969                 while match(getline(lnum+1), '^\s') != -1
970                         let lnum = lnum + 1
971                 endwhile
972                 call cursor(lnum, strlen(getline(lnum)) + 1)
973                 return ''
974
975         elseif lnum == hdr_end
976                 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
977                 return ''
978         endif
979         echo 'mode=' . mode()
980         if mode() == 'i'
981                 if !getbufvar(bufnr('.'), '&et')
982                         return "\t"
983                 endif
984                 let space = ''
985                 let shiftwidth = a:shiftwidth
986                 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
987                 " we assume no one has shiftwidth set to more than 40 :)
988                 return '                                        '[0:shiftwidth]
989         endif
990 endfunction
991
992 " --- --- compose screen helper functions {{{2
993
994 function! s:NM_compose_get_user_email()
995         let name = substitute(system('id -u -n'), '\v(^\s*|\s*$|\n)', '', 'g')
996         let fqdn = substitute(system('hostname -f'), '\v(^\s*|\s*$|\n)', '', 'g')
997
998         " TODO: do this properly
999         return name . '@' . fqdn
1000 endfunction
1001
1002 function! s:NM_compose_find_line_match(start, pattern, failure)
1003         let lnum = a:start
1004         let lend = line('$')
1005         while lnum < lend
1006                 if match(getline(lnum), a:pattern) != -1
1007                         return lnum
1008                 endif
1009                 let lnum = lnum + 1
1010         endwhile
1011         return a:failure
1012 endfunction
1013
1014
1015 " --- notmuch helper functions {{{1
1016
1017 function! s:NM_newBuffer(type, content)
1018         enew
1019         setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1020         silent put=a:content
1021         keepjumps 0d
1022         setlocal nomodifiable
1023         execute printf('set filetype=notmuch-%s', a:type)
1024         execute printf('set syntax=notmuch-%s', a:type)
1025         let b:nm_type = a:type
1026 endfunction
1027
1028 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1029         let fdir = expand(a:fdir)
1030         if !isdirectory(fdir)
1031                 call mkdir(fdir, 'p')
1032         endif
1033         let file_name = <SID>NM_mktemp(fdir, a:fname)
1034         if writefile(a:lines, file_name)
1035                 throw 'Eeek! couldn''t write to temporary file ' . file_name
1036         endif
1037         exec printf('edit %s', file_name)
1038         setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1039         execute printf('set filetype=notmuch-%s', a:type)
1040         execute printf('set syntax=notmuch-%s', a:type)
1041         let b:nm_type = a:type
1042 endfunction
1043
1044 function! s:NM_mktemp(dir, name)
1045         let time_stamp = strftime('%Y%m%d-%H%M%S')
1046         let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1047         " TODO: check if it exists, try again
1048         return file_name
1049 endfunction
1050
1051 function! s:NM_shell_escape(word)
1052         " TODO: use shellescape()
1053         let word = substitute(a:word, '''', '\\''', 'g')
1054         return '''' . word . ''''
1055 endfunction
1056
1057 " this function was taken from git.vim, then fixed up
1058 " http://github.com/motemen/git-vim
1059 function! s:NM_shell_split(cmd)
1060         let l:split_cmd = []
1061         let cmd = a:cmd
1062         let iStart = 0
1063         while 1
1064                 let t = match(cmd, '\S', iStart)
1065                 if t < iStart
1066                         break
1067                 endif
1068                 let iStart = t
1069
1070                 let iSpace = match(cmd, '\v(\s|$)', iStart)
1071                 if iSpace < iStart
1072                         break
1073                 endif
1074
1075                 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1076                 if iQuote1 > iSpace || iQuote1 < iStart
1077                         let iEnd = iSpace - 1
1078                         let l:split_cmd += [ cmd[iStart : iEnd] ]
1079                 else
1080                         let q = cmd[iQuote1]
1081                         let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1082                         if iQuote2 < iQuote1
1083                                 throw 'No matching ' . q . ' quote'
1084                         endif
1085                         let iEnd = iQuote2
1086                         let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1087                 endif
1088
1089
1090                 let iStart = iEnd + 1
1091         endwhile
1092
1093         return l:split_cmd
1094 endfunction
1095
1096
1097 function! s:NM_run(args)
1098         let words = a:args
1099         call map(words, 's:NM_shell_escape(v:val)')
1100         let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1101
1102         let start = reltime()
1103         let out = system(cmd)
1104         let err = v:shell_error
1105         let delta = reltime(start)
1106
1107         if exists('g:notmuch_debug') && g:notmuch_debug
1108                 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1109         endif
1110
1111         if err
1112                 echohl Error
1113                 echo substitute(out, '\n*$', '', '')
1114                 echohl None
1115                 return ''
1116         else
1117                 return out
1118         endif
1119 endfunction
1120
1121 " --- external mail handling helpers {{{1
1122
1123 function! s:NM_new_mail()
1124         echo 'not implemented'
1125 endfunction
1126
1127 " --- other helpers {{{1
1128
1129 function! s:NM_kill_this_buffer()
1130         if exists('b:nm_prev_bufnr')
1131                 setlocal bufhidden=delete
1132                 exec printf(":buffer %d", b:nm_prev_bufnr)
1133         else
1134                 echo "This is the last buffer; use :q<CR> to quit."
1135         endif
1136 endfunction
1137
1138 function! s:NM_search_expand(arg)
1139         let word = expand(a:arg)
1140         let prev_bufnr = bufnr('%')
1141         setlocal bufhidden=hide
1142         call <SID>NM_cmd_search([word])
1143         setlocal bufhidden=delete
1144         let b:nm_prev_bufnr = prev_bufnr
1145 endfunction
1146
1147 function! s:NM_add_remove_tags(filter, prefix, tags)
1148         let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1149         if !len(filter)
1150                 echoe 'Eeek! I couldn''t find the thead id!'
1151         endif
1152         call map(a:tags, 'a:prefix . v:val')
1153         let args = ['tag']
1154         call extend(args, a:tags)
1155         call add(args, '--')
1156         call extend(args, filter)
1157         " TODO: handle errors
1158         call <SID>NM_run(args)
1159 endfunction
1160
1161 function! s:NM_add_remove_tags_on_screen(online, prefix, tags)
1162         setlocal modifiable
1163         if a:prefix == '-'
1164                 for tagname in a:tags
1165                         exec printf('silent! %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', string(a:online), tagname)
1166                 endfor
1167         else
1168                 for tagname in a:tags
1169                         exec printf('silent! %ss/(\([^)]*\)\([^)]*\))$/(\1 %s)/', string(a:online), tagname)
1170                 endfor
1171         endif
1172         setlocal nomodifiable
1173 endfunction
1174
1175 " --- process and set the defaults {{{1
1176
1177 function! NM_set_defaults(force)
1178         for [key, dflt] in items(s:notmuch_defaults)
1179                 let cmd = ''
1180                 if !a:force && exists(key) && type(dflt) == type(eval(key))
1181                         continue
1182                 elseif type(dflt) == type(0)
1183                         let cmd = printf('let %s = %d', key, dflt)
1184                 elseif type(dflt) == type('')
1185                         let cmd = printf('let %s = ''%s''', key, dflt)
1186                 " FIXME: not sure why this didn't work when dflt is an array
1187                 "elseif type(dflt) == type([])
1188                 "        let cmd = printf('let %s = %s', key, string(dflt))
1189                 else
1190                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1191                                                 \ a:force, key, string(dflt))
1192                         continue
1193                 endif
1194                 exec cmd
1195         endfor
1196 endfunction
1197 call NM_set_defaults(0)
1198
1199 " for some reason NM_set_defaults() didn't work for arrays...
1200 if !exists('g:notmuch_show_headers')
1201         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1202 endif
1203 if !exists('g:notmuch_initial_search_words')
1204         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1205 endif
1206 if !exists('g:notmuch_folders')
1207         let g:notmuch_folders = s:notmuch_folders_defaults
1208 endif
1209
1210 if !exists('g:notmuch_signature')
1211         let g:notmuch_signature = s:notmuch_signature_defaults
1212 endif
1213 if !exists('g:notmuch_compose_headers')
1214         let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1215 endif
1216
1217 " --- assign keymaps {{{1
1218
1219 function! s:NM_set_map(type, maps)
1220         nmapclear
1221         for [key, code] in items(a:maps)
1222                 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1223         endfor
1224         " --- this is a hack for development :)
1225         nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
1226 endfunction
1227
1228 " --- command handler {{{1
1229
1230 function! NotMuch(args)
1231         let args = a:args
1232         if !strlen(args)
1233                 let args = 'folders'
1234         endif
1235
1236         let words = <SID>NM_shell_split(args)
1237         if words[0] == 'folders' || words[0] == 'f'
1238                 let words = words[1:]
1239                 call <SID>NM_cmd_folders(words)
1240
1241         elseif words[0] == 'search' || words[0] == 's'
1242                 if len(words) > 1
1243                         let words = words[1:]
1244                 elseif exists('b:nm_search_words')
1245                         let words = b:nm_search_words
1246                 else
1247                         let words = g:notmuch_initial_search_words
1248                 endif
1249                 call <SID>NM_cmd_search(words)
1250
1251         elseif words[0] == 'show'
1252                 echoe 'show is not yet implemented.'
1253
1254         elseif words[0] == 'new' || words[0] == 'compose'
1255                 let words = words[1:]
1256                 call <SID>NM_cmd_compose(words, [])
1257         endif
1258 endfunction
1259 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1260         return []
1261 endfunction
1262
1263
1264 " --- glue {{{1
1265
1266 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1267 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1268
1269 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :