summaryrefslogtreecommitdiff
path: root/plugin/autocmd.lua
blob: 1597a2114465dde8a68a9cb6da1e491fe3a6c563 (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
local autocmd = vim.api.nvim_create_autocmd

-- Highlight text being yanked.
autocmd({ "TextYankPost" }, {
  callback = function()
    vim.highlight.on_yank({
      higroup = "IncSearch",
      timeout = 50,
    })
  end,
})

-- Remove trailing whitespace on save (and keep cursor's position!).
autocmd({ "BufWritePre" }, {
  callback = function()
    local cursor = vim.fn.getpos(".")
    vim.cmd([[%s/\s\+$//e]])
    vim.fn.setpos(".", cursor)
  end,
})

-- Restore cursor's position in buffer from previous session.
autocmd({ "BufReadPost" }, {
  callback = function(args)
    local mark = vim.api.nvim_buf_get_mark(args.buf, '"')
    local count = vim.api.nvim_buf_line_count(args.buf)
    if mark[1] > 0 and mark[1] <= count then
      vim.cmd('normal! g`"zz')
    end
  end,
})

-- Close on `q` or `<Esc>`.
autocmd({ "FileType" }, {
  pattern = {
    "help",
    "qf",
    "lspinfo",
    "man",
    "checkhealth",
    "lazy",
  },
  command = [[
    nnoremap <buffer><silent> q :close<CR>
    nnoremap <buffer><silent> <Esc> :close<CR>
    set nobuflisted
  ]]
})

-- Autocreate a directory when saving a file.
autocmd({ "BufWritePre" }, {
  callback = function(event)
    if event.match:match("^%w%w+:[\\/][\\/]") then
      return
    end
    local file = vim.uv.fs_realpath(event.match) or event.match
    vim.fn.mkdir(vim.fn.fnamemodify(file, ":p:h"), "p")
  end,
})