about summary refs log tree commit diff
path: root/fnl/nvrc/macro/event.fnl
blob: 3453431618dafd34908ed70558b8c3aa95bc38b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
(import-macros {: as->} :nvrc.macro.thread)

(local {: format} string)
(local {: insert : concat} table)

(local {: fn? : gensym-checksum : vlua} (require :nvrc.macro.toolkit))

(fn last [xs]
  (. xs (length xs)))

(fn ->str [x]
  (tostring x))

(fn includes? [xs x]
  (accumulate [is? false _ v (ipairs xs) :until is?]
    (= v x)))

(lambda au! [name ...]
  "Defines an autocommand group using the vim API."
  `(do
     (vim.cmd ,(format "augroup %s" name))
     (vim.cmd :autocmd!)
     (do
       ,...)
     (vim.cmd "augroup END")))

(lambda aub! [name ...]
  "Defines a buffer-local autocommand group using the vim API."
  `(do
     (vim.cmd ,(format "augroup %s" name))
     (vim.cmd "autocmd! * <buffer>")
     (do
       ,...)
     (vim.cmd "augroup END")))

(lambda ac! [events pattern ...]
  "Defines an autocommand using the vim API."
  (let [events (as-> [$ events] (if (sequence? $) $ [$])
                     (icollect [_ v (ipairs $)]
                       (->str v)) (concat $ ","))
        pattern (as-> [$ pattern] (if (sequence? $) $ [$])
                      (icollect [_ v (ipairs $)]
                        (->str v)) (concat $ ","))
        once? (or (includes? [...] `++once) (includes? [...] :++once))
        nested? (or (includes? [...] `++nested) (includes? [...] :++nested))
        command (last [...])]
    (if (fn? command)
        (let [fsym (gensym-checksum "__" command)]
          `(do
             (global ,fsym ,command)
             (vim.cmd ,(format (if (and once? nested?)
                                   "autocmd %s %s ++once ++nested call %s" once?
                                   "autocmd %s %s ++once call %s" nested?
                                   "autocmd %s %s ++nested call %s"
                                   "autocmd %s %s call %s")
                               events pattern (vlua fsym)))))
        `(vim.cmd ,(format (if (and once? nested?)
                               "autocmd %s %s ++once ++nested %s" once?
                               "autocmd %s %s ++once %s" nested?
                               "autocmd %s %s ++nested %s" "autocmd %s %s %s")
                           events pattern command)))))

{: au! : aub! : ac!}