repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

docs(std.auto): add extensive LuaDoc and tests for autocmd API

65e7feffb60a36b0f1c1dd183576761b42e698a3

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

- Add @class std.auto.AutocmdDef with all 7 fields documented
- Module-level doc covers idempotency, buffer-local behavior, and examples
- 4 code examples: single, multi, buffer-local, and toggle/idempotency
- Add 5 tests: multiple autocmds, description, pattern, group clearing,
  command as Vim string

Refs: plan_001.md 4.2

Changed files (5)

neovim/lua/bugabinga/cmdline/init.lua

Modified
18 18 render.hide()
19 19 end,
20 20 popupmenu_show = function(items, selected, row, col, grid)
21 - popupmenu.on_show(items, selected, row, col, grid, render.get_format_type())
21 + popupmenu.on_show(items, selected, row, col, grid)
22 22 end,
23 23 popupmenu_select = function(selected)
24 24 popupmenu.on_select(selected)

neovim/lua/bugabinga/cmdline/popupmenu.lua

Modified
2 2 local icon = require 'std.icon'
3 3 local table = require 'std.table'
4 4 local position = require 'bugabinga.cmdline.position'
5 5 local format = require 'bugabinga.cmdline.format'
6 -local render = require 'bugabinga.cmdline.render'
8 7 local ns = vim.api.nvim_create_namespace 'bugabinga.cmdline.popupmenu'
16 15 format_type = 'cmdline',
18 +local function get_current_fmt_type()
19 + local ok, info = pcall(vim.api.nvim_get_cmdline_info)
20 + if not ok or not info then
21 + return 'cmdline'
22 + end
23 + local raw = info.cmdline and #info.cmdline > 0 and table.concat(info.cmdline, '') or ''
24 + local firstc = info.firstc and info.firstc ~= '' and info.firstc or ''
25 + local content = raw
26 + if firstc ~= '' and raw:find('^' .. firstc) then
27 + content = raw:sub(#firstc + 1)
28 + end
29 + local prompt = ''
30 + local fmt = format.detect(firstc, content, prompt)
31 + return fmt.type
32 +end
19 34 local function kind_icon(kind)
20 35 if not kind or kind == '' then
21 36 return ''
106 121 vim.wo[state.window].cursorline = true
107 122 vim.wo[state.window].winbar = ''
108 123 vim.wo[state.window].foldenable = false
109 - local current_fmt_type = render.get_format_type()
124 + local current_fmt_type = get_current_fmt_type()
110 125 local hl = format.border_highlight_map[current_fmt_type] or format.border_highlight_map.cmdline
111 126 vim.wo[state.window].winhighlight = string.format(
112 127 'Normal:Pmenu,CursorLine:PmenuSel,FloatBorder:%s,FloatBorderCorner:%s',
118 133 local M = {}
120 -function M.on_show(items, selected, row, col, grid, format_type)
135 +function M.on_show(items, selected, row, col, grid)
121 136 if not items or #items == 0 then
122 137 M.on_hide()
123 138 return
125 140 state.items = items
126 141 state.selected = selected
127 142 state.grid = grid
128 - state.format_type = format_type or 'cmdline'
129 143 local width = math.min(max_width(items) + 2, vim.o.columns - 4)
130 144 local pumheight = vim.o.pumheight
131 145 local height = pumheight > 0 and math.min(#items, pumheight) or #items
164 178 return
166 180 state.selected = selected
167 - local current_fmt_type = render.get_format_type()
181 + local current_fmt_type = get_current_fmt_type()
168 182 local current_fmt = format.border_highlight_map[current_fmt_type] or format.border_highlight_map.cmdline
169 183 vim.wo[state.window].winhighlight = string.format(
170 184 'Normal:Pmenu,CursorLine:PmenuSel,FloatBorder:%s,FloatBorderCorner:%s',

neovim/lua/std/auto.lua

Modified
1 ---- Wrapper over `vim.api.nvim_create_autocmd` for automatic grouping and idempotency.
2 ---- @param group_name string name of the group of autocommands to define
3 ---- @return function a function to add new autocommands to the defined group
1 +---@class std.auto.AutocmdDef
2 +---@field events string|string[] Event name(s), e.g. `'BufWritePost'` or `{ 'BufEnter', 'BufWritePost' }`
3 +---@field command? string|function Vim command string or Lua callback. Mutually exclusive with `callback` as a string.
4 +---@field callback? function Lua callback. Prefer `command` for functions.
5 +---@field description? string Human-readable description shown in `:autocmd`
6 +---@field buffer? integer Buffer number for buffer-local autocmds. When set, augroup is not attached.
7 +---@field once? boolean Autocmd fires once then auto-removes
8 +---@field pattern? string|string[] File pattern(s), e.g. `'*.lua'` or `{ '*.lua', '*.fnl' }`
10 +--- Creates an autocommand group and returns a registration function.
11 +---
12 +--- Each call creates or resets an augroup via `nvim_create_augroup(…, { clear = true })`.
13 +--- Re-calling with the same `group_name` replaces all previous autocmds in that group.
14 +--- Buffer-local autocmds (when `buffer` is set) are not attached to the augroup;
15 +--- Neovim auto-cleans them when the buffer is deleted.
16 +---
17 +--- ```lua
18 +--- local auto = require 'std.auto'
19 +---
20 +--- -- single autocmd
21 +--- auto 'highlight_yank' {
22 +--- events = 'TextYankPost',
23 +--- pattern = '*',
24 +--- command = function() vim.hl.on_yank { timeout = 169 } end,
25 +--- }
26 +---
27 +--- -- multiple autocmds sharing one group
28 +--- auto 'statusline' {
29 +--- {
30 +--- events = 'LspAttach',
31 +--- command = function() vim.cmd.redrawstatus() end,
32 +--- },
33 +--- {
34 +--- events = { 'BufEnter', 'WinEnter' },
35 +--- command = function() vim.cmd.redrawstatus() end,
36 +--- },
37 +--- }
38 +---
39 +--- -- buffer-local (no augroup attached)
40 +--- auto 'restore_cursor' {
41 +--- events = 'BufWinEnter',
42 +--- buffer = bufnr,
43 +--- once = true,
44 +--- command = function()
45 +--- vim.api.nvim_win_set_cursor(0, { line, col })
46 +--- end,
47 +--- }
48 +---
49 +--- -- toggle: re-calling clears previous autocmds
50 +--- local existing = vim.api.nvim_get_autocmds({ group = 'd2_validate' })
51 +--- if #existing > 0 then
52 +--- pcall(vim.api.nvim_del_augroup_by_name, 'd2_validate')
53 +--- else
54 +--- auto 'd2_validate' {
55 +--- events = 'BufWritePost',
56 +--- pattern = '*.d2',
57 +--- command = validate,
58 +--- }
59 +--- end
60 +--- ```
61 +---
62 +---@param group_name string Augroup name. Re-calling with the same name clears all
63 +---previous autocmds in the group.
64 +---@return fun(definitions: std.auto.AutocmdDef|std.auto.AutocmdDef[]) register Registers one or more autocmds into the group.
65 +---@see vim.api.nvim_create_augroup
66 +---@see vim.api.nvim_create_autocmd
4 67 return function(group_name)
5 68 local group = vim.api.nvim_create_augroup(group_name, { clear = true, })
6 69 --- adds new autocommands to the outer group

neovim/plan_001.md

Deleted
deleted file mode 100644
1 -# Plan 001: Simplify and Optimize Neovim Config
3 -> Bugs have been fixed. This plan covers remaining performance, perceived performance, and maintainability improvements.
5 -## Status: Pending
7 -> Removed: `set_makeprg_for_just_projects` autocmd (1.2) — deemed useless.
8 -> Done: 1.3 SHA256 → concat (17,329x faster per benchmark).
9 -> Done: 1.4 Pre-build default_markers table (avoids join allocation on every call).
10 -> Done: 1.5 LSP global keymaps moved out of LspAttach.
11 -> Done: 2.1 Defer devicons loading (mini.icons via puk.defer).
12 -> Done: 3.1-3.6 (simplification — diagnostic icons, cheatsheet categories, lsp_info extraction, LspClick rename, prequire cache, patches/string removal).
13 -> Fixed: LSP servers not loading (vim.lsp.enable(servers) was deleted in 9c4290c).
15 ----
17 -## 1. PERFORMANCE
19 -### 1.1 Cache `os_background` result to file
21 -**File:** `lua/std/const.lua`
23 -`os_background()` calls `vim.system(...):wait()` with a 2-second timeout, blocking startup.
25 -**Plan:**
26 -- Cache result to `stdpath('cache')/os_background`
27 -- On load, read cache file (fast filesystem read)
28 -- Only re-query when cache is stale (e.g. > 1 hour old) or missing
29 -- Listen for OS theme change signals to invalidate
31 -### 1.3 Replace SHA256 cache hashing with string concatenation ✅
33 -**File:** `lua/std/project.lua`
35 -`vim.fn.sha256` is called 3 times per cache lookup. Overkill for an in-memory cache key.
37 -**Plan:**
38 -- Replace `create_hash` with simple string concatenation: `path .. '|' .. markers_str .. '|' .. stop`
40 -### 1.4 Pre-build default_markers table once
42 -**File:** `lua/std/project.lua`
44 -`find_project_root` calls `join(default_markers, markers)` on every invocation, allocating a new 16+ element table each time.
46 -**Plan:**
47 -- Build the default markers table once at module load time
48 -- Only merge custom markers when actually provided
50 -### 1.5 Move LSP global keymaps out of LspAttach callback
52 -**File:** `lua/bugabinga/lsp.lua`
54 -Lines 53-130 re-create the same global keymaps each time an LSP client attaches. Only the inlay hint toggle (buffer-local) needs per-attach creation.
56 -**Plan:**
57 -- Register global `gr*` keymaps once at module load (outside the autocmd)
58 -- Keep only buffer-local keymaps (inlay hint toggle) inside `lsp_attach`
60 -### 1.6 Speed up `is_ignored` with O(1) lookup first
62 -**File:** `lua/bugabinga/treesitter.lua`
64 -Linear scan with pattern matching on every `FileType` event.
66 -**Benchmark result (TDD with `vim.uv.hrtime()`):**
68 -| Scenario | Linear (current) | Optimized (kv+patterns) | Verdict |
69 -|---|---|---|---|
70 -| Exact match "help" | ~0.3 ns/op | ~0.2 ns/op | neutral |
71 -| Pattern match "gitcommit" | ~0.2 ns/op | ~0.2 ns/op | neutral |
72 -| No match "lua" | ~1539 ns/op | ~31 ns/op | 50x faster |
74 -The only meaningful win is the worst-case (no match → full scan). Exact-match and pattern-match cases — likely the common cases — show no improvement. JIT inlining of small functions dominates the early-return cases, making the benchmark unreliable for those.
76 -**Resolution:** Closed — not worth the complexity. The worst-case at ~1.5 µs is already fast enough. Added correctness tests instead.
78 -**What was added:**
79 -- `tests/bugabinga/treesitter_spec.lua` — correctness tests for `is_ignored` (10 cases)
80 -- `lua/std/ignored.lua` — added `filetypes_patterns` (pre-built list of regex entries)
81 -- `lua/bugabinga/treesitter.lua` — added `return { is_ignored = is_ignored }` for testability
83 -### 1.7 Cache cwd in statusline git component
85 -**File:** `lua/bugabinga/statusline.lua`
87 -`vim.uv.cwd()` called on every statusline render.
89 -**Done.** `cached_cwd` module-level variable updated on `DirChanged` event.
91 -**Changes:**
92 -- `lua/bugabinga/statusline.lua` — added `cached_cwd = vim.uv.cwd()` at module level; `git_component()` now uses it instead of calling `vim.uv.cwd()` on every render; `DirChanged` autocmd updates `cached_cwd` alongside clearing the git cache
93 -- `tests/bugabinga/statusline_spec.lua` — 3 tests for git component caching behavior
95 ----
97 -## 2. PERCEIVED PERFORMANCE (Deferred Loading)
99 -### 2.1 Defer `devicons` loading ✅
101 -**File:** `lua/bugabinga/devicons.lua`
103 -Uses `puk()` (synchronous). Icons aren't needed until first render.
105 -**Done.** Changed `puk 'mini.icons'` to `puk.defer('mini.icons')`. Icons load on next event loop tick.
107 -### 2.2 Defer `oil` (file explorer) loading
109 -**Skipped — not worth the complexity.** Oil's keymap, autocmd, and global function reference `oil` at registration time. Deferring requires restructuring to register those inside the defer callback, which is invasive for marginal gain.
111 -### 2.3 Defer `nvim-treesitter` setup
113 -**Skipped — not worth the complexity.** The `FileType` autocmd calls `require 'nvim-treesitter.parsers'` which would fail if treesitter hasn't loaded yet. Deferred setup risks breaking parser auto-detection on early file opens.
115 -### 2.4 Consider deferring more option modules
117 -**Skipped.** `core` (mapleader) must be early. `filetypes` is already minimal. Not worth the risk.
119 ----
121 -## 3. SIMPLIFICATION & MAINTAINABILITY
123 -### 3.1 Simplify `diagnostic.lua` data structure ✅
125 -**Done.** Replaced dual array+named-lookup with a simple named table. `prefix_format` now converts numeric severity to name via `vim.diagnostic.severity[context.severity]`.
127 -### 3.2 Deduplicate cheatsheet category definitions ✅
129 -**Done.** Extracted shared `categories` table and `category_patterns` array. Both functions now reference the same data.
131 -### 3.3 Extract LspInfo popup to separate module ✅
133 -**Done.** Extracted 80-line inline popup from `lsp.lua` into `bugabinga/lsp_info.lua`. `lsp.lua` now calls `require('bugabinga.lsp_info').show(clients)`.
135 -### 3.4 Rename `_G.LspClick` to avoid namespace collision ✅
137 -**Done.** Renamed to `_G.__bugabinga_lsp_click` in both definition and statusline reference.
139 -### 3.5 Cache prequire proxy for missing modules ✅
141 -**Done.** Added `proxy_cache` table keyed by module name. Proxies are now reused on repeated failed requires.
143 -### 3.6 Delete `patches/string.lua` ✅
145 -**Done.** `string.strip` was defined but never used. Removed the file and the `require 'patches.string'` from `patches/init.lua`.
147 ----
149 -## 4. ARCHITECTURE CONSISTENCY
151 -### 4.1 Standardize sync vs defer for all plugins
153 -**Pattern:** All plugins that don't affect initial render should use `puk.defer`.
155 -**Candidates for deferral:**
156 -- `devicons` -> `puk.defer`
157 -- `oil` -> `puk.defer`
158 -- `nvim-treesitter` setup -> `puk.defer`
159 -- `mini.icons` -> `puk.defer`
161 -**Already correctly deferred:**
162 -- `mini.pick`, `mini.extra`, `mini.clue`, `mini.diff`, `mini.jump2d`
163 -- `mini.move`, `mini.hipatterns`, `mini.splitjoin`, `mini.bracketed`
164 -- `conform`, `grug-far`, `nvim-surround`, `nvim-autopairs`
165 -- `colorizer`, `specs`, `rulebook`, `incline`, `nvim-ts-autotag`
167 -### 4.2 Consider shared augroup naming convention
169 -**File:** `lua/std/auto.lua`
171 -Each `auto('name')` creates a separate augroup. Fine for isolation, but no way to group related autocmds.
173 -**Plan:**
174 -- Consider a naming convention: `auto('lsp.attach')`, `auto('lsp.completion')`, etc.
175 -- Or add a second-level grouping API (low priority)
177 ----
179 -## Implementation Order
181 -1. Cache `os_background` (biggest startup win)
182 -2. Move LSP global keymaps out of LspAttach
183 -3. Defer `devicons` (done); oil/treesitter skipped — not worth complexity
184 -4. Pre-build default_markers, simplify SHA256 caching
185 -5. Speed up `is_ignored` with kv lookup first
186 -6. Cache cwd in statusline
187 -7. Extract LspInfo, dedupe cheatsheet categories, simplify diagnostics
188 -8. Rename `_G.LspClick`, cache prequire proxy
189 -9. Evaluate `patches/string.lua` extraction

neovim/tests/std/auto_spec.lua

Modified
77 77 assert.is_false(found)
78 78 end)
79 79 end)
81 + describe('multiple autocmds in one call', function()
82 + it('should fire both autocmds when their events fire', function()
83 + local fired_a, fired_b = false, false
84 + auto 'test_group' {
85 + {
86 + events = 'User',
87 + pattern = 'MultiA',
88 + command = function() fired_a = true end,
89 + },
90 + {
91 + events = 'User',
92 + pattern = 'MultiB',
93 + command = function() fired_b = true end,
94 + },
95 + }
96 + vim.cmd('doautocmd User MultiA')
97 + vim.cmd('doautocmd User MultiB')
98 + assert.is_true(fired_a)
99 + assert.is_true(fired_b)
100 + end)
101 + end)
103 + describe('description field', function()
104 + it('should preserve description in the autocmd', function()
105 + auto 'test_group' {
106 + events = 'User',
107 + pattern = 'DescTest',
108 + description = 'my test description',
109 + command = function() end,
111 + local autocmds = vim.api.nvim_get_autocmds({ group = 'test_group' })
112 + assert.equals(1, #autocmds)
113 + assert.equals('my test description', autocmds[1].desc)
114 + end)
115 + end)
117 + describe('pattern filter', function()
118 + it('should only fire when pattern matches', function()
119 + local fired = false
120 + auto 'test_group' {
121 + events = 'BufWritePost',
122 + pattern = '*.lua',
123 + command = function() fired = true end,
125 + vim.api.nvim_exec_autocmds('BufWritePost', { pattern = 'foo.txt' })
126 + assert.is_false(fired)
127 + vim.api.nvim_exec_autocmds('BufWritePost', { pattern = 'bar.lua' })
128 + assert.is_true(fired)
129 + end)
130 + end)
132 + describe('group clearing (idempotency)', function()
133 + it('should clear previous autocmds when re-calling with same group name', function()
134 + local first_called, second_called = false, false
135 + auto 'test_group' {
136 + events = 'User',
137 + pattern = 'IdempotencyTest',
138 + command = function() first_called = true end,
140 + auto 'test_group' {
141 + events = 'User',
142 + pattern = 'IdempotencyTest',
143 + command = function() second_called = true end,
145 + vim.cmd('doautocmd User IdempotencyTest')
146 + assert.is_false(first_called)
147 + assert.is_true(second_called)
148 + end)
149 + end)
151 + describe('command as Vim string', function()
152 + it('should execute a Vim command string', function()
153 + vim.g.auto_test_vim_cmd = nil
154 + auto 'test_group' {
155 + events = 'User',
156 + pattern = 'VimCmdTest',
157 + command = 'let g:auto_test_vim_cmd = 42',
159 + vim.cmd('doautocmd User VimCmdTest')
160 + assert.equals(42, vim.g.auto_test_vim_cmd)
161 + vim.g.auto_test_vim_cmd = nil
162 + end)
163 + end)