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