]> git.notmuchmail.org Git - notmuch/blob - vim/plugin/notmuch.vim
vim: syntax highlighting for notmuch-compose mode
[notmuch] / vim / plugin / notmuch.vim
1 " notmuch.vim plugin --- run notmuch within vim
2 "
3 " Copyright © Carl Worth
4 "
5 " This file is part of Notmuch.
6 "
7 " Notmuch is free software: you can redistribute it and/or modify it
8 " under the terms of the GNU General Public License as published by
9 " the Free Software Foundation, either version 3 of the License, or
10 " (at your option) any later version.
11 "
12 " Notmuch is distributed in the hope that it will be useful, but
13 " WITHOUT ANY WARRANTY; without even the implied warranty of
14 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 " General Public License for more details.
16 "
17 " You should have received a copy of the GNU General Public License
18 " along with Notmuch.  If not, see <http://www.gnu.org/licenses/>.
19 "
20 " Authors: Bart Trojanowski <bart@jukie.net>
21
22 " --- configuration defaults {{{1
23
24 let s:notmuch_defaults = {
25         \ 'g:notmuch_cmd':                           'notmuch'                    ,
26         \ 'g:notmuch_debug':                         0                            ,
27         \
28         \ 'g:notmuch_search_newest_first':           1                            ,
29         \ 'g:notmuch_search_from_column_width':      20                           ,
30         \
31         \ 'g:notmuch_show_fold_signatures':          1                            ,
32         \ 'g:notmuch_show_fold_citations':           1                            ,
33         \ 'g:notmuch_show_fold_bodies':              0                            ,
34         \ 'g:notmuch_show_fold_headers':             1                            ,
35         \
36         \ 'g:notmuch_show_message_begin_regexp':     '^\fmessage{'                ,
37         \ 'g:notmuch_show_message_end_regexp':       '^\fmessage}'                ,
38         \ 'g:notmuch_show_header_begin_regexp':      '^\fheader{'                 ,
39         \ 'g:notmuch_show_header_end_regexp':        '^\fheader}'                 ,
40         \ 'g:notmuch_show_body_begin_regexp':        '^\fbody{'                   ,
41         \ 'g:notmuch_show_body_end_regexp':          '^\fbody}'                   ,
42         \ 'g:notmuch_show_attachment_begin_regexp':  '^\fattachment{'             ,
43         \ 'g:notmuch_show_attachment_end_regexp':    '^\fattachment}'             ,
44         \ 'g:notmuch_show_part_begin_regexp':        '^\fpart{'                   ,
45         \ 'g:notmuch_show_part_end_regexp':          '^\fpart}'                   ,
46         \ 'g:notmuch_show_marker_regexp':            '^\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$',
47         \
48         \ 'g:notmuch_show_message_parse_regexp':     '\(id:[^ ]*\) depth:\([0-9]*\) match:\([0-9]*\) filename:\(.*\)$',
49         \ 'g:notmuch_show_tags_regexp':              '(\([^)]*\))$'               ,
50         \
51         \ 'g:notmuch_show_signature_regexp':         '^\(-- \?\|_\+\)$'           ,
52         \ 'g:notmuch_show_signature_lines_max':      12                           ,
53         \
54         \ 'g:notmuch_show_citation_regexp':          '^\s*>'                      ,
55         \
56         \ 'g:notmuch_compose_temp_file_dir':         '~/.notmuch/compose/'        ,
57         \ }
58
59 " defaults for g:notmuch_initial_search_words
60 " override with: let g:notmuch_initial_search_words = [ ... ]
61 let s:notmuch_initial_search_words_defaults = [
62         \ 'tag:inbox and tag:unread',
63         \ ]
64
65 " defaults for g:notmuch_show_headers
66 " override with: let g:notmuch_show_headers = [ ... ]
67 let s:notmuch_show_headers_defaults = [
68         \ 'Subject',
69         \ 'To',
70         \ 'Cc',
71         \ 'Bcc',
72         \ 'Date',
73         \ ]
74
75 " defaults for g:notmuch_folders
76 " override with: let g:notmuch_folders = [ ... ]
77 let s:notmuch_folders_defaults = [
78         \ [ 'new',    'tag:inbox and tag:unread' ],
79         \ [ 'inbox',  'tag:inbox'                ],
80         \ [ 'unread', 'tag:unread'               ],
81         \ ]
82
83 " defaults for g:notmuch_signature
84 " override with: let g:notmuch_signature = [ ... ]
85 let s:notmuch_signature_defaults = [
86         \ '',
87         \ '-- ',
88         \ 'email sent from notmuch.vim plugin'
89         \ ]
90
91 " defaults for g:notmuch_compose_headers
92 " override with: let g:notmuch_compose_headers = [ ... ]
93 let s:notmuch_compose_headers_defaults = [
94         \ 'From',
95         \ 'To',
96         \ 'Cc',
97         \ 'Bcc',
98         \ 'Subject'
99         \ ]
100
101 " --- keyboard mapping definitions {{{1
102
103 " --- --- bindings for folders mode {{{2
104
105 let g:notmuch_folders_maps = {
106         \ 's':          ':call <SID>NM_search_prompt()<CR>',
107         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
108         \ '=':          ':call <SID>NM_folders_refresh_view()<CR>',
109         \ '<Enter>':    ':call <SID>NM_folders_show_search()<CR>',
110         \ }
111
112 " --- --- bindings for search screen {{{2
113 let g:notmuch_search_maps = {
114         \ '<Enter>':    ':call <SID>NM_search_show_thread()<CR>',
115         \ '<C-]>':      ':call <SID>NM_search_expand(''<cword>'')<CR>',
116         \ 'a':          ':call <SID>NM_search_archive_thread()<CR>',
117         \ 'f':          ':call <SID>NM_search_filter()<CR>',
118         \ 'm':          ':call <SID>NM_new_mail()<CR>',
119         \ 'o':          ':call <SID>NM_search_toggle_order()<CR>',
120         \ 'r':          ':call <SID>NM_search_reply_to_thread()<CR>',
121         \ 's':          ':call <SID>NM_search_prompt()<CR>',
122         \ ',s':         ':call <SID>NM_search_edit()<CR>',
123         \ 't':          ':call <SID>NM_search_filter_by_tag()<CR>',
124         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
125         \ '+':          ':call <SID>NM_search_add_tags([])<CR>',
126         \ '-':          ':call <SID>NM_search_remove_tags([])<CR>',
127         \ '=':          ':call <SID>NM_search_refresh_view()<CR>',
128         \ '?':          ':echo <SID>NM_search_thread_id()<CR>',
129         \ }
130
131 " --- --- bindings for show screen {{{2
132 let g:notmuch_show_maps = {
133         \ '<C-P>':      ':call <SID>NM_show_previous(1, 0)<CR>',
134         \ '<C-N>':      ':call <SID>NM_show_next(1, 0)<CR>',
135         \ '<C-]>':      ':call <SID>NM_search_expand(''<cword>'')<CR>',
136         \ 'q':          ':call <SID>NM_kill_this_buffer()<CR>',
137         \
138         \ 'b':          ':call <SID>NM_show_fold_toggle(''b'', ''bdy'', !g:notmuch_show_fold_bodies)<CR>',
139         \ 'c':          ':call <SID>NM_show_fold_toggle(''c'', ''cit'', !g:notmuch_show_fold_citations)<CR>',
140         \ 'h':          ':call <SID>NM_show_fold_toggle(''h'', ''hdr'', !g:notmuch_show_fold_headers)<CR>',
141         \ 's':          ':call <SID>NM_show_fold_toggle(''s'', ''sig'', !g:notmuch_show_fold_signatures)<CR>',
142         \
143         \ 'a':          ':call <SID>NM_show_archive_thread()<CR>',
144         \ 'A':          ':call <SID>NM_show_mark_read_then_archive_thread()<CR>',
145         \ 'N':          ':call <SID>NM_show_mark_read_then_next_open_message()<CR>',
146         \ 'v':          ':call <SID>NM_show_view_all_mime_parts()<CR>',
147         \ '+':          ':call <SID>NM_show_add_tag()<CR>',
148         \ '-':          ':call <SID>NM_show_remove_tag()<CR>',
149         \ '<Space>':    ':call <SID>NM_show_advance_marking_read_and_archiving()<CR>',
150         \ '\|':         ':call <SID>NM_show_pipe_message()<CR>',
151         \
152         \ '<S-Tab>':    ':call <SID>NM_show_previous_fold()<CR>',
153         \ '<Tab>':      ':call <SID>NM_show_next_fold()<CR>',
154         \ '<Enter>':    ':call <SID>NM_show_toggle_fold()<CR>',
155         \
156         \ 'r':          ':call <SID>NM_show_reply()<CR>',
157         \ 'm':          ':call <SID>NM_new_mail()<CR>',
158         \ '?':          ':echo <SID>NM_show_message_id() . ''  @ '' . join(<SID>NM_show_search_words())<CR>',
159         \ }
160
161 " --- --- bindings for compose screen {{{2
162 let g:notmuch_compose_nmaps = {
163         \ ',s':         ':call <SID>NM_compose_send()<CR>',
164         \ ',q':         ':call <SID>NM_kill_this_buffer()<CR>',
165         \ '<Tab>':      ':call <SID>NM_compose_next_entry_area()<CR>',
166         \ }
167 let g:notmuch_compose_imaps = {
168         \ '<Tab>':      '<C-r>=<SID>NM_compose_next_entry_area()<CR>',
169         \ }
170
171 " --- implement folders screen {{{1
172
173 function! s:NM_cmd_folders(words)
174         if len(a:words)
175                 echoe 'Not exapecting any arguments for folders command.'
176         endif
177         let cmd = ['count']
178         let disp = []
179         let searches = []
180         for entry in g:notmuch_folders
181                 let [ name, search ] = entry
182                 let data = s:NM_run(cmd + [search])
183                 let cnt = matchlist(data, '\(\d\+\)')[1]
184                 call add(disp, printf('%9d %-20s (%s)', cnt, name, search))
185                 call add(searches, search)
186         endfor
187
188         call <SID>NM_newBuffer('folders', join(disp, "\n"))
189         let b:nm_searches = searches
190         let b:nm_timestamp = reltime()
191
192         call <SID>NM_cmd_folders_mksyntax()
193         call <SID>NM_set_map('n', g:notmuch_folders_maps)
194         setlocal cursorline
195         setlocal nowrap
196 endfunction
197
198 function! s:NM_cmd_folders_mksyntax()
199 endfunction
200
201 " --- --- folders screen action functions {{{2
202
203 function! s:NM_folders_refresh_view()
204         let lno = line('.')
205         setlocal bufhidden=delete
206         call s:NM_cmd_folders([])
207         exec printf('norm %dG', lno)
208 endfunction
209
210 function! s:NM_folders_show_search()
211         let line = line('.')
212         let search = b:nm_searches[line-1]
213
214         let prev_bufnr = bufnr('%')
215         setlocal bufhidden=hide
216         call <SID>NM_cmd_search([search])
217         setlocal bufhidden=delete
218         let b:nm_prev_bufnr = prev_bufnr
219 endfunction
220
221
222 " --- implement search screen {{{1
223
224 function! s:NM_cmd_search(words)
225         let cmd = ['search']
226         if g:notmuch_search_newest_first
227                 let cmd = cmd + ['--sort=newest-first']
228         else
229                 let cmd = cmd + ['--sort=oldest-first']
230         endif
231         let data = s:NM_run(cmd + a:words)
232         let lines = split(data, "\n")
233         let disp = copy(lines)
234         call map(disp, 's:NM_cmd_search_fmtline(v:val)')
235
236         call <SID>NM_newBuffer('search', join(disp, "\n"))
237         let b:nm_raw_lines = lines
238         let b:nm_search_words = a:words
239
240         call <SID>NM_cmd_search_mksyntax()
241         call <SID>NM_set_map('n', g:notmuch_search_maps)
242         setlocal cursorline
243         setlocal nowrap
244 endfunction
245 function! s:NM_cmd_search_fmtline(line)
246         let m = matchlist(a:line, '^\(thread:\S\+\)\s\([^]]\+\]\) \([^;]\+\); \(.*\) (\([^(]*\))$')
247         if !len(m)
248                 return 'ERROR PARSING: ' . a:line
249         endif
250         let max = g:notmuch_search_from_column_width
251         let from = m[3]
252         if strlen(from) >= max
253                 let from = substitute(m[3][0:max-4], '[^A-Za-z1-9_]*$', '', '') . '...'
254         endif
255         return printf('%-20s %-20s | %s (%s)', m[2], from, m[4], m[5])
256 endfunction
257 function! s:NM_cmd_search_mksyntax()
258         syntax clear nmSearchFrom
259         exec printf('syntax match nmSearchFrom /\(\] \)\@<=.\{%d\}/ oneline contained', g:notmuch_search_from_column_width)
260 endfunction
261
262 " --- --- search screen action functions {{{2
263
264 function! s:NM_search_show_thread()
265         let id = <SID>NM_search_thread_id()
266         if id != ''
267                 let words = [id]
268                 if exists('b:nm_search_words')
269                         let words = ['('] + b:nm_search_words + [')', 'and', id]
270                 endif
271                 if len(words)
272                         call <SID>NM_cmd_show(words)
273                 endif
274         endif
275 endfunction
276
277 function! s:NM_search_prompt()
278         " TODO: input() can support completion
279         let text = input('NotMuch Search: ')
280         if strlen(text)
281                 let tags = split(text)
282         else
283                 let tags = s:notmuch_initial_search_words_defaults
284         endif
285         let prev_bufnr = bufnr('%')
286         if b:nm_type == 'search' && exists('b:nm_prev_bufnr')
287                 " TODO: we intend to replace the current buffer,
288                 "       ... maybe we could just clear it
289                 let prev_bufnr = b:nm_prev_bufnr
290                 setlocal bufhidden=delete
291         else
292                 setlocal bufhidden=hide
293         endif
294         call <SID>NM_cmd_search(tags)
295         setlocal bufhidden=delete
296         let b:nm_prev_bufnr = prev_bufnr
297 endfunction
298
299 function! s:NM_search_edit()
300         " TODO: input() can support completion
301         let text = input('NotMuch Search: ', join(b:nm_search_words, ' '))
302         if strlen(text)
303                 call <SID>NM_cmd_search(split(text))
304         endif
305 endfunction
306
307 function! s:NM_search_archive_thread()
308         call <SID>NM_add_remove_tags_on_screen('', '-', ['inbox'])
309         call <SID>NM_add_remove_tags([], '-', ['inbox'])
310         norm j
311 endfunction
312
313 function! s:NM_search_filter()
314         call <SID>NM_search_filter_helper('Filter: ', '', '')
315 endfunction
316
317 function! s:NM_search_filter_by_tag()
318         call <SID>NM_search_filter_helper('Filter Tag(s): ', 'tag:', 'and')
319 endfunction
320
321 function! s:NM_search_filter_helper(prompt, prefix, joiner)
322         " TODO: input() can support completion
323         let text = input(a:prompt)
324         if !strlen(text)
325                 return
326         endif
327
328         let tags = split(text)
329         if strlen(a:prefix)
330                 call map(tags, 'a:prefix . v:val')
331         endif
332         if strlen(a:joiner)
333                 let idx = len(tags) - 1
334                 while idx > 0
335                         call insert(tags, a:joiner, idx)
336                         let idx = idx - 1
337                 endwhile
338         endif
339         let tags = b:nm_search_words + ['and', '('] + tags + [')']
340
341         let prev_bufnr = bufnr('%')
342         setlocal bufhidden=hide
343         call <SID>NM_cmd_search(tags)
344         setlocal bufhidden=delete
345         let b:nm_prev_bufnr = prev_bufnr
346 endfunction
347
348 function! s:NM_search_toggle_order()
349         let g:notmuch_search_newest_first = !g:notmuch_search_newest_first
350         " FIXME: maybe this would be better done w/o reading re-reading the lines
351         "         reversing the b:nm_raw_lines and the buffer lines would be better
352         call <SID>NM_search_refresh_view()
353 endfunction
354
355 function! s:NM_search_reply_to_thread()
356         echo 'not implemented'
357 endfunction
358
359 function! s:NM_search_add_tags(tags)
360         call <SID>NM_search_add_remove_tags('Add Tag(s): ', '+', a:tags)
361 endfunction
362
363 function! s:NM_search_remove_tags(tags)
364         call <SID>NM_search_add_remove_tags('Remove Tag(s): ', '-', a:tags)
365 endfunction
366
367 function! s:NM_search_refresh_view()
368         let lno = line('.')
369         let prev_bufnr = b:nm_prev_bufnr
370         setlocal bufhidden=delete
371         call <SID>NM_cmd_search(b:nm_search_words)
372         let b:nm_prev_bufnr = prev_bufnr
373         " FIXME: should find the line of the thread we were on if possible
374         exec printf('norm %dG', lno)
375 endfunction
376
377 " --- --- search screen helper functions {{{2
378
379 function! s:NM_search_thread_id()
380         if !exists('b:nm_raw_lines')
381                 echoe 'no b:nm_raw_lines'
382                 return ''
383         endif
384         let mnum = line('.') - 1
385         if len(b:nm_raw_lines) <= mnum
386                 return ''
387         endif
388         echo 'len=' . string(len(b:nm_raw_lines)) . '  mnum=' . string(mnum)
389         let info = b:nm_raw_lines[mnum]
390         let what = split(info, '\s\+')[0]
391         return what
392 endfunction
393
394 function! s:NM_search_add_remove_tags(prompt, prefix, intags)
395         if type(a:intags) != type([]) || len(a:intags) == 0
396                 " TODO: input() can support completion
397                 let text = input(a:prompt)
398                 if !strlen(text)
399                         return
400                 endif
401                 let tags = split(text, ' ')
402         else
403                 let tags = a:intags
404         endif
405         call <SID>NM_add_remove_tags([], a:prefix, tags)
406         call <SID>NM_add_remove_tags_on_screen('', a:prefix, tags)
407 endfunction
408
409 " --- implement show screen {{{1
410
411 function! s:NM_cmd_show(words)
412         let prev_bufnr = bufnr('%')
413         let data = s:NM_run(['show'] + a:words)
414         let lines = split(data, "\n")
415
416         let info = s:NM_cmd_show_parse(lines)
417
418         setlocal bufhidden=hide
419         call <SID>NM_newBuffer('show', join(info['disp'], "\n"))
420         setlocal bufhidden=delete
421         let b:nm_words = a:words
422         let b:nm_raw_info = info
423         let b:nm_prev_bufnr = prev_bufnr
424
425         call <SID>NM_cmd_show_mkfolds()
426         call <SID>NM_cmd_show_mksyntax()
427         call <SID>NM_set_map('n', g:notmuch_show_maps)
428         setlocal foldtext=NM_cmd_show_foldtext()
429         setlocal fillchars=
430         setlocal foldcolumn=6
431
432 endfunction
433
434 function! s:NM_show_previous(can_change_thread, find_matching)
435         let info = b:nm_raw_info
436         let lnum = line('.')
437         for msg in reverse(copy(info['msgs']))
438                 if a:find_matching && msg['match'] == '0'
439                         continue
440                 endif
441                 if lnum <= msg['start']
442                         continue
443                 endif
444
445                 exec printf('norm %dGzt', msg['start'])
446                 " TODO: try to fit the message on screen
447                 return
448         endfor
449         if !a:can_change_thread
450                 return
451         endif
452         call <SID>NM_kill_this_buffer()
453         if line('.') > 1
454                 norm k
455                 call <SID>NM_search_show_thread()
456                 norm G
457                 call <SID>NM_show_previous(0, a:find_matching)
458         else
459                 echo 'No more messages.'
460         endif
461 endfunction
462
463 function! s:NM_show_next(can_change_thread, find_matching)
464         let info = b:nm_raw_info
465         let lnum = line('.')
466         for msg in info['msgs']
467                 if a:find_matching && msg['match'] == '0'
468                         continue
469                 endif
470                 if lnum >= msg['start']
471                         continue
472                 endif
473
474                 exec printf('norm %dGzt', msg['start'])
475                 " TODO: try to fit the message on screen
476                 return
477         endfor
478         if a:can_change_thread
479                 call <SID>NM_show_next_thread()
480         endif
481 endfunction
482
483 function! s:NM_show_next_thread()
484         call <SID>NM_kill_this_buffer()
485         if line('.') != line('$')
486                 norm j
487                 call <SID>NM_search_show_thread()
488         else
489                 echo 'No more messages.'
490         endif
491 endfunction
492
493 function! s:NM_show_archive_thread()
494         echo 'not implemented'
495 endfunction
496
497 function! s:NM_show_mark_read_then_archive_thread()
498         echo 'not implemented'
499 endfunction
500
501 function! s:NM_show_mark_read_then_next_open_message()
502         echo 'not implemented'
503 endfunction
504
505 function! s:NM_show_previous_message()
506         echo 'not implemented'
507 endfunction
508
509 function! s:NM_show_reply()
510         echo 'not implemented'
511 endfunction
512
513 function! s:NM_show_view_all_mime_parts()
514         echo 'not implemented'
515 endfunction
516
517 function! s:NM_show_view_raw_message()
518         echo 'not implemented'
519 endfunction
520
521 function! s:NM_show_add_tag()
522         echo 'not implemented'
523 endfunction
524
525 function! s:NM_show_remove_tag()
526         echo 'not implemented'
527 endfunction
528
529 " if entire message is not visible scroll down 1/2 page or less to get to the bottom of message
530 " otherwise go to next message
531 " any message that is viewed entirely has inbox and unread tags removed
532 function! s:NM_show_advance_marking_read_and_archiving()
533         let advance_tags = ['unread', 'inbox']
534
535         let vis_top = line('w0')
536         let vis_bot = line('w$')
537
538         let msg_top = <SID>NM_show_get_message_for_line(vis_top)
539         if !has_key(msg_top,'id')
540                 echo "No top visible message."
541         endif
542
543         " if the top message is the last message, just expunge the entire thread and move on
544         if msg_top['end'] == line('$')
545                 let ids = []
546                 for msg in b:nm_raw_info['msgs']
547                         if has_key(msg,'match') && msg['match'] != '0'
548                                 if len(ids)
549                                         call add(ids, 'OR')
550                                 endif
551                                 call add(ids, msg['id'])
552                         endif
553                 endfor
554
555                 let filter = ['('] + advance_tags + [')', 'AND', '('] + ids + [')']
556                 call <SID>NM_add_remove_tags(filter, '-', advance_tags)
557                 call <SID>NM_show_next(1, 1)
558                 return
559         endif
560
561         let msg_bot = <SID>NM_show_get_message_for_line(vis_bot)
562         if !has_key(msg_bot,'id')
563                 echo "No bottom visible message."
564         endif
565
566         " if entire message fits on the screen, read/archive it, move to the next one
567         if msg_top['id'] != msg_bot['id'] || msg_top['end'] <= vis_bot
568                 call <SID>NM_add_remove_tags_on_screen(msg_top['start'], '-', advance_tags)
569                 exec printf('norm %dG', vis_top)
570                 call <SID>NM_show_next(0, 1)
571                 if has_key(msg_top,'match') && msg_top['match'] != '0'
572                         redraw
573                         " do this last to hide the latency
574                         let filter = ['('] + advance_tags + [')', 'AND', msg_top['id']]
575                         call <SID>NM_add_remove_tags(filter, '-', advance_tags)
576                 endif
577                 return
578         endif
579
580         " entire message does not fit on the screen, scroll down to bottom, max 1/2 screen
581         let jmp = winheight(winnr()) / 2
582         let max = msg_bot['end'] - vis_bot
583         if jmp > max
584                 let jmp = max
585         endif
586         exec printf('norm %dGzt', vis_top + jmp)
587         return
588 endfunction
589
590 function! s:NM_show_pipe_message()
591         echo 'not implemented'
592 endfunction
593
594 function! s:NM_show_previous_fold()
595         echo 'not implemented'
596 endfunction
597
598 function! s:NM_show_next_fold()
599         echo 'not implemented'
600 endfunction
601
602 function! s:NM_show_toggle_fold()
603         echo 'not implemented'
604 endfunction
605
606
607 " --- --- show screen helper functions {{{2
608
609 function! s:NM_show_get_message_for_line(line)
610         for msg in b:nm_raw_info['msgs']
611                 if a:line > msg['end']
612                         continue
613                 endif
614                 return msg
615         endfor
616         return {}
617 endfunction
618
619 function! s:NM_show_message_id()
620         if !exists('b:nm_raw_info')
621                 echoe 'no b:nm_raw_info'
622                 return ''
623         endif
624         let msg = <SID>NM_show_get_message_for_line(line('.'))
625         if has_key(msg,'id')
626                 return msg['id']
627         endif
628         return ''
629 endfunction
630
631 function! s:NM_show_search_words()
632         if !exists('b:nm_words')
633                 echoe 'no b:nm_words'
634                 return []
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 = []
879         let start_on_line = 0
880
881         let hdrs = { }
882         for word in a:words
883                 let m = matchlist(word, '^\([^:]\+\):\s*\(.*\)\s*$')
884                 if !len(m)
885                         throw 'Eeek! bad parameter ''' . string(word) . ''''
886                 endif
887                 let key = substitute(m[1], '\<\w', '\U&', 'g')
888                 if !has_key(hdrs, key)
889                         let hdrs[key] = []
890                 endif
891                 if strlen(m[2])
892                         call add(hdrs[key], m[2])
893                 endif
894         endfor
895
896         if !has_key(hdrs, 'From') || !len(hdrs['From'])
897                 let me = <SID>NM_compose_get_user_email()
898                 let hdrs['From'] = [ me ]
899         endif
900
901         for key in g:notmuch_compose_headers
902                 let text = has_key(hdrs, key) ? join(hdrs[key], ', ') : ''
903                 call add(lines, key . ': ' . text)
904                 if !start_on_line && !strlen(text)
905                         let start_on_line = len(lines)
906                 endif
907         endfor
908
909         for [key,val] in items(hdrs)
910                 if match(g:notmuch_compose_headers, key) == -1
911                         let line = key . ': ' . join(val, ', ')
912                         call add(lines, line)
913                 endif
914         endfor
915
916         call extend(lines, [ '', '' ])
917         if !start_on_line
918                 let start_on_line = len(lines) + 1
919         endif
920
921         if len(a:body_lines)
922                 call extend(lines, a:body_lines)
923         else
924                 call add(lines, '')
925         endif
926         call extend(lines, g:notmuch_signature)
927
928         let prev_bufnr = bufnr('%')
929         setlocal bufhidden=hide
930         call <SID>NM_newFileBuffer(g:notmuch_compose_temp_file_dir, '%s.mail',
931                                   \ 'compose', lines)
932         setlocal bufhidden=hide
933
934         call <SID>NM_cmd_compose_mksyntax()
935         call <SID>NM_set_map('n', g:notmuch_compose_nmaps)
936         call <SID>NM_set_map('i', g:notmuch_compose_imaps)
937
938         exec printf('norm %dG', start_on_line)
939         startinsert!
940         echo 'Type your message, use <TAB> to jump to next header and then body.'
941 endfunction
942 function! s:NM_cmd_compose_mksyntax()
943         silent! setlocal syntax=mail
944 endfunction
945
946 function! s:NM_compose_send()
947         echo 'not implemented'
948 endfunction
949
950 function! s:NM_compose_next_entry_area()
951         let lnum = line('.')
952         let hdr_end = <SID>NM_compose_find_line_match(1,'^$',1)
953         echo 'header end = ' . string(hdr_end)
954         if lnum < hdr_end
955                 let lnum = lnum + 1
956                 let line = getline(lnum)
957                 if match(line, '^\([^:]\+\):\s*$') == -1
958                         call cursor(lnum, strlen(line) + 1)
959                         return ''
960                 endif
961                 while match(getline(lnum+1), '^\s') != -1
962                         let lnum = lnum + 1
963                 endwhile
964                 call cursor(lnum, strlen(getline(lnum)) + 1)
965                 return ''
966
967         elseif lnum == hdr_end
968                 call cursor(lnum+1, strlen(getline(lnum+1)) + 1)
969                 return ''
970         endif
971         echo 'mode=' . mode()
972         if mode() == 'i'
973                 if !getbufvar(bufnr('.'), '&et')
974                         return "\t"
975                 endif
976                 let space = ''
977                 let shiftwidth = a:shiftwidth
978                 let shiftwidth = shiftwidth - ((virtcol('.')-1) % shiftwidth)
979                 " we assume no one has shiftwidth set to more than 40 :)
980                 return '                                        '[0:shiftwidth]
981         endif
982 endfunction
983
984 " --- --- compose screen helper functions {{{2
985
986 function! s:NM_compose_get_user_email()
987         let name = substitute(system('id -u -n'), '\v(^\s*|\s*$|\n)', '', 'g')
988         let fqdn = substitute(system('hostname -f'), '\v(^\s*|\s*$|\n)', '', 'g')
989
990         " TODO: do this properly
991         return name . '@' . fqdn
992 endfunction
993
994 function! s:NM_compose_find_line_match(start, pattern, failure)
995         let lnum = a:start
996         let lend = line('$')
997         while lnum < lend
998                 if match(getline(lnum), a:pattern) != -1
999                         return lnum
1000                 endif
1001                 let lnum = lnum + 1
1002         endwhile
1003         return a:failure
1004 endfunction
1005
1006
1007 " --- notmuch helper functions {{{1
1008
1009 function! s:NM_newBuffer(type, content)
1010         enew
1011         setlocal buftype=nofile readonly modifiable scrolloff=0 sidescrolloff=0
1012         silent put=a:content
1013         keepjumps 0d
1014         setlocal nomodifiable
1015         execute printf('set filetype=notmuch-%s', a:type)
1016         execute printf('set syntax=notmuch-%s', a:type)
1017         let b:nm_type = a:type
1018 endfunction
1019
1020 function! s:NM_newFileBuffer(fdir, fname, type, lines)
1021         let fdir = expand(a:fdir)
1022         if !isdirectory(fdir)
1023                 call mkdir(fdir, 'p')
1024         endif
1025         let file_name = <SID>NM_mktemp(fdir, a:fname)
1026         if writefile(a:lines, file_name)
1027                 throw 'Eeek! couldn''t write to temporary file ' . file_name
1028         endif
1029         exec printf('edit %s', file_name)
1030         setlocal buftype= noreadonly modifiable scrolloff=0 sidescrolloff=0
1031         execute printf('set filetype=notmuch-%s', a:type)
1032         execute printf('set syntax=notmuch-%s', a:type)
1033         let b:nm_type = a:type
1034 endfunction
1035
1036 function! s:NM_mktemp(dir, name)
1037         let time_stamp = strftime('%Y%m%d-%H%M%S')
1038         let file_name = substitute(a:dir,'/*$','/','') . printf(a:name, time_stamp)
1039         " TODO: check if it exists, try again
1040         return file_name
1041 endfunction
1042
1043 function! s:NM_shell_escape(word)
1044         " TODO: use shellescape()
1045         let word = substitute(a:word, '''', '\\''', 'g')
1046         return '''' . word . ''''
1047 endfunction
1048
1049 " this function was taken from git.vim, then fixed up
1050 " http://github.com/motemen/git-vim
1051 function! s:NM_shell_split(cmd)
1052         let l:split_cmd = []
1053         let cmd = a:cmd
1054         let iStart = 0
1055         while 1
1056                 let t = match(cmd, '\S', iStart)
1057                 if t < iStart
1058                         break
1059                 endif
1060                 let iStart = t
1061
1062                 let iSpace = match(cmd, '\v(\s|$)', iStart)
1063                 if iSpace < iStart
1064                         break
1065                 endif
1066
1067                 let iQuote1 = match(cmd, '\(^["'']\|[^\\]\@<=["'']\)', iStart)
1068                 if iQuote1 > iSpace || iQuote1 < iStart
1069                         let iEnd = iSpace - 1
1070                         let l:split_cmd += [ cmd[iStart : iEnd] ]
1071                 else
1072                         let q = cmd[iQuote1]
1073                         let iQuote2 = match(cmd, '[^\\]\@<=[' . q . ']', iQuote1 + 1)
1074                         if iQuote2 < iQuote1
1075                                 throw 'No matching ' . q . ' quote'
1076                         endif
1077                         let iEnd = iQuote2
1078                         let l:split_cmd += [ cmd[iStart+1 : iEnd-1 ] ]
1079                 endif
1080
1081
1082                 let iStart = iEnd + 1
1083         endwhile
1084
1085         return l:split_cmd
1086 endfunction
1087
1088
1089 function! s:NM_run(args)
1090         let words = a:args
1091         call map(words, 's:NM_shell_escape(v:val)')
1092         let cmd = g:notmuch_cmd . ' ' . join(words) . '< /dev/null'
1093
1094         let start = reltime()
1095         let out = system(cmd)
1096         let err = v:shell_error
1097         let delta = reltime(start)
1098
1099         if exists('g:notmuch_debug') && g:notmuch_debug
1100                 echo printf('[%s] {%s} %s', reltimestr(delta), string(err), string(cmd))
1101         endif
1102
1103         if err
1104                 echohl Error
1105                 echo substitute(out, '\n*$', '', '')
1106                 echohl None
1107                 return ''
1108         else
1109                 return out
1110         endif
1111 endfunction
1112
1113 " --- external mail handling helpers {{{1
1114
1115 function! s:NM_new_mail()
1116         echo 'not implemented'
1117 endfunction
1118
1119 " --- other helpers {{{1
1120
1121 function! s:NM_kill_this_buffer()
1122         if exists('b:nm_prev_bufnr')
1123                 setlocal bufhidden=delete
1124                 exec printf(":buffer %d", b:nm_prev_bufnr)
1125         else
1126                 echo "This is the last buffer; use :q<CR> to quit."
1127         endif
1128 endfunction
1129
1130 function! s:NM_search_expand(arg)
1131         let word = expand(a:arg)
1132         let prev_bufnr = bufnr('%')
1133         setlocal bufhidden=hide
1134         call <SID>NM_cmd_search([word])
1135         setlocal bufhidden=delete
1136         let b:nm_prev_bufnr = prev_bufnr
1137 endfunction
1138
1139 function! s:NM_add_remove_tags(filter, prefix, tags)
1140         let filter = len(a:filter) ? a:filter : [<SID>NM_search_thread_id()]
1141         if !len(filter)
1142                 echoe 'Eeek! I couldn''t find the thead id!'
1143         endif
1144         call map(a:tags, 'a:prefix . v:val')
1145         let args = ['tag']
1146         call extend(args, a:tags)
1147         call add(args, '--')
1148         call extend(args, filter)
1149         " TODO: handle errors
1150         call <SID>NM_run(args)
1151 endfunction
1152
1153 function! s:NM_add_remove_tags_on_screen(online, prefix, tags)
1154         setlocal modifiable
1155         if a:prefix == '-'
1156                 for tagname in a:tags
1157                         exec printf('silent! %ss/(\([^)]*\)\<%s\>\([^)]*\))$/(\1\2)/', string(a:online), tagname)
1158                 endfor
1159         else
1160                 for tagname in a:tags
1161                         exec printf('silent! %ss/(\([^)]*\)\([^)]*\))$/(\1 %s)/', string(a:online), tagname)
1162                 endfor
1163         endif
1164         setlocal nomodifiable
1165 endfunction
1166
1167 " --- process and set the defaults {{{1
1168
1169 function! NM_set_defaults(force)
1170         for [key, dflt] in items(s:notmuch_defaults)
1171                 let cmd = ''
1172                 if !a:force && exists(key) && type(dflt) == type(eval(key))
1173                         continue
1174                 elseif type(dflt) == type(0)
1175                         let cmd = printf('let %s = %d', key, dflt)
1176                 elseif type(dflt) == type('')
1177                         let cmd = printf('let %s = ''%s''', key, dflt)
1178                 " FIXME: not sure why this didn't work when dflt is an array
1179                 "elseif type(dflt) == type([])
1180                 "        let cmd = printf('let %s = %s', key, string(dflt))
1181                 else
1182                         echoe printf('E: Unknown type in NM_set_defaults(%d) using [%s,%s]',
1183                                                 \ a:force, key, string(dflt))
1184                         continue
1185                 endif
1186                 exec cmd
1187         endfor
1188 endfunction
1189 call NM_set_defaults(0)
1190
1191 " for some reason NM_set_defaults() didn't work for arrays...
1192 if !exists('g:notmuch_show_headers')
1193         let g:notmuch_show_headers = s:notmuch_show_headers_defaults
1194 endif
1195 if !exists('g:notmuch_initial_search_words')
1196         let g:notmuch_initial_search_words = s:notmuch_initial_search_words_defaults
1197 endif
1198 if !exists('g:notmuch_folders')
1199         let g:notmuch_folders = s:notmuch_folders_defaults
1200 endif
1201
1202 if !exists('g:notmuch_signature')
1203         let g:notmuch_signature = s:notmuch_signature_defaults
1204 endif
1205 if !exists('g:notmuch_compose_headers')
1206         let g:notmuch_compose_headers = s:notmuch_compose_headers_defaults
1207 endif
1208
1209 " --- assign keymaps {{{1
1210
1211 function! s:NM_set_map(type, maps)
1212         nmapclear
1213         for [key, code] in items(a:maps)
1214                 exec printf('%snoremap <buffer> %s %s', a:type, key, code)
1215         endfor
1216         " --- this is a hack for development :)
1217         nnoremap ,nmr :source ~/.vim/plugin/notmuch.vim<CR>:call NotMuch('')<CR>
1218 endfunction
1219
1220 " --- command handler {{{1
1221
1222 function! NotMuch(args)
1223         let args = a:args
1224         if !strlen(args)
1225                 let args = 'folders'
1226         endif
1227
1228         let words = <SID>NM_shell_split(args)
1229         if words[0] == 'folders' || words[0] == 'f'
1230                 let words = words[1:]
1231                 call <SID>NM_cmd_folders(words)
1232
1233         elseif words[0] == 'search' || words[0] == 's'
1234                 if len(words) > 1
1235                         let words = words[1:]
1236                 elseif exists('b:nm_search_words')
1237                         let words = b:nm_search_words
1238                 else
1239                         let words = g:notmuch_initial_search_words
1240                 endif
1241                 call <SID>NM_cmd_search(words)
1242
1243         elseif words[0] == 'show'
1244                 echoe 'show is not yet implemented.'
1245
1246         elseif words[0] == 'new' || words[0] == 'compose'
1247                 let words = words[1:]
1248                 call <SID>NM_cmd_compose(words, [])
1249         endif
1250 endfunction
1251 function! CompleteNotMuch(arg_lead, cmd_line, cursor_pos)
1252         return []
1253 endfunction
1254
1255
1256 " --- glue {{{1
1257
1258 command! -nargs=* -complete=customlist,CompleteNotMuch NotMuch call NotMuch(<q-args>)
1259 cabbrev  notmuch <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'NotMuch' : 'notmuch')<CR>
1260
1261 " vim: set ft=vim ts=8 sw=8 et foldmethod=marker :