aboutsummaryrefslogtreecommitdiffstats
path: root/neovim/.config/nvim/lua/config/autocmds.lua
blob: e9ebe043b9c2ea97a7fd5d9360107ded658a695a (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
64
65
-- Remove trailing spaces on save, preserving cursor and search pattern
local function strip_trailing_whitespace()
  if vim.list_contains({ "markdown", "diff" }, vim.bo.filetype) then
    return
  end
  local view = vim.fn.winsaveview()
  vim.cmd([[keeppatterns %s/\s\+$//e]])
  vim.fn.winrestview(view)
end

vim.api.nvim_create_autocmd("BufWritePre", {
  pattern = "*",
  callback = strip_trailing_whitespace,
})

-- Project-local config: search upward from cwd for a .nvim.lua, the same
-- nearest-ancestor pattern LSP root-dir detection uses, so it's found
-- regardless of exactly which subdirectory Neovim's cwd is or how you got
-- there (:cd, opening a file, session restore, ...) - unlike core 'exrc'
-- (deliberately left off in options.lua), which only ever checks the
-- literal cwd once at startup.
local sourced_project_configs = {}

local function source_project_config()
  local found = vim.fs.find(".nvim.lua", {
    upward = true,
    path = vim.fn.getcwd(),
    stop = vim.env.HOME,
  })[1]
  if not found or sourced_project_configs[found] then
    return
  end

  -- vim.secure.read is the same trust mechanism 'exrc' itself uses: prompts
  -- on first encounter, honors ~/.local/state/nvim/trust, :trust still
  -- manages the allowlist unchanged. Returns nil (no prompt shown again)
  -- for a file previously denied.
  local content = vim.secure.read(found)
  if not content then
    return
  end
  sourced_project_configs[found] = true

  local chunk, load_err = load(content, "@" .. found)
  if not chunk then
    vim.notify("Error loading " .. found .. ":\n" .. load_err, vim.log.levels.ERROR)
    return
  end
  local ok, run_err = pcall(chunk)
  if not ok then
    vim.notify("Error running " .. found .. ":\n" .. run_err, vim.log.levels.ERROR)
  end
end

vim.api.nvim_create_autocmd({ "VimEnter", "DirChanged" }, {
  callback = source_project_config,
})

-- Note: the colorscheme (with its "desert" fallback) is applied from
-- lua/plugins/colorscheme.lua's own `config` function, not here — under
-- lazy.nvim that's the natural place to react to "the plugin is now loaded".
--
-- Note: the vimrc's "reload vimrc on save" autocmd has no clean Lua
-- equivalent (module caching means `require()`-based configs aren't simply
-- re-sourceable) and is deliberately not ported.