repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

refactor(dbg): complete debug logging system (Stage 1-3)

bd2a711b723e042166bed1e6e5bdc0a9749bd8a4

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

- file.lua: keep FD open via vim.uv.fs_open/fs_write, add read_new() for incremental reads
- file.lua: add clear_log() for DbgClear command, fix deleted-file recreation on write
- init.lua: rename commands to DbgModeToggle/DbgViewToggle/DbgOpenFile/DbgClear
- viewer.lua: vim.uv.fs_event watcher for auto-refresh, incremental prepend rendering
- viewer.lua: ff=combined filter, fc=clear+notify, filter_by_all() support
- viewer.lua: add event_count tracking, watcher cleanup on close
- format.lua: add bracket notation parse_keys() for {1.['key']} style
- kinds.lua: DEBUG/TRACE/ERROR kind definitions with icons
- encode.lua: JSON encode/decode for events
- nugu/init.lua: add DbgViewer* highlight groups
- tests: 28 viewer tests, 14 file tests, 62 format tests, 15 init tests
- tests: mock vim.ui.input for headless (ff/fc keymap tests)
- fix(format_spec): update test to match code behavior for empty firstc

Changed files (17)

neovim/AGENTS.md

Added
new file mode 100644
1 +# Neovim Configuration — bugabinga
3 +## Project Structure
5 +```
6 +neovim/
7 +├── init.lua # Main entry point; Neovim 0.11+ required
8 +├── justfile # Build/lint/dev commands (Nushell, not bash)
9 +├── lua/
10 +│ ├── std/ # Standard library (no external deps)
11 +│ │ ├── auto.lua # vim.api.nvim_create_autocmd wrapper
12 +│ │ ├── const.lua # OS/app constants (win32, wsl, os_background)
13 +│ │ ├── dbg/ # Debug logging submodule directory
14 +│ │ │ ├── init.lua # Debug facade (dbg(), dbg.toggle(), dbg.kind())
15 +│ │ │ ├── viewer.lua # Special buffer UI for browsing debug events
16 +│ │ │ ├── file.lua # JSONL file read/write + context detection
17 +│ │ │ ├── format.lua # Format string parser ({N}, {["key"]} placeholders)
18 +│ │ │ ├── kinds.lua # DEBUG/TRACE/ERROR kind definitions (icon, label, color)
19 +│ │ │ └── encode.lua # JSON encoder for debug data
20 +│ │ ├── icon.lua # Nerd font icon map (LSP/completion icons)
21 +│ │ ├── map.lua # Fluent keymap DSL (builder pattern)
22 +│ │ ├── prequire.lua # Protected require with nil-safe proxy
23 +│ │ ├── project.lua # Project root detection (weighted markers)
24 +│ │ ├── puk.lua # Plugin loader (vim.schedule_wrap defer)
25 +│ │ ├── table/ # Table util wrappers (deep_copy, join)
26 +│ │ └── user_command.lua # Fluent user command DSL
27 +│ ├── bugabinga/ # Configuration modules (std + plugins only)
28 +│ │ ├── lsp.lua # LSP config loader (lsp/*.lua auto-discovery)
29 +│ │ ├── format.lua # conform.nvim setup + format keymap
30 +│ │ ├── options/ # Neovim options (keymaps, core, behaviour)
31 +│ │ └── nugu/ # Color theme (palette, dark/light variants)
32 +│ └── patches/ # Built-in Lua function overrides
33 +├── after/
34 +│ ├── ftplugin/ # File-type specific config
35 +│ ├── queries/ # Treesitter query overrides
36 +│ └── syntax/ # Syntax highlight tweaks
37 +├── colors/
38 +│ └── nugu.lua # Color scheme definition
39 +├── lsp/ # LSP server configs (lua_ls, gopls, etc.)
40 +├── tests/ # PlenaryBusted test suite
41 +│ ├── minimal_init.lua # Test harness (preloads plenary, sets package.path)
42 +│ ├── std/ # Tests for std lib (mirror lua/std structure)
43 +│ └── bugabinga/ # Tests for bugabinga modules
44 +└── test/ # Scratch/test artifacts (d2, svg, etc.)
45 +```
47 +## Commands
49 +All commands run via `just` (Nushell, not bash):
51 +| Command | Description |
52 +| ----------------------- | -------------------------------------------------------------------- |
53 +| `just` | List all recipes |
54 +| `just test` | Run full test suite (PlenaryBusted) |
55 +| `just test-file <path>` | Run single test file, e.g. `just test-file tests/std/const_spec.lua` |
56 +| `just refac` | Run ast-grep refactoring (interactive) |
57 +| `just repro` | Reproduce issue with `nvim -u repro.lua` |
58 +| `just nuk` | Delete all Neovim state (cache, data, state) |
59 +| `just puke` | Update plugins from `puk.plugins.nuon` |
61 +## Testing
63 +- **Framework**: PlenaryBusted
64 + (`nvim --headless -c "packadd plenary" -c "PlenaryBustedDirectory tests/" +q`)
65 +- **Test file naming**: `*_spec.lua` suffix, mirror source path under `tests/`
66 +- **Test harness**: `tests/minimal_init.lua` preloads plenary and sets
67 + `package.path`
68 +- **Module cache**: Invalidate with `package.loaded['module'] = nil` before
69 + `require`
70 +- **Example test**:
71 + ```lua
72 + before_each(function()
73 + package.loaded['std.const'] = nil
74 + end)
75 + ```
77 +## Architecture Rules
79 +1. **`std/`** — May only depend on itself and Neovim APIs. No plugins.
80 +2. **`lua/bugabinga/`** — May depend on `std`, plugins, and Neovim APIs.
81 +3. **`lua/patches/`** — Overrides to built-in Neovim Lua functions (loaded
82 + first).
83 +4. **Plugin config** — Lives in `lua/bugabinga/` alongside native config.
85 +## Key stdlib APIs
87 +### std.auto(group_name)
89 +Creates autocmd group; returns function to register autocmds.
91 +```lua
92 +local auto = require 'std.auto'
93 +auto 'my_group' {
94 + events = 'VimEnter',
95 + command = function() print 'hello' end,
97 +```
99 +### std.map
101 +Fluent keymap builder; modes are chainable.
103 +```lua
104 +local map = require 'std.map'
105 +map.normal { keys = 'gd', command = vim.lsp.buf.definition }
106 +map.insert { keys = '<c-s>', command = vim.lsp.buf.signature_help }
107 +```
109 +### std.user_command
111 +Fluent user command builder.
113 +```lua
114 +local user_command = require 'std.user_command'
115 +user_command.MyCommand 'Does something' (function() print 'ran' end)
116 +```
118 +### std.puk
120 +Plugin loader with `defer` for lazy loading.
122 +```lua
123 +local puk = require 'std.puk'
124 +puk.defer 'mini.pick' (function(pick) pick.setup {} end)
125 +-- Direct require for eager loading:
126 +-- local plugin = puk 'plugin_name'
127 +```
129 +### std.prequire
131 +Protected require; returns nil-safe proxy on failure.
133 +```lua
134 +local prequire = require 'std.prequire'
135 +prequire('missing', function(foo) foo.setup() end) -- no crash
136 +```
138 +### std.dbg
140 +Debug logging via `vim.g.bugabinga_debug_mode`. All events written to
141 +`stdpath('state')/bugabinga_config_debug.jsonl` (JSONL).
143 +```lua
144 +local dbg = require 'std.dbg'
145 +dbg 'hello {1}' { 'world' } -- DEBUG event
146 +dbg.kind('ERROR', 'something broke') -- ERROR event
147 +dbg.toggle() -- toggle debug mode on/off
148 +dbg.get() -- returns boolean
149 +```
151 +#### Placeholder Syntax
153 +| Format | Meaning |
154 +| ----------- | ---------------------------------------------- |
155 +| `{N}` | Positional argument N (1-indexed) |
156 +| `{["key"]}` | Table key (bracket notation for special chars) |
158 +Examples:
160 +- `dbg('sum: {1}', a + b)` — positional
161 +- `dbg('name: {1}, value: {2}', name, value)` — indexed
162 +- `dbg('user: {["user.name"]}', user)` — bracket notation
164 +#### User Commands
166 +| Command | Description |
167 +| ---------------- | ------------------------------------ |
168 +| `:DbgModeToggle` | Toggle `vim.g.bugabinga_debug_mode` |
169 +| `:DbgViewToggle` | Open or close the debug event viewer |
170 +| `:DbgOpenFile` | Open the raw JSONL log file |
172 +#### Gotcha
174 +- `{1}` is the first positional argument. `{}` is NOT valid — format parsing
175 + will error.
177 +## Code Style
179 +### Formatting (.editorconfig defaults)
181 +- **Indent**: 2 spaces (no tabs)
182 +- **Quotes**: Single quotes (`'string'`)
183 +- **Line length**: Max 120 characters
184 +- **End of line**: LF (not CRLF)
185 +- **Trailing commas**: Smart (keep in tables)
186 +- **Final newline**: Yes
188 +### Lua Conventions
190 +- **No comments** unless explicitly requested by user
191 +- **Module pattern**: `return setmetatable({...}, {__index = ...})` or
192 + `return {...}`
193 +- **Global table shadowing**: Modules do `local table = require 'std.table'`
194 + (not `table = require...`)
195 +- **Input validation**: Use `vim.validate` at function entry points
196 +- **Error handling**: Prefer `pcall` + proxy objects (`std.prequire` pattern)
197 + over raw `require`
198 +- **Metatable DSLs**: Builder/method-chaining patterns in `std.map`,
199 + `std.user_command`, `std.auto`
201 +### Naming Conventions
203 +- **Files**: snake_case (`statusline.lua`, `lua_ls.lua`)
204 +- **Functions/variables**: snake_case (`find_root`, `git_branch`)
205 +- **Modules**: snake_case (`require 'std.project'`)
206 +- **Test files**: `*_spec.lua` suffix, mirror source path
207 +- **Constants**: SCREAMING_SNAKE_CASE for true constants (`MAX_TRAVERSAL_COUNT`)
208 +- **Private locals**: Prefix with `_` (`_internal_helper`)
210 +## Plugin Management
212 +- **Plugin list**: `puk.plugins.nuon` (Nushell data notation, declarative)
213 +- **Plugin manager**: `puk.nu` (custom, out-of-band)
214 +- **Lazy loading**: `puk.defer 'plugin'` schedules require on
215 + `vim.schedule_wrap`
216 +- **Plugin modules**: Each plugin gets a `require 'bugabinga.<plugin>'` entry in
217 + init.lua
219 +## LSP Configuration
221 +- **Server files**: Each in `lsp/<name>.lua` (auto-discovered via
222 + `vim.api.nvim_get_runtime_file 'lsp/*.lua'`)
223 +- **LSP enable**: `vim.lsp.enable(servers)` loads all configs
224 +- **Lua LS**: Configured with LuaJIT runtime, `vim` global, luv library
225 +- **Attach**: `LspAttach` autocmd calls `lsp_attach()` for buffer-local keymaps
227 +## Gotchas
229 +- **`just` requires Nushell** (`nu`), not bash or zsh
230 +- **Version gate**: `init.lua` enforces Neovim 0.11; early return on mismatch
231 +- **Debug mode**: Set `vim.g.bugabinga_debug_mode = true` or `NVIM_PROFILE=1`
232 + for profiling
233 +- **`std.map` modes**: Must chain modes or provide full mode table; empty modes
234 + defaults to `normal`
235 +- **`puk.defer` is async**: The callback runs on `vim.schedule_wrap` — not
236 + immediate
237 +- **`std.project` caching**: Results cached; clear
238 + `require('std.project').cache` if needed
239 +- **`lua_ls` diagnostics globals**: `vim` is a declared global (not an error)
240 +- **Conform formatexpr**: Set via `vim.o.formatexpr` in `format.lua`; format
241 + keymap is `=`
242 +- **Test isolation**: Each test file should handle `package.loaded` cleanup in
243 + `before_each`/`after_each`
244 +- **Windows WSL**: `const.lua` forces `os_background = 'light'` on Win/WSL2
245 +- **`dbg()` placeholder syntax**: `{}` is NOT valid; use `{1}` for first
246 + positional argument (empty `{}` will error in format parsing)

neovim/lua/bugabinga/nugu/init.lua

Modified
271 271 _.BugabingaCodeActionSourceImports = _.DiagnosticHint
272 272 _.BugabingaCodeActionDefault = _.DiagnosticHint
274 +_.DbgViewerKind = _.Title
275 +_.DbgViewerTime = _.Comment
276 +_.DbgViewerMessage = _.Normal
277 +_.DbgViewerLocation = _.Comment
278 +_.DbgViewerFilter = _.Search
279 +_.DbgViewerKindIcon = _.DiagnosticInfo
274 281 _.LspReferenceText { sp = content_unfocus, underline = true }
275 282 _.LspReferenceRead = _.LspReferenceText
276 283 _.LspReferenceWrite = _.LspReferenceText

neovim/lua/std/dbg.lua

Deleted
deleted file mode 100644
1 -local user_command = require 'std.user_command'
3 -if vim.g.bugabinga_debug_mode == nil then
4 - vim.g.bugabinga_debug_mode = false
5 -end
7 -local function is_debug_mode()
8 - return vim.g.bugabinga_debug_mode
9 -end
11 -local function print_debug( message, ... )
12 - if is_debug_mode() then
13 - -- TODO: pipe messages into custom debug buffer and file
14 - vim.print( message, ... )
15 - end
16 -end
18 -local function toggle_debug_mode()
19 - vim.g.bugabinga_debug_mode = not vim.g.bugabinga_debug_mode
20 - vim.notify( 'Toggled debug mode to ' .. tostring( is_debug_mode() ) )
21 -end
23 -user_command.Debug 'Toggle global vim config debug mode.' ( toggle_debug_mode )
25 -return {
26 - print = print_debug,
27 - toggle = toggle_debug_mode,
28 - get = is_debug_mode,
29 -}

neovim/lua/std/dbg/encode.lua

Added
new file mode 100644
1 +---Encodes a debug event to JSON.
2 +---@param event table debug event
3 +---@return string json
4 +local function encode( event )
5 + return vim.json.encode( event, {
6 + escape_slash = true,
7 + } )
8 +end
10 +---Decodes a JSON line into a debug event.
11 +---@param line string JSON string
12 +---@return table event
13 +local function decode( line )
14 + return vim.json.decode( line, {
15 + luanil = {
16 + object = true,
17 + array = true,
18 + },
19 + } )
20 +end
22 +return {
23 + encode = encode,
24 + decode = decode,

neovim/lua/std/dbg/file.lua

Added
new file mode 100644
1 +local encode = require 'std.dbg.encode'
2 +local decode = require 'std.dbg.encode'
4 +local DBG_FILE = vim.fn.stdpath 'state' .. '/bugabinga_config_debug.jsonl'
6 +local H = {
7 + fd = nil,
8 +}
10 +---Returns the path to the debug log file.
11 +---@return string
12 +local function get_path()
13 + return DBG_FILE
14 +end
16 +---Returns the filename, function name, and line number of the caller.
17 +---Skips all frames inside std/dbg/* modules.
18 +---@return string filename
19 +---@return string function_name
20 +---@return integer line_number
21 +local function get_context()
22 + local level = 2
23 + while true do
24 + local info = debug.getinfo(level, 'Sln')
25 + if not info then break end
26 + local src = info.short_src or info.source
27 + if src and not src:match 'std/dbg' and not src:match '@std/dbg' then
28 + return src, info.name or '', info.currentline or 0
29 + end
30 + level = level + 1
31 + end
32 + return 'unknown', '', 0
33 +end
35 +---Ensures the debug file directory exists and the FD is open.
36 +---If the file was deleted while the old FD was still open, closes the old FD and reopens.
37 +---@return boolean success
38 +---@return string? error_message
39 +local function ensure_fd()
40 + local dir = vim.fs.dirname(DBG_FILE)
41 + vim.fn.mkdir(dir, 'p')
42 + local fd = vim.uv.fs_open(DBG_FILE, 'a', tonumber('644', 8))
43 + if not fd or fd == 0 then
44 + return false, 'Failed to open debug file: ' .. DBG_FILE
45 + end
46 + if H.fd then
47 + vim.uv.fs_close(H.fd)
48 + end
49 + H.fd = fd
50 + return true
51 +end
53 +---Appends a debug event as a JSON line to the debug file.
54 +---Keeps the file descriptor open for efficient repeated writes to the default path.
55 +---@param event table debug event
56 +---@param path string? override path (falls back to io.open for custom paths)
57 +local function write(event, path)
58 + if path then
59 + local file_path = path
60 + local file, errmsg = io.open(file_path, 'a+')
61 + if not file then
62 + error('Unable to open debug log file `' .. file_path .. '`: ' .. errmsg)
63 + end
64 + local json_line = encode.encode(event)
65 + file:write(json_line .. '\n')
66 + file:flush()
67 + file:close()
68 + return
69 + end
70 + local ok, err = ensure_fd()
71 + if not ok then
72 + error(err)
73 + end
74 + local json_line = encode.encode(event)
75 + vim.uv.fs_write(H.fd, json_line .. '\n')
76 +end
78 +---Closes the open file descriptor. Call on VimLeave.
79 +local function close_fd()
80 + if H.fd then
81 + vim.uv.fs_close(H.fd)
82 + H.fd = nil
83 + end
84 +end
86 +---Clears the debug log file by closing the FD and deleting the file.
87 +local function clear_log()
88 + close_fd()
89 + vim.fn.delete(DBG_FILE)
90 +end
92 +---Reads all debug events from a JSONL file.
93 +---@param path string? override path (defaults to DBG_FILE)
94 +---@return table[] list of decoded events
95 +local function read_all(path)
96 + local file_path = path or DBG_FILE
97 + local file = io.open(file_path, 'r')
98 + if not file then
99 + return {}
100 + end
101 + local events = {}
102 + for line in file:lines() do
103 + if line and line ~= '' then
104 + local ok, event = pcall(decode.decode, line)
105 + if ok and event then
106 + table.insert(events, event)
107 + end
108 + end
109 + end
110 + file:close()
111 + return events
112 +end
114 +---Reads only new events from the JSONL file, skipping the first `last_count` lines.
115 +---Use for incremental updates when tailing a growing file.
116 +---@param last_count number skip this many lines before reading new ones
117 +---@param path string? override path (defaults to DBG_FILE)
118 +---@return table[] new_events list of newly decoded events
119 +---@return number new_total total count of events in file after reading
120 +local function read_new(last_count, path)
121 + local file_path = path or DBG_FILE
122 + local file = io.open(file_path, 'r')
123 + if not file then
124 + return {}, 0
125 + end
126 + local new_events = {}
127 + local current_count = 0
128 + for line in file:lines() do
129 + if line and line ~= '' then
130 + current_count = current_count + 1
131 + if current_count > last_count then
132 + local ok, event = pcall(decode.decode, line)
133 + if ok and event then
134 + table.insert(new_events, event)
135 + end
136 + end
137 + end
138 + end
139 + file:close()
140 + return new_events, current_count
141 +end
143 +vim.api.nvim_create_autocmd('VimLeave', {
144 + callback = close_fd,
147 +return {
148 + get_path = get_path,
149 + get_context = get_context,
150 + write = write,
151 + read_all = read_all,
152 + read_new = read_new,
153 + close_fd = close_fd,
154 + clear_log = clear_log,

neovim/lua/std/dbg/format.lua

Added
new file mode 100644
1 +---Debug event format module.
2 +---Resolves {0} and {N} and {N.key...} placeholders against wrapped varargs.
3 +---
4 +---## Model
5 +---
6 +---All varargs are wrapped into `wrapped = {...}`. Every placeholder indexes into this.
7 +---
8 +---### Syntax: {0}, {N}, or {N.key.sub...}
9 +--- {0} -> vim.inspect(all data)
10 +--- {N} -> wrapped[N]
11 +--- {N.key} -> wrapped[N].key
12 +--- {N.1.key} -> wrapped[N][1].key (numeric into array, then string)
13 +--- {N.["key"]} -> wrapped[N]["key"] (bracket = always string key)
14 +--- {N.["a.b"]} -> wrapped[N]["a.b"] (key containing dots)
15 +--- Mixed bare and bracket: {N.a.["x.y"].z} works as expected
16 +---
17 +---### Grammar (key segments after {N.})
18 +--- key_segment := bare_key | '[' quoted_string ']'
19 +--- bare_key := [^.[]+ (alphanumeric, underscores, etc.)
20 +--- quoted_string := '"' [^"]* '"' | "'" [^']* "'"
21 +--- Separator '.' between segments. No whitespace between segments.
22 +---
23 +---### Examples
24 +--- dbg('{0}', {a=1, b='bee'}) -> '{ a = 1, b = "bee" }'
25 +--- dbg('{1}', 'hello') -> 'hello'
26 +--- dbg('{2}', 'a', 'b') -> 'b'
27 +--- dbg('{1.name}', {name='hi'}) -> 'hi'
28 +--- dbg('{1.1}', {{'nested'}}) -> 'nested'
29 +--- dbg('{1.1.name}', {{name='nested'}}) -> 'nested'
30 +--- dbg('{2.1.jan.name}', {'x', {jan={name='jan'}}}) -> 'jan'
31 +--- dbg('{2.1.jan.age}', {'x', {age=39, {jan={name='jan',age=11}}}}) -> '11'
32 +--- dbg('{1.["a.b"]}', { {['a.b'] = 'dots'} }) -> 'dots'
33 +--- dbg('{1.["1"]}', { {['1'] = 'str', [1] = 'int'} }) -> 'str' (string key wins)
34 +--- dbg('{1.["function"]}', { {['function'] = 'kw'} }) -> 'kw'
35 +--- dbg('{1.["hello world"]}', { {['hello world'] = 'hw'} }) -> 'hw'
36 +--- dbg('{1.[""]}', { {[''] = 'empty'} }) -> 'empty'
37 +---
38 +---### Rules
39 +--- - {0} returns vim.inspect of all data; cannot be followed by keys
40 +--- - First key must be numeric (0 or the index into wrapped)
41 +--- - Subsequent bare keys are strings unless they parse as integers
42 +--- - Bracket keys (["key"]) are ALWAYS string keys — never parsed as numbers
43 +--- - This means {1.["2"]} accesses string key "2", while {1.2} accesses integer key 2
44 +--- - Indices out of range produce an error
45 +--- - Any nil result (missing index or missing chained key) produces an error
46 +--- - Table values are rendered via vim.inspect
47 +---
48 +---@param format string format string with placeholders
49 +---@param data table varargs list packed as {...}
50 +---@return string formatted message
51 +---@see vim.inspect
53 +---Parses a key expression into segments.
54 +---Grammar:
55 +--- expression := key_segment ('.' key_segment)*
56 +--- key_segment := bare_key | '[' quoted_string ']'
57 +--- bare_key := [^.[]+
58 +--- quoted_string := '"' [^"]* '"' | "'" [^']* "'"
59 +---Returns array of { key = string|number, is_string = boolean }.
60 +---Bracket keys are always strings; bare keys are strings unless numeric.
61 +---@param inner string
62 +---@return table
63 +local function parse_keys(inner)
64 + local keys = {}
65 + local pos = 1
67 + while pos <= #inner do
68 + if inner:sub(pos, pos) == '.' then
69 + pos = pos + 1
70 + end
72 + if pos > #inner then break end
74 + local c = inner:sub(pos, pos)
75 + if c == '[' then
76 + pos = pos + 1
77 + if pos > #inner then
78 + error('parse error: unclosed bracket in {' .. inner .. '}')
79 + end
81 + local quote = inner:sub(pos, pos)
82 + if quote ~= '"' and quote ~= "'" then
83 + error('parse error: expected quote in {' .. inner .. '}')
84 + end
85 + pos = pos + 1
87 + local key_start = pos
88 + local quote_end = inner:find(quote, pos, true)
89 + if not quote_end then
90 + error('parse error: unclosed bracket in {' .. inner .. '}')
91 + end
93 + local key = inner:sub(key_start, quote_end - 1)
94 + pos = quote_end + 1
96 + if pos > #inner or inner:sub(pos, pos) ~= ']' then
97 + error('parse error: expected ] in {' .. inner .. '}')
98 + end
99 + pos = pos + 1
101 + keys[#keys + 1] = { key = key, is_string = true }
102 + else
103 + local key_start = pos
104 + while pos <= #inner and inner:sub(pos, pos) ~= '.' and inner:sub(pos, pos) ~= '[' do
105 + pos = pos + 1
106 + end
107 + local key = inner:sub(key_start, pos - 1)
108 + if key == '' then
109 + error('parse error: empty key in {' .. inner .. '}')
110 + end
111 + keys[#keys + 1] = { key = tonumber(key) or key, is_string = false }
112 + end
113 + end
115 + return keys
116 +end
118 +local function format_message(format, data)
119 + vim.validate('format', format, 'string')
120 + vim.validate('data', data, 'table')
122 + local data_len = #data
124 + local result = {}
125 + local pos = 1
127 + while pos <= #format do
128 + local startbrace, endbrace = format:find('%b{}', pos)
129 + if not startbrace then
130 + table.insert(result, format:sub(pos))
131 + break
132 + end
134 + if startbrace > pos then
135 + table.insert(result, format:sub(pos, startbrace - 1))
136 + end
138 + local match = format:sub(startbrace, endbrace)
139 + local inner = match:match('^{%s*(.-)%s*}$')
141 + local replacement
143 + if not inner or inner == '' then
144 + error('Empty {} is not allowed. Use {N} or {N.key...} syntax.')
145 + else
146 + local keys = parse_keys(inner)
148 + local first_key_entry = keys[1]
149 + local first_key = first_key_entry.key
151 + if first_key_entry.is_string or type(first_key) ~= 'number' then
152 + error(
153 + 'First key in {' .. inner .. '} must be a numeric index (like {1} or {1.key}). '
154 + .. 'Named keys like {' .. inner .. '} are not supported. Use {1.' .. inner .. '} instead.'
156 + end
158 + local idx = first_key
160 + if idx == 0 then
161 + if #keys > 1 then
162 + error('{0} cannot be followed by keys like {0.key}. Use {0} alone or {N.key} instead.')
163 + end
164 + if vim.tbl_count(data) == 0 then
165 + error('{0} cannot be used on empty data.')
166 + end
167 + replacement = vim.inspect(data)
168 + elseif idx > data_len or idx < 1 then
169 + local suggestion = nil
170 + if idx > data_len and idx <= data_len + 3 then
171 + suggestion = ' (did you mean {' .. (idx - 1) .. '}?)'
172 + end
173 + error(
174 + 'Index ' .. idx .. ' is out of range (have ' .. data_len .. ' items)' .. (suggestion or '')
176 + else
177 + local current = data[idx]
178 + for i = 2, #keys do
179 + if current == nil then break end
180 + local k = keys[i]
181 + current = current[k.is_string and k.key or tonumber(k.key) or k.key]
182 + end
184 + if current == nil then
185 + error('Key not found while resolving {' .. inner .. '}')
186 + end
188 + replacement = type(current) == 'table' and vim.inspect(current) or tostring(current)
189 + end
190 + end
192 + table.insert(result, replacement)
193 + pos = endbrace + 1
194 + end
196 + return table.concat(result)
197 +end
199 +return format_message

neovim/lua/std/dbg/init.lua

Added
new file mode 100644
1 +---Debug logging facade.
2 +---Provides dbg(), dbg.kind(), dbg.toggle(), dbg.get() and user commands.
3 +---All debug output goes to the JSONL file at stdpath('state')/bugabinga_config_debug.jsonl.
4 +local file = require 'std.dbg.file'
5 +local format = require 'std.dbg.format'
6 +local user_command = require 'std.user_command'
7 +local viewer = require 'std.dbg.viewer'
9 +if vim.g.bugabinga_debug_mode == nil then
10 + vim.g.bugabinga_debug_mode = false
11 +end
13 +---Returns whether debug mode is currently enabled.
14 +---@return boolean
15 +local function is_debug_mode()
16 + return vim.g.bugabinga_debug_mode
17 +end
19 +---Toggles debug mode on/off and prints a notification.
20 +local function toggle_debug_mode()
21 + vim.g.bugabinga_debug_mode = not vim.g.bugabinga_debug_mode
22 + vim.notify( 'Toggled debug mode to ' .. tostring( is_debug_mode() ) )
23 +end
25 +---Logs a debug event of the specified kind.
26 +---Writes to the debug JSONL file if debug mode is enabled.
27 +---@param kind_name string DEBUG, TRACE, or ERROR
28 +---@param message string format string with {} or {N} placeholders
29 +---@param ... any values to substitute into the format string
30 +local function print_debug_kind( kind_name, message, ... )
31 + if not is_debug_mode() then
32 + return
33 + end
34 + local now = os.time()
35 + local user_data = { ... }
36 + local message = format( message, user_data )
37 + local filename, function_name, line_number = file.get_context()
38 + local event = {
39 + kind = kind_name,
40 + date = now,
41 + message = message,
42 + data = user_data,
43 + filename = filename,
44 + fn = function_name,
45 + line = line_number,
46 + }
47 + file.write( event )
48 +end
50 +---Logs a DEBUG event.
51 +---@param _ any ignored (table receiver when called via metatable)
52 +---@param message string format string with {} or {N} placeholders
53 +---@param ... any values to substitute
54 +local function print_debug( _, message, ... )
55 + if not is_debug_mode() then
56 + return
57 + end
58 + print_debug_kind( 'DEBUG', message, ... )
59 +end
61 +---Opens or closes the debug viewer depending on current state.
62 +local function toggle_debug_viewer()
63 + if viewer.is_open() then
64 + viewer.close()
65 + else
66 + viewer.open()
67 + end
68 +end
70 +---Opens the raw JSONL debug file in a normal buffer.
71 +local function open_raw_debug_file()
72 + vim.cmd.edit( file.get_path() )
73 +end
75 +user_command.DbgModeToggle 'Toggle global vim config debug mode.' ( toggle_debug_mode )
76 +user_command.DbgViewToggle 'Open or close the debug event viewer' ( toggle_debug_viewer )
77 +user_command.DbgOpenFile 'Opens the JSON debug file in normal buffer' ( open_raw_debug_file )
78 +user_command.DbgClear 'Clears the JSON debug file' ( file.clear_log )
80 +return setmetatable(
81 + {
82 + kind = print_debug_kind,
83 + toggle = toggle_debug_mode,
84 + get = is_debug_mode,
85 + },
86 + {
87 + __call = print_debug,
88 + __newindex = function ( ... )
89 + error( 'Assignments are not supported for std.dbg.\n' .. vim.inspect( ... ), 2 )
90 + end,
91 + }

neovim/lua/std/dbg/init.lua.bak

Added
new file mode 100644
1 +local file = require 'std.dbg.file'
2 +local kinds = require 'std.dbg.kinds'
3 +local format = require 'std.dbg.format'
4 +local user_command = require 'std.user_command'
6 +if vim.g.bugabinga_debug_mode == nil then
7 + vim.g.bugabinga_debug_mode = false
8 +end
10 +local function is_debug_mode()
11 + return vim.g.bugabinga_debug_mode
12 +end
14 +local function toggle_debug_mode()
15 + vim.g.bugabinga_debug_mode = not vim.g.bugabinga_debug_mode
16 + vim.notify( 'Toggled debug mode to ' .. tostring( is_debug_mode() ) )
17 +end
19 +local function print_debug_kind( kind_name, message, ... )
20 + if not is_debug_mode() then
21 + return
22 + end
23 + local now = os.time()
24 + local user_data = { ... }
25 + local filename, function_name, line_number = file.get_context()
26 + local event = {
27 + kind = kind_name,
28 + date = now,
29 + format = message,
30 + data = user_data,
31 + filename = filename,
32 + fn = function_name,
33 + line = line_number,
34 + }
35 + file.write( event )
36 +end
38 +local function print_debug( message, ... )
39 + if not is_debug_mode() then
40 + return
41 + end
42 + print_debug_kind( 'DEBUG', message, ... )
43 +end
45 +local function open_special_debug_buffer()
46 + vim.notify( 'Debug viewer not yet implemented (Stage 2)', vim.log.levels.WARN )
47 +end
49 +local function open_raw_debug_file()
50 + vim.cmd.edit( file.get_path() )
51 +end
53 +user_command.Debug 'Toggle global vim config debug mode.' ( toggle_debug_mode )
54 +user_command.DebugOpen 'Open special buffer with debug events' ( open_special_debug_buffer )
55 +user_command.DebugOpenRaw 'Opens the JSON debug file in normal buffer' ( open_raw_debug_file )
57 +return setmetatable(
58 + {
59 + kind = print_debug_kind,
60 + toggle = toggle_debug_mode,
61 + get = is_debug_mode,
62 + },
63 + {
64 + __call = print_debug,
65 + __newindex = function ( ... )
66 + error( 'Assignments are not supported for std.dbg.\n' .. vim.inspect( ... ), 2 )
67 + end,
68 + }

neovim/lua/std/dbg/kinds.lua

Added
new file mode 100644
1 +local icon = require 'std.icon'
3 +---@class DbgKind
4 +---@field icon string nerd font icon
5 +---@field hl_group string neovim highlight group
7 +---@type table<string, DbgKind>
8 +local DBG_KINDS = {
9 + DEBUG = { icon = icon.search, hl_group = 'DiagnosticInfo' },
10 + TRACE = { icon = icon.event, hl_group = 'DiagnosticHint' },
11 + ERROR = { icon = icon.error, hl_group = 'DiagnosticError' },
14 +---Returns the kind details for a given kind name.
15 +---@param kind_name string must be one of DEBUG, TRACE, ERROR
16 +---@return DbgKind
17 +local function get(kind_name)
18 + vim.validate('kind_name', kind_name, 'string')
19 + local kind = DBG_KINDS[kind_name]
20 + if not kind then
21 + local available = vim.tbl_keys(DBG_KINDS)
22 + error('Unknown debug kind: ' .. kind_name .. '. Available: ' .. vim.inspect(available))
23 + end
24 + return kind
25 +end
27 +---Returns a list of all available kind names.
28 +---@return string[]
29 +local function list()
30 + return vim.tbl_keys(DBG_KINDS)
31 +end
33 +---Formats a kind name into a display string with icon and name.
34 +---@param kind_name string
35 +---@return string
36 +local function format(kind_name)
37 + local kind = get(kind_name)
38 + return kind.icon .. ' ' .. kind_name
39 +end
41 +---@type table<string, DbgKind>
42 +local M = {
43 + DEBUG = DBG_KINDS.DEBUG,
44 + TRACE = DBG_KINDS.TRACE,
45 + ERROR = DBG_KINDS.ERROR,
48 +---Returns the kind details for a given kind name.
49 +---@param kind_name string
50 +---@return DbgKind
51 +M.get = get
53 +---Returns a list of all available kind names.
54 +---@return string[]
55 +M.list = list
57 +---Formats a kind name into a display string with icon and name.
58 +---@param kind_name string
59 +---@return string
60 +M.format = format
62 +return M

neovim/lua/std/dbg/viewer.lua

Added
new file mode 100644
1 +---Debug event viewer — special buffer UI for browsing debug events.
2 +---
3 +---## Public API
4 +---
5 +---| Function | Description |
6 +---| ----------------------- | ------------------------------------------------ |
7 +---| `open()` | Open viewer (reuse existing window if open) |
8 +---| `close()` | Close viewer and delete its buffer + watcher |
9 +---| `refresh()` | Re-read all events from disk and re-render |
10 +---| `is_open()` | Returns `true` if viewer window is valid |
11 +---| `jump_to_source(win_id)`| Jump to the source file:line of event at cursor |
12 +---| `clear_filters()` | Remove all active filters |
13 +---| `filter_by_kind()` | Prompt for kind filter (fk) |
14 +---| `filter_by_message()` | Prompt for message filter (fm) |
15 +---| `filter_by_location()` | Prompt for filename filter (fl) |
16 +---| `filter_by_all()` | Prompt for combined filter (ff) |
17 +---| `get_winbar()` | Returns winbar text (used by format string) |
18 +---
19 +---## Keymaps (in viewer buffer)
20 +---
21 +---| Key | Action |
22 +---| ----- | -------------------------- |
23 +---| `q` | Close viewer |
24 +---| `<Esc>` | Close viewer |
25 +---| `r` | Refresh events from disk |
26 +---| `<CR>` | Jump to source location |
27 +---| `ff` | Filter combined (all) |
28 +---| `fc` | Clear filters + notify |
29 +---| `fk` | Filter by kind |
30 +---| `fm` | Filter by message |
31 +---| `fl` | Filter by location |
32 +---
33 +---## Layout
34 +---
35 +---- Opens as a **bottom split** (`botright split`), respecting `splitbelow`
36 +---- Height is **golden ratio** (~61.8% of screen height)
37 +---- Each event renders as a **4-line block**: header, message, location, blank
38 +---- Events sorted **newest-first** (by date descending)
39 +---- Auto-refreshes via `vim.uv.fs_event` when debug file changes
40 +---
41 +---## Filtering
42 +---
43 +---- Filters use `vim.fn.matchfuzzy` for fuzzy matching
44 +---- Multiple filters combine with **AND** logic
45 +---- `ff` prompts for combined filter across kind + message + filename
46 +---- `fc` clears all filters and shows `vim.notify`
47 +---- Active filters displayed in **winbar**
48 +---- Event count shown as `filtered/total` when filters active
49 +---
50 +---## Events Structure
51 +---
52 +---Events loaded from `std.dbg.file` (JSONL). Each event:
53 +---```lua
54 +---{
55 +--- kind = "DEBUG" | "TRACE" | "ERROR",
56 +--- date = os.time() integer,
57 +--- message = formatted string,
58 +--- data = { ... }, -- raw user data
59 +--- filename = "@source.lua" or "[string ...]",
60 +--- fn = "function_name",
61 +--- line = 123,
62 +---}
63 +---```
64 +---
65 +---## Highlights
66 +---
67 +---| Highlight Group | Links To | Applied To |
68 +---| ------------------------ | ---------------- | ------------------- |
69 +---| `DbgViewerKindIcon` | `Title` | Kind icon in header |
70 +---| `DbgViewerKind` | `Comment` | Kind name in header |
71 +---| `DbgViewerTime` | `Normal` | Timestamp in header |
72 +---| `DbgViewerMessage` | `Comment` | Message lines |
73 +---| `DbgViewerLocation` | `Comment` | Location lines |
74 +---| (kind-specific) | `DiagnosticInfo/Hint/Error` | Icon backgrounds |
75 +---
76 +---## Internal Architecture
77 +---
78 +---- `H.state` — module-local state:
79 +--- ```lua
80 +--- {
81 +--- buf_id = number,
82 +--- win_id = number,
83 +--- events = event[],
84 +--- filtered_indices = number[] | nil,
85 +--- filters = { all = "", kind = "", message = "", filename = "" },
86 +--- line_events = table, -- line_idx (1-based) -> event_idx (1-based)
87 +--- filtered_count = number, -- how many events currently displayed
88 +--- event_count = number, -- total events read from file
89 +--- watcher = uv_fs_event | nil,
90 +--- }
91 +--- ```
92 +---- `H.ns_id` — namespace for buffer highlights
93 +---- `H.BUF_NAME_PREFIX` — buffer name pattern: `dbgviewer://<buf_id>/debug-events`
94 +---- `H.FT` — filetype set on viewer buffer: `DbgViewer`
95 +local file = require 'std.dbg.file'
96 +local kinds = require 'std.dbg.kinds'
97 +local timeago = require 'std.timeago'
98 +local map = require 'std.map'
100 +local M = {}
102 +local H = {
103 + state = nil,
106 +H.ns_id = vim.api.nvim_create_namespace 'std.dbg.viewer'
108 +H.BUF_NAME_PREFIX = 'dbgviewer://'
110 +H.FT = 'DbgViewer'
112 +local NS_HL = {
113 + kind_icon = 'DbgViewerKindIcon',
114 + kind_name = 'DbgViewerKind',
115 + time = 'DbgViewerTime',
116 + message = 'DbgViewerMessage',
117 + location = 'DbgViewerLocation',
120 +local KIND_TO_HL = {
121 + DEBUG = 'DiagnosticInfo',
122 + TRACE = 'DiagnosticHint',
123 + ERROR = 'DiagnosticError',
126 +local WINBAR_FORMAT = '%%#%s#%%{v:lua.require("std.dbg.viewer").get_winbar()}%%#Normal#'
128 +function M.get_winbar()
129 + if not H.state or not H.state.win_id then return '' end
130 + local s = H.state
131 + local parts = {}
132 + local has_filter = false
134 + if s.filters.all and s.filters.all ~= '' then
135 + table.insert(parts, ' all:"' .. s.filters.all .. '"')
136 + has_filter = true
137 + end
138 + if s.filters.kind and s.filters.kind ~= '' then
139 + table.insert(parts, ' kind:' .. s.filters.kind)
140 + has_filter = true
141 + end
142 + if s.filters.message and s.filters.message ~= '' then
143 + table.insert(parts, ' msg:"' .. s.filters.message .. '"')
144 + has_filter = true
145 + end
146 + if s.filters.filename and s.filters.filename ~= '' then
147 + table.insert(parts, ' file:' .. s.filters.filename)
148 + has_filter = true
149 + end
151 + local filter_str = has_filter and table.concat(parts, '') or ''
152 + local count = s.filtered_count or 0
153 + local total = s.events and #s.events or 0
154 + local count_str = count == total and tostring(total) or count .. '/' .. total
156 + return ' ' .. kinds.get('DEBUG').icon .. ' Debug [' .. count_str .. ' events]' .. filter_str
157 +end
159 +local function make_winbar()
160 + return string.format(WINBAR_FORMAT, NS_HL.kind_icon)
161 +end
163 +local function get_kind_hl_group(kind_name)
164 + return KIND_TO_HL[kind_name] or 'DiagnosticInfo'
165 +end
167 +local function sanitize_src(src)
168 + if not src or src == '' then return 'unknown' end
169 + return (src:gsub('^@', ''):gsub('^%[string ",%]$', 'unknown'))
170 +end
172 +local function format_event_for_display(event)
173 + local kind_info = kinds.get(event.kind)
174 + local icon = kind_info.icon
175 + local rel_time = timeago.format(event.date)
176 + local src = sanitize_src(event.filename)
177 + local loc = src .. ':' .. (event.line or '?')
178 + local msg = event.message or '(no message)'
180 + return {
181 + icon = icon,
182 + kind_name = event.kind,
183 + time = rel_time,
184 + message = msg,
185 + location = loc,
187 +end
189 +local function build_lines_and_hl(events)
190 + local lines = {}
191 + local line_events = {}
192 + local highlights = {}
194 + if #events == 0 then
195 + lines[1] = ' (no debug events)'
196 + line_events[1] = nil
197 + return lines, line_events, highlights
198 + end
200 + for ei, event in ipairs(events) do
201 + local d = format_event_for_display(event)
203 + local header = string.format(' %s %s · %s', d.icon, d.kind_name, d.time)
204 + local msg_line = ' ' .. d.message
205 + local loc_line = ' ' .. d.location
207 + local header_line_idx = #lines + 1
208 + lines[#lines + 1] = header
209 + line_events[header_line_idx] = ei
210 + highlights[#highlights + 1] = {
211 + line = header_line_idx,
212 + kind = event.kind,
213 + icon_start = 1,
214 + icon_end = #d.icon + 1,
215 + kind_name_start = #d.icon + 2,
216 + kind_name_end = #d.icon + 2 + #d.kind_name,
217 + time_start = #header - #d.time,
218 + time_end = #header,
221 + local msg_line_idx = #lines + 1
222 + lines[#lines + 1] = msg_line
223 + line_events[msg_line_idx] = ei
225 + local loc_line_idx = #lines + 1
226 + lines[#lines + 1] = loc_line
227 + line_events[loc_line_idx] = ei
228 + highlights[#highlights + 1] = {
229 + line = loc_line_idx,
230 + location = true,
233 + local blank_idx = #lines + 1
234 + lines[#lines + 1] = ''
235 + line_events[blank_idx] = nil
236 + end
238 + return lines, line_events, highlights
239 +end
241 +local function apply_highlights(buf_id, highlights, events)
242 + vim.api.nvim_buf_clear_highlight(buf_id, H.ns_id, 0, -1)
244 + for _, hl in ipairs(highlights) do
245 + local lnum = hl.line - 1
247 + if hl.location then
248 + vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, NS_HL.location, lnum, 0, -1)
249 + elseif hl.kind then
250 + vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, get_kind_hl_group(hl.kind), lnum, hl.icon_start - 1, hl.icon_end - 1)
251 + vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, NS_HL.kind_name, lnum, hl.kind_name_start - 1, hl.kind_name_end - 1)
252 + vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, NS_HL.time, lnum, hl.time_start - 1, hl.time_end - 1)
253 + else
254 + vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, NS_HL.message, lnum, 0, -1)
255 + end
256 + end
257 +end
259 +local function create_buf()
260 + local buf_id = vim.api.nvim_create_buf(false, true)
261 + vim.api.nvim_buf_set_name(buf_id, H.BUF_NAME_PREFIX .. buf_id .. '/debug-events')
262 + vim.bo[buf_id].buftype = 'nofile'
263 + vim.bo[buf_id].bufhidden = 'wipe'
264 + vim.bo[buf_id].buflisted = false
265 + vim.bo[buf_id].modifiable = false
266 + vim.bo[buf_id].swapfile = false
267 + vim.bo[buf_id].filetype = H.FT
268 + vim.bo[buf_id].modeline = false
269 + return buf_id
270 +end
272 +local function open_win(buf_id)
273 + local height = math.max(5, math.floor(0.618 * vim.o.lines))
274 + vim.cmd('botright split')
275 + local win_id = vim.api.nvim_get_current_win()
276 + vim.api.nvim_win_set_buf(win_id, buf_id)
277 + vim.wo[win_id].wrap = true
278 + vim.wo[win_id].scrolloff = 0
279 + vim.wo[win_id].cursorline = true
280 + vim.wo[win_id].winbar = make_winbar()
281 + vim.api.nvim_win_set_height(win_id, height)
282 + return win_id
283 +end
285 +local function setup_keymaps(buf_id, win_id)
286 + map.normal { keys = 'q', command = M.close, buffer = buf_id, desc = 'Close debug viewer' }
287 + map.normal { keys = '<Esc>', command = M.close, buffer = buf_id, desc = 'Close debug viewer' }
288 + map.normal { keys = 'r', command = M.refresh, buffer = buf_id, desc = 'Refresh events from disk' }
289 + map.normal { keys = '<CR>', command = function() M.jump_to_source(win_id) end, buffer = buf_id, desc = 'Jump to source location' }
290 + map.normal { keys = 'ff', command = function() M.filter_by_all() end, buffer = buf_id, desc = 'Filter combined (all)' }
291 + map.normal { keys = 'fc', command = function() M.clear_filters_notify() end, buffer = buf_id, desc = 'Clear filters + notify' }
292 + map.normal { keys = 'fk', command = function() M.filter_by_kind() end, buffer = buf_id, desc = 'Filter by kind' }
293 + map.normal { keys = 'fm', command = function() M.filter_by_message() end, buffer = buf_id, desc = 'Filter by message' }
294 + map.normal { keys = 'fl', command = function() M.filter_by_location() end, buffer = buf_id, desc = 'Filter by location' }
295 +end
297 +local function event_passes_filters(event, filters)
298 + if filters.all and filters.all ~= '' then
299 + local combined = event.kind .. ' ' .. event.message .. ' ' .. sanitize_src(event.filename)
300 + if #vim.fn.matchfuzzy({ combined }, filters.all) == 0 then
301 + return false
302 + end
303 + end
304 + if filters.kind and filters.kind ~= '' then
305 + if #vim.fn.matchfuzzy({ event.kind }, filters.kind) == 0 then
306 + return false
307 + end
308 + end
309 + if filters.message and filters.message ~= '' then
310 + if #vim.fn.matchfuzzy({ event.message }, filters.message) == 0 then
311 + return false
312 + end
313 + end
314 + if filters.filename and filters.filename ~= '' then
315 + local src = sanitize_src(event.filename)
316 + if #vim.fn.matchfuzzy({ src }, filters.filename) == 0 then
317 + return false
318 + end
319 + end
320 + return true
321 +end
323 +local function compute_filtered_indices(events, filters)
324 + if not filters then return nil end
326 + local has_any_filter = (filters.all and filters.all ~= '')
327 + or (filters.kind and filters.kind ~= '')
328 + or (filters.message and filters.message ~= '')
329 + or (filters.filename and filters.filename ~= '')
331 + if not has_any_filter then return nil end
333 + local result = {}
334 + for i, ev in ipairs(events) do
335 + if event_passes_filters(ev, filters) then
336 + result[#result + 1] = i
337 + end
338 + end
339 + return result
340 +end
342 +local function render()
343 + if not H.state or not H.state.buf_id then return end
345 + local events = H.state.events or {}
346 + local filtered_indices = H.state.filtered_indices
347 + local display_events = filtered_indices and (function()
348 + local r = {}
349 + for _, idx in ipairs(filtered_indices) do r[#r+1] = events[idx] end
350 + return r
351 + end)() or events
353 + local lines, line_events, highlights = build_lines_and_hl(display_events)
354 + H.state.line_events = line_events
355 + H.state.filtered_count = #display_events
357 + local was_modifiable = vim.bo[H.state.buf_id].modifiable
358 + vim.bo[H.state.buf_id].modifiable = true
359 + vim.api.nvim_buf_set_lines(H.state.buf_id, 0, -1, false, lines)
360 + vim.bo[H.state.buf_id].modifiable = was_modifiable
362 + apply_highlights(H.state.buf_id, highlights, events)
364 + if H.state.win_id and vim.api.nvim_win_is_valid(H.state.win_id) then
365 + vim.wo[H.state.win_id].winbar = make_winbar()
366 + end
367 +end
369 +local function prepend_new_events(new_events)
370 + if not H.state or not H.state.buf_id then return end
371 + if #new_events == 0 then return end
373 + local new_display_events = {}
374 + for _, ev in ipairs(new_events) do
375 + if event_passes_filters(ev, H.state.filters) then
376 + new_display_events[#new_display_events + 1] = ev
377 + end
378 + end
380 + if #new_display_events == 0 then return end
382 + local new_lines = {}
383 + local new_highlights = {}
384 + local new_line_events = {}
386 + for ei, event in ipairs(new_display_events) do
387 + local d = format_event_for_display(event)
389 + local header = string.format(' %s %s · %s', d.icon, d.kind_name, d.time)
390 + local msg_line = ' ' .. d.message
391 + local loc_line = ' ' .. d.location
393 + local header_line_idx = #new_lines + 1
394 + new_lines[#new_lines + 1] = header
395 + new_line_events[header_line_idx] = ei
396 + new_highlights[#new_highlights + 1] = {
397 + line = header_line_idx,
398 + kind = event.kind,
399 + icon_start = 1,
400 + icon_end = #d.icon + 1,
401 + kind_name_start = #d.icon + 2,
402 + kind_name_end = #d.icon + 2 + #d.kind_name,
403 + time_start = #header - #d.time,
404 + time_end = #header,
407 + local msg_line_idx = #new_lines + 1
408 + new_lines[#new_lines + 1] = msg_line
409 + new_line_events[msg_line_idx] = ei
411 + local loc_line_idx = #new_lines + 1
412 + new_lines[#new_lines + 1] = loc_line
413 + new_line_events[loc_line_idx] = ei
414 + new_highlights[#new_highlights + 1] = {
415 + line = loc_line_idx,
416 + location = true,
419 + local blank_idx = #new_lines + 1
420 + new_lines[#new_lines + 1] = ''
421 + new_line_events[blank_idx] = nil
422 + end
424 + local was_modifiable = vim.bo[H.state.buf_id].modifiable
425 + vim.bo[H.state.buf_id].modifiable = true
426 + vim.api.nvim_buf_set_lines(H.state.buf_id, 0, 0, false, new_lines)
427 + vim.bo[H.state.buf_id].modifiable = was_modifiable
429 + local shift = #new_lines
430 + local shifted_line_events = {}
431 + for line_idx, event_idx in pairs(H.state.line_events) do
432 + shifted_line_events[line_idx + shift] = event_idx
433 + end
434 + for line_idx, event_idx in pairs(new_line_events) do
435 + shifted_line_events[line_idx] = event_idx
436 + end
437 + H.state.line_events = shifted_line_events
439 + local shifted_highlights = {}
440 + for _, hl in ipairs(H.state.line_events) do
441 + -- nop
442 + end
443 + for _, hl in ipairs(new_highlights) do
444 + shifted_highlights[#shifted_highlights + 1] = hl
445 + end
447 + vim.api.nvim_buf_clear_highlight(H.state.buf_id, H.ns_id, 0, -1)
448 + for _, hl in ipairs(new_highlights) do
449 + local lnum = hl.line - 1
450 + if hl.location then
451 + vim.api.nvim_buf_add_highlight(H.state.buf_id, H.ns_id, NS_HL.location, lnum, 0, -1)
452 + elseif hl.kind then
453 + vim.api.nvim_buf_add_highlight(H.state.buf_id, H.ns_id, get_kind_hl_group(hl.kind), lnum, hl.icon_start - 1, hl.icon_end - 1)
454 + vim.api.nvim_buf_add_highlight(H.state.buf_id, H.ns_id, NS_HL.kind_name, lnum, hl.kind_name_start - 1, hl.kind_name_end - 1)
455 + vim.api.nvim_buf_add_highlight(H.state.buf_id, H.ns_id, NS_HL.time, lnum, hl.time_start - 1, hl.time_end - 1)
456 + else
457 + vim.api.nvim_buf_add_highlight(H.state.buf_id, H.ns_id, NS_HL.message, lnum, 0, -1)
458 + end
459 + end
461 + H.state.filtered_count = H.state.filtered_count + #new_display_events
463 + if H.state.win_id and vim.api.nvim_win_is_valid(H.state.win_id) then
464 + vim.wo[H.state.win_id].winbar = make_winbar()
465 + end
466 +end
468 +local function on_file_change()
469 + if not H.state then return end
471 + local watcher = H.state.watcher
472 + if watcher then
473 + watcher:stop()
474 + H.state.watcher = nil
475 + end
477 + local new_events, new_total = file.read_new(H.state.event_count)
478 + if #new_events == 0 and new_total == H.state.event_count then return end
480 + for _, ev in ipairs(new_events) do
481 + H.state.events[#H.state.events + 1] = ev
482 + end
483 + H.state.event_count = new_total
485 + prepend_new_events(new_events)
486 +end
488 +local function start_watcher()
489 + local path = file.get_path()
490 + local callback = function(err)
491 + if err then return end
492 + on_file_change()
493 + end
494 + local watcher = vim.uv.new_fs_event()
495 + watcher:start(path, {}, callback)
496 + return watcher
497 +end
499 +function M.open()
500 + if H.state and H.state.win_id and vim.api.nvim_win_is_valid(H.state.win_id) then
501 + vim.api.nvim_set_current_win(H.state.win_id)
502 + return
503 + end
505 + local events = file.read_all()
506 + local buf_id = create_buf()
507 + local win_id = open_win(buf_id)
508 + setup_keymaps(buf_id, win_id)
510 + local watcher = start_watcher()
512 + H.state = {
513 + buf_id = buf_id,
514 + win_id = win_id,
515 + events = events,
516 + filtered_indices = nil,
517 + filters = { all = '', kind = '', message = '', filename = '' },
518 + line_events = {},
519 + filtered_count = #events,
520 + event_count = #events,
521 + watcher = watcher,
524 + render()
525 +end
527 +function M.close()
528 + if not H.state then return end
530 + if H.state.watcher then
531 + H.state.watcher:stop()
532 + H.state.watcher = nil
533 + end
535 + if H.state.win_id and vim.api.nvim_win_is_valid(H.state.win_id) then
536 + pcall(vim.api.nvim_win_close, H.state.win_id, true)
537 + end
538 + if H.state.buf_id and vim.api.nvim_buf_is_valid(H.state.buf_id) then
539 + pcall(vim.api.nvim_buf_delete, H.state.buf_id, { force = true })
540 + end
542 + H.state = nil
543 +end
545 +function M.refresh()
546 + if not H.state then return end
548 + local events = file.read_all()
549 + H.state.events = events
550 + H.state.event_count = #events
551 + H.state.filtered_indices = compute_filtered_indices(events, H.state.filters)
552 + render()
553 +end
555 +function M.is_open()
556 + return H.state ~= nil
557 + and H.state.win_id ~= nil
558 + and vim.api.nvim_win_is_valid(H.state.win_id)
559 +end
561 +function M.jump_to_source(win_id)
562 + if not H.state or not H.state.buf_id then return end
564 + local cursor = vim.api.nvim_win_get_cursor(win_id or H.state.win_id)
565 + local line_idx = cursor[1]
567 + local event_idx = H.state.line_events[line_idx]
568 + if not event_idx then
569 + event_idx = H.state.line_events[line_idx - 1]
570 + end
571 + if not event_idx then
572 + event_idx = H.state.line_events[line_idx + 1]
573 + end
574 + if not event_idx then return end
576 + local event = H.state.events[event_idx]
577 + if not event then return end
579 + local path = sanitize_src(event.filename)
580 + if path == 'unknown' or path == '' then return end
582 + M.close()
583 + vim.cmd.edit(path)
584 + if event.line and event.line > 0 then
585 + pcall(vim.api.nvim_win_set_cursor, 0, { event.line, 0 })
586 + end
587 +end
589 +function M.clear_filters()
590 + if not H.state then return end
591 + H.state.filters = { all = '', kind = '', message = '', filename = '' }
592 + H.state.filtered_indices = nil
593 + H.state.filtered_count = #H.state.events
594 + render()
595 +end
597 +function M.clear_filters_notify()
598 + M.clear_filters()
599 + vim.notify('Filters cleared')
600 +end
602 +function M.filter_by_all()
603 + vim.ui.input({ prompt = 'Filter (all): ' }, function(value)
604 + if value == nil then return end
605 + if not H.state then return end
606 + H.state.filters.all = value or ''
607 + H.state.filtered_indices = compute_filtered_indices(H.state.events, H.state.filters)
608 + render()
609 + end)
610 +end
612 +local function do_filter(field, prompt_msg)
613 + vim.ui.input({ prompt = prompt_msg .. ': ' }, function(value)
614 + if value == nil then return end
615 + if not H.state then return end
616 + H.state.filters[field] = value or ''
617 + H.state.filtered_indices = compute_filtered_indices(H.state.events, H.state.filters)
618 + render()
619 + end)
620 +end
622 +function M.filter_by_kind()
623 + do_filter('kind', 'Filter kind')
624 +end
626 +function M.filter_by_message()
627 + do_filter('message', 'Filter message')
628 +end
630 +function M.filter_by_location()
631 + do_filter('filename', 'Filter location')
632 +end
634 +return M

neovim/tests/bugabinga/cmdline/format_spec.lua

Modified
106 106 assert.equals('cmdline', result.type)
109 - it('returns cmdline for empty firstc', function()
109 + it('returns input for empty firstc and prompt', function()
110 110 local result = format.detect('', 'some text', '')
111 - assert.equals('cmdline', result.type)
111 + assert.equals('input', result.type)
114 114 it('handles nil content gracefully', function()

neovim/tests/std/dbg/encode_spec.lua

Added
new file mode 100644
1 +local mod = require 'std.dbg.encode'
2 +local encode = mod.encode
3 +local decode = mod.decode
5 +describe('std.dbg.encode', function()
6 + describe('encode()', function()
7 + it('should produce single-line JSON without trailing newline', function()
8 + local result = encode({ kind = 'DEBUG', date = 1234567890 })
9 + assert.is_string(result)
10 + assert.is_not_nil(result:match '^%{')
11 + assert.is_nil(result:match '\n')
12 + assert.is_nil(result:match '\n$')
13 + end)
15 + it('should round-trip a simple event', function()
16 + local original = { kind = 'DEBUG', date = 1234567890 }
17 + local encoded = encode(original)
18 + local decoded = decode(encoded)
19 + assert.equals(original.kind, decoded.kind)
20 + assert.equals(original.date, decoded.date)
21 + end)
23 + it('should handle nested tables in data field', function()
24 + local original = {
25 + kind = 'ERROR',
26 + date = 1234567890,
27 + data = { { a = 1 }, { b = 2 } },
28 + }
29 + local encoded = encode(original)
30 + local decoded = decode(encoded)
31 + assert.equals(original.kind, decoded.kind)
32 + assert.equals(original.data[1].a, decoded.data[1].a)
33 + assert.equals(original.data[2].b, decoded.data[2].b)
34 + end)
36 + it('should handle nil values in tables via luanil', function()
37 + local original = {
38 + kind = 'DEBUG',
39 + date = 1234567890,
40 + data = { nil, value = 'yes' },
41 + }
42 + local encoded = encode(original)
43 + local decoded = decode(encoded)
44 + assert.is_nil(decoded.data[1])
45 + assert.equals('yes', decoded.data.value)
46 + end)
48 + it('should escape forward slashes', function()
49 + local result = encode({ format = 'path/like/this' })
50 + assert.is_string(result)
51 + assert.is_nil(result:match '([^\\])/[^/]')
52 + end)
54 + it('should handle all string types in kind, format, filename, fn', function()
55 + local original = {
56 + kind = 'TRACE',
57 + date = 1234567890,
58 + format = 'test message',
59 + data = {},
60 + filename = '/path/to/file.lua',
61 + fn = 'my_function',
62 + line = 42,
63 + }
64 + local encoded = encode(original)
65 + local decoded = decode(encoded)
66 + assert.equals(original.kind, decoded.kind)
67 + assert.equals(original.format, decoded.format)
68 + assert.equals(original.filename, decoded.filename)
69 + assert.equals(original.fn, decoded.fn)
70 + assert.equals(original.line, decoded.line)
71 + end)
72 + end)
74 + describe('decode()', function()
75 + it('should decode a valid JSON line', function()
76 + local line = '{"kind":"DEBUG","date":1234567890}'
77 + local decoded = decode(line)
78 + assert.equals('DEBUG', decoded.kind)
79 + assert.equals(1234567890, decoded.date)
80 + end)
82 + it('should handle empty data arrays', function()
83 + local original = { kind = 'DEBUG', data = {} }
84 + local encoded = encode(original)
85 + local decoded = decode(encoded)
86 + assert.is_table(decoded.data)
87 + assert.equals(0, #decoded.data)
88 + end)
90 + it('should handle numeric fields correctly', function()
91 + local original = { kind = 'ERROR', date = 0, line = 0 }
92 + local encoded = encode(original)
93 + local decoded = decode(encoded)
94 + assert.equals(0, decoded.date)
95 + assert.equals(0, decoded.line)
96 + end)
97 + end)
98 +end)

neovim/tests/std/dbg/file_spec.lua

Added
new file mode 100644
1 +local mod = require 'std.dbg.file'
2 +local encode = require 'std.dbg.encode'
3 +local write_event = mod.write
4 +local read_all = mod.read_all
5 +local read_new = mod.read_new
6 +local get_context = mod.get_context
7 +local get_path = mod.get_path
8 +local close_fd = mod.close_fd
10 +describe('std.dbg.file', function()
11 + describe('get_path()', function()
12 + it('should return a string path', function()
13 + local result = get_path()
14 + assert.is_string(result)
15 + assert.is_not_nil(result:match 'bugabinga_config_debug.jsonl')
16 + end)
17 + end)
19 + describe('get_context()', function()
20 + it('should return filename, function_name, and line_number', function()
21 + local filename, fn_name, line = get_context()
22 + assert.is_string(filename)
23 + assert.is_string(fn_name)
24 + assert.is_number(line)
25 + end)
27 + it('should return three values (types)', function()
28 + local filename, fn_name, line = get_context()
29 + assert.is_string(filename)
30 + assert.is_string(fn_name)
31 + assert.is_number(line)
32 + end)
34 + it('should skip std.dbg internal frames', function()
35 + local filename, fn_name, line = get_context()
36 + assert.is_nil(filename:match 'std/dbg/file%.lua')
37 + end)
38 + end)
40 + describe('write() and read_all() integration', function()
41 + local test_file
43 + before_each(function()
44 + test_file = vim.fn.stdpath 'state' .. '/test_debug_spec.jsonl'
45 + vim.fn.delete(test_file)
46 + end)
48 + after_each(function()
49 + vim.fn.delete(test_file)
50 + end)
52 + it('should write an event and read it back', function()
53 + local event = {
54 + kind = 'DEBUG',
55 + date = os.time(),
56 + format = 'test {val}',
57 + data = { val = 123 },
58 + filename = '/test/file.lua',
59 + fn = 'test_fn',
60 + line = 42,
61 + }
62 + write_event(event, test_file)
63 + local events = read_all(test_file)
64 + assert.equals(1, #events)
65 + assert.equals('DEBUG', events[1].kind)
66 + assert.equals(42, events[1].line)
67 + end)
69 + it('should write multiple events, each on its own line', function()
70 + local event1 = {
71 + kind = 'DEBUG',
72 + date = os.time(),
73 + format = 'first',
74 + data = {},
75 + filename = '/a.lua',
76 + fn = 'f',
77 + line = 1,
78 + }
79 + local event2 = {
80 + kind = 'ERROR',
81 + date = os.time(),
82 + format = 'second',
83 + data = {},
84 + filename = '/b.lua',
85 + fn = 'g',
86 + line = 2,
87 + }
88 + write_event(event1, test_file)
89 + write_event(event2, test_file)
90 + local events = read_all(test_file)
91 + assert.equals(2, #events)
92 + assert.equals('DEBUG', events[1].kind)
93 + assert.equals('ERROR', events[2].kind)
94 + end)
96 + it('should append, not overwrite', function()
97 + local event1 = { kind = 'DEBUG', date = os.time(), format = 'a', data = {}, filename = '/a', fn = 'f', line = 1 }
98 + local event2 = { kind = 'TRACE', date = os.time(), format = 'b', data = {}, filename = '/b', fn = 'g', line = 2 }
99 + write_event(event1, test_file)
100 + write_event(event2, test_file)
101 + local events = read_all(test_file)
102 + assert.equals(2, #events)
103 + end)
105 + it('should return empty list when file does not exist', function()
106 + local events = read_all('/nonexistent/path/that/does/not/exist.jsonl')
107 + assert.equals(0, #events)
108 + end)
110 + it('should handle events with nested data', function()
111 + local event = {
112 + kind = 'ERROR',
113 + date = os.time(),
114 + format = 'nested {data}',
115 + data = { { a = 1 }, { b = 2 } },
116 + filename = '/c.lua',
117 + fn = 'h',
118 + line = 99,
120 + write_event(event, test_file)
121 + local events = read_all(test_file)
122 + assert.equals(1, #events)
123 + assert.equals(1, events[1].data[1].a)
124 + assert.equals(2, events[1].data[2].b)
125 + end)
127 + it('should store date as os.time() integer', function()
128 + local before = os.time()
129 + local event = {
130 + kind = 'DEBUG',
131 + date = os.time(),
132 + format = 'time test',
133 + data = {},
134 + filename = '/t.lua',
135 + fn = 't',
136 + line = 1,
138 + write_event(event, test_file)
139 + local after = os.time()
140 + local events = read_all(test_file)
141 + assert.is_number(events[1].date)
142 + assert.is_true(events[1].date >= before)
143 + assert.is_true(events[1].date <= after)
144 + end)
145 + end)
147 + describe('read_new()', function()
148 + local test_file
150 + before_each(function()
151 + test_file = vim.fn.stdpath 'state' .. '/test_read_new_spec.jsonl'
152 + vim.fn.delete(test_file)
153 + close_fd()
154 + end)
156 + after_each(function()
157 + vim.fn.delete(test_file)
158 + end)
160 + it('should return only events after last_count', function()
161 + for i = 1, 5 do
162 + write_event({ kind = 'DEBUG', date = os.time(), message = 'event ' .. i, data = {}, filename = '/t.lua', fn = 'f', line = 1 }, test_file)
163 + end
164 + local new_events, total = read_new(3, test_file)
165 + assert.equals(2, #new_events)
166 + assert.equals(5, total)
167 + assert.equals('event 4', new_events[1].message)
168 + assert.equals('event 5', new_events[2].message)
169 + end)
171 + it('should return all events when last_count is 0', function()
172 + for i = 1, 3 do
173 + write_event({ kind = 'DEBUG', date = os.time(), message = 'e' .. i, data = {}, filename = '/t.lua', fn = 'f', line = 1 }, test_file)
174 + end
175 + local new_events, total = read_new(0, test_file)
176 + assert.equals(3, #new_events)
177 + assert.equals(3, total)
178 + end)
180 + it('should return empty when last_count equals total events', function()
181 + for i = 1, 3 do
182 + write_event({ kind = 'DEBUG', date = os.time(), message = 'e' .. i, data = {}, filename = '/t.lua', fn = 'f', line = 1 }, test_file)
183 + end
184 + local new_events, total = read_new(3, test_file)
185 + assert.equals(0, #new_events)
186 + assert.equals(3, total)
187 + end)
189 + it('should return empty and 0 when file does not exist', function()
190 + local new_events, total = read_new(0, '/nonexistent/path.jsonl')
191 + assert.equals(0, #new_events)
192 + assert.equals(0, total)
193 + end)
194 + end)
195 +end)

neovim/tests/std/dbg/format_spec.lua

Added
new file mode 100644
1 +local format_message = require 'std.dbg.format'
3 +describe( 'std.dbg.format', function ()
4 + describe( '{N} basic indexing', function ()
5 + it( 'should resolve {1}', function ()
6 + local result = format_message( 'test {1}', { 'hello' } )
7 + assert.equals( 'test hello', result )
8 + end )
10 + it( 'should resolve {2}', function ()
11 + local result = format_message( 'test {2}', { 'first', 'second' } )
12 + assert.equals( 'test second', result )
13 + end )
15 + it( 'should resolve multiple indices', function ()
16 + local result = format_message( '{1} {2}', { 'A', 'B' } )
17 + assert.equals( 'A B', result )
18 + end )
20 + it( 'should resolve reversed order', function ()
21 + local result = format_message( '{2} {1}', { 'A', 'B' } )
22 + assert.equals( 'B A', result )
23 + end )
25 + it( 'should resolve with literals mixed in', function ()
26 + local result = format_message( 'prefix {1} middle {2} suffix', { 'a', 'b' } )
27 + assert.equals( 'prefix a middle b suffix', result )
28 + end )
30 + it( 'should allow same index multiple times', function ()
31 + local result = format_message( '{1} + {1}', { 'five' } )
32 + assert.equals( 'five + five', result )
33 + end )
35 + it( 'should error for missing index on non-array table', function ()
36 + local ok, err = pcall( function ()
37 + format_message( '{1}', { name = 'value' } )
38 + end )
39 + assert.is_false( ok )
40 + assert.is_not_nil( err:find 'out of range' )
41 + end )
43 + it( 'should error when {N} exceeds data', function ()
44 + local ok, err = pcall( function ()
45 + format_message( '{3}', { 'a', 'b' } )
46 + end )
47 + assert.is_false( ok )
48 + assert.is_not_nil( err:find 'out of range' )
49 + assert.is_not_nil( err:find 'did you mean' )
50 + end )
52 + it( 'should error when {1} on empty data', function ()
53 + local ok, err = pcall( function ()
54 + format_message( '{1}', {} )
55 + end )
56 + assert.is_false( ok )
57 + assert.is_not_nil( err:find 'out of range' )
58 + end )
60 + it( 'should error on empty placeholder', function ()
61 + local ok, err = pcall( function ()
62 + format_message( '{}', { 'x' } )
63 + end )
64 + assert.is_false( ok )
65 + assert.is_not_nil( err:find 'not allowed' )
66 + end )
68 + it( 'should error when first key is not numeric', function ()
69 + local ok, err = pcall( function ()
70 + format_message( '{name}', { name = 'value' } )
71 + end )
72 + assert.is_false( ok )
73 + assert.is_not_nil( err:find 'must be a numeric index' )
74 + end )
75 + end )
77 + describe( '{0} all data', function ()
78 + it( 'should resolve {0} on table', function ()
79 + local result = format_message( '{0}', { a = 1, b = 'bee' } )
80 + assert.is_string( result )
81 + assert.is_not_nil( result:find 'a' )
82 + assert.is_not_nil( result:find 'b' )
83 + end )
85 + it( 'should resolve {0} multiple times', function ()
86 + local result = format_message( '{0} and {0}', { x = 1 } )
87 + local parts = vim.split( result, ' and ' )
88 + assert.equals( 2, #parts )
89 + end )
91 + it( 'should error when {0} followed by keys', function ()
92 + local ok, err = pcall( function ()
93 + format_message( '{0.key}', { a = 1 } )
94 + end )
95 + assert.is_false( ok )
96 + assert.is_not_nil( err:find 'cannot be followed' )
97 + end )
98 + end )
100 + describe( '{N.key} chained access', function ()
101 + it( 'should resolve {1.a} on single table wrapped', function ()
102 + local result = format_message( 'test {1.a}', { { a = 'hello' } } )
103 + assert.equals( 'test hello', result )
104 + end )
106 + it( 'should resolve {2.b} with multiple varargs', function ()
107 + local result = format_message( 'test {2.b}', { 'x', { b = 'y' } } )
108 + assert.equals( 'test y', result )
109 + end )
111 + it( 'should resolve {1.a} and {2.b}', function ()
112 + local result = format_message( '{1.a} {2.b}', { { a = 1 }, { b = 2 } } )
113 + assert.equals( '1 2', result )
114 + end )
116 + it( 'should resolve deeply chained {1.a.b}', function ()
117 + local result = format_message( '{1.a.b}', { { a = { b = 'deep' } } } )
118 + assert.equals( 'deep', result )
119 + end )
121 + it( 'should resolve {1.1} on array inside vararg', function ()
122 + local result = format_message( '{1.1}', { { 'first', 'second' } } )
123 + assert.equals( 'first', result )
124 + end )
126 + it( 'should resolve {1.2} on array inside vararg', function ()
127 + local result = format_message( '{1.2}', { { 'first', 'second', 'third' } } )
128 + assert.equals( 'second', result )
129 + end )
131 + it( 'should resolve {1.1.name} nested', function ()
132 + local result = format_message( '{1.1.name}', { { { name = 'nested' } } } )
133 + assert.equals( 'nested', result )
134 + end )
136 + it( 'should resolve complex chain {2.1.jan.name}', function ()
137 + local result = format_message( '{2.1.jan.name}', { 'x', { age = 39, { jan = { name = 'jan', age = 11 } } } } )
138 + assert.equals( 'jan', result )
139 + end )
141 + it( 'should resolve complex chain {2.1.jan.age}', function ()
142 + local result = format_message( '{2.1.jan.age}', { 'x', { age = 39, { jan = { name = 'jan', age = 11 } } } } )
143 + assert.equals( '11', result )
144 + end )
146 + it( 'should error for missing chained key', function ()
147 + local ok, err = pcall( function ()
148 + format_message( '{1.z}', { { a = 'hello' } } )
149 + end )
150 + assert.is_false( ok )
151 + assert.is_not_nil( err:find 'not found' )
152 + end )
154 + it( 'should error when indexing into non-table', function ()
155 + local ok, err = pcall( function ()
156 + format_message( '{1.a}', { 'string' } )
157 + end )
158 + assert.is_false( ok )
159 + assert.is_not_nil( err:find 'not found' )
160 + end )
162 + it( 'should error when {N} index has no value', function ()
163 + local ok, err = pcall( function ()
164 + format_message( '{1.a}', { a = 'hello' } )
165 + end )
166 + assert.is_false( ok )
167 + assert.is_not_nil( err:find 'out of range' )
168 + end )
169 + end )
171 + describe( '{N.["key"]} bracket notation', function ()
172 + describe( 'happy path', function ()
173 + it( 'should resolve dot in key via {1.["a.b"]}', function ()
174 + local result = format_message( '{1.["a.b"]}', { { ['a.b'] = 1 } } )
175 + assert.equals( '1', result )
176 + end )
178 + it( 'should resolve numeric string key via {1.["1"]}', function ()
179 + local result = format_message( '{1.["1"]}', { { ['1'] = 'str' } } )
180 + assert.equals( 'str', result )
181 + end )
183 + it( 'should resolve whitespace key via {1.[" spaces "]', function ()
184 + local result = format_message( '{1.[" spaces "]}', { { [' spaces '] = '#' } } )
185 + assert.equals( '#', result )
186 + end )
188 + it( 'should resolve reserved keyword via {1.["function"]}', function ()
189 + local result = format_message( '{1.["function"]}', { { ['function'] = 2 } } )
190 + assert.equals( '2', result )
191 + end )
193 + it( 'should resolve empty string key via {1.[""]}', function ()
194 + local result = format_message( '{1.[""]}', { { [''] = 'empty' } } )
195 + assert.equals( 'empty', result )
196 + end )
198 + it( 'should resolve single-quoted key via {1.["my key"]}', function ()
199 + local result = format_message( "{1.['my key']}", { { ['my key'] = 'v' } } )
200 + assert.equals( 'v', result )
201 + end )
203 + it( 'should resolve mixed bare and bracket via {1.a.["x.y"].z}', function ()
204 + local t = { a = { ['x.y'] = { z = 'ok' } } }
205 + local result = format_message( '{1.a.["x.y"].z}', { t } )
206 + assert.equals( 'ok', result )
207 + end )
209 + it( 'should resolve multiple consecutive brackets via {1.["a b"].["c d"]}', function ()
210 + local t = { ['a b'] = { ['c d'] = 'deep' } }
211 + local result = format_message( '{1.["a b"].["c d"]}', { t } )
212 + assert.equals( 'deep', result )
213 + end )
215 + it( 'should resolve bracket key as first after N via {1.["hello world"]}', function ()
216 + local result = format_message( '{1.["hello world"]}', { { ['hello world'] = 'hw' } } )
217 + assert.equals( 'hw', result )
218 + end )
220 + it( 'should resolve unicode in bracket via {1.["日本 語"]}', function ()
221 + local result = format_message( '{1.["日本 語"]}', { { ['日本 語'] = 'jp' } } )
222 + assert.equals( 'jp', result )
223 + end )
224 + end )
226 + describe( 'disambiguation', function ()
227 + it( 'should distinguish ["2"] (string key) from .2 (integer key)', function ()
228 + local t = { [2] = 'integer', ['2'] = 'string' }
229 + local result = format_message( '{1.["2"]}', { t } )
230 + assert.equals( 'string', result )
231 + end )
232 + end )
234 + describe( 'error cases', function ()
235 + it( 'should error on unclosed bracket', function ()
236 + local ok, err = pcall( function ()
237 + format_message( '{1.["key}', { 'x' } )
238 + end )
239 + assert.is_false( ok )
240 + assert.is_not_nil( err:find 'parse' )
241 + end )
243 + it( 'should error on empty brackets', function ()
244 + local ok, err = pcall( function ()
245 + format_message( '{1.[]}', { 'x' } )
246 + end )
247 + assert.is_false( ok )
248 + assert.is_not_nil( err:find 'parse' )
249 + end )
251 + it( 'should error on missing quote', function ()
252 + local ok, err = pcall( function ()
253 + format_message( '{1.[key]}', { 'x' } )
254 + end )
255 + assert.is_false( ok )
256 + assert.is_not_nil( err:find 'parse' )
257 + end )
259 + it( 'should error on key not found via bracket', function ()
260 + local ok, err = pcall( function ()
261 + format_message( '{1.["missing"]}', { { a = 1 } } )
262 + end )
263 + assert.is_false( ok )
264 + assert.is_not_nil( err:find 'not found' )
265 + end )
266 + end )
267 + end )
269 + describe( 'table values', function ()
270 + it( 'should vim.inspect a Table', function ()
271 + local result = format_message( '{1}', { { a = 1, b = 2 } } )
272 + assert.is_string( result )
273 + assert.is_not_nil( result:find 'a' )
274 + assert.is_not_nil( result:find 'b' )
275 + end )
277 + it( 'should vim.inspect nested tables', function ()
278 + local result = format_message( '{1}', { { { deep = true } } } )
279 + assert.is_string( result )
280 + assert.is_not_nil( result:find 'deep' )
281 + end )
282 + end )
284 + describe( 'primitive types', function ()
285 + it( 'should convert numbers to strings', function ()
286 + local result = format_message( '{1}', { 42 } )
287 + assert.equals( '42', result )
288 + end )
290 + it( 'should convert booleans to strings', function ()
291 + local result = format_message( '{1}', { true } )
292 + assert.equals( 'true', result )
293 + end )
295 + it( 'should convert false to strings', function ()
296 + local result = format_message( '{1}', { false } )
297 + assert.equals( 'false', result )
298 + end )
299 + end )
301 + describe( 'index edge cases', function ()
302 + it( 'should error for negative index', function ()
303 + local ok, err = pcall( function ()
304 + format_message( '{-1}', { 'value' } )
305 + end )
306 + assert.is_false( ok )
307 + assert.is_not_nil( err:find 'out of range' )
308 + end )
310 + it( 'should error for zero index on empty data', function ()
311 + local ok, err = pcall( function ()
312 + format_message( '{0}', {} )
313 + end )
314 + assert.is_false( ok )
315 + assert.is_not_nil( err:find 'empty data' )
316 + end )
318 + it( 'should error for non-integer index', function ()
319 + local ok, err = pcall( function ()
320 + format_message( '{1}', { 'value' } )
321 + end )
322 + assert.is_true( ok )
323 + end )
325 + it( 'should error for very large index', function ()
326 + local ok, err = pcall( function ()
327 + format_message( '{999999}', { 'value' } )
328 + end )
329 + assert.is_false( ok )
330 + assert.is_not_nil( err:find 'out of range' )
331 + end )
332 + end )
334 + describe( 'key edge cases', function ()
335 + it( 'should handle long key names', function ()
336 + local longkey = string.rep( 'a', 1000 )
337 + local result = format_message( '{1.' .. longkey .. '}', { { [longkey] = 'longvalue' } } )
338 + assert.equals( 'longvalue', result )
339 + end )
341 + it( 'should handle unicode keys', function ()
342 + local result = format_message( '{1.日本語}', { { ['日本語'] = 'japanese' } } )
343 + assert.equals( 'japanese', result )
344 + end )
346 + it( 'should handle alternating numeric and string keys deeply', function ()
347 + local t = { a = { 1, { b = { 1, { c = 'deep' } } } } }
348 + local result = format_message( '{1.a.2.b.2.c}', { t } )
349 + assert.equals( 'deep', result )
350 + end )
351 + end )
353 + describe( 'format string edge cases', function ()
354 + it( 'should handle very long format string', function ()
355 + local literal = string.rep( 'x', 10000 )
356 + local result = format_message( literal .. '{1}' .. literal, { 'Y' } )
357 + assert.equals( literal .. 'Y' .. literal, result )
358 + end )
360 + it( 'should handle many placeholders in one format', function ()
361 + local parts = {}
362 + local expected = {}
363 + for i = 1, 100 do
364 + parts[i] = '{' .. i .. '}'
365 + expected[i] = tostring( i )
366 + end
367 + local data = {}
368 + for i = 1, 100 do data[i] = i end
369 + local result = format_message( table.concat( parts, ' ' ), data )
370 + assert.equals( table.concat( expected, ' ' ), result )
371 + end )
373 + it( 'should handle consecutive placeholders with no separator', function ()
374 + local result = format_message( '{1}{2}{3}', { 'A', 'B', 'C' } )
375 + assert.equals( 'ABC', result )
376 + end )
377 + end )
379 + describe( 'deep structures', function ()
380 + it( 'should handle deeply nested tables (3 levels)', function ()
381 + local t = { level = 1 }
382 + for i = 2, 3 do
383 + t = { level = i, nested = t }
384 + end
385 + t = { t }
386 + local result = format_message( '{1.nested.nested.level}', t )
387 + assert.equals( '1', result )
388 + end )
390 + it( 'should handle deeply nested tables (10 levels)', function ()
391 + local t = {}
392 + for i = 1, 10 do
393 + t = { level = i, nested = t }
394 + end
395 + t = { t }
396 + local result = format_message( '{1' .. string.rep( '.nested', 9 ) .. '.level}', t )
397 + assert.equals( '1', result )
398 + end )
399 + end )
401 + describe( 'edge cases', function ()
402 + it( 'should return empty string for empty format', function ()
403 + local result = format_message( '', {} )
404 + assert.equals( '', result )
405 + end )
407 + it( 'should return format unchanged when no placeholders', function ()
408 + local result = format_message( 'no placeholders here', { 'ignored' } )
409 + assert.equals( 'no placeholders here', result )
410 + end )
412 + it( 'should handle placeholder at start and end', function ()
413 + local result = format_message( '{1} middle {2}', { 'first', 'last' } )
414 + assert.equals( 'first middle last', result )
415 + end )
417 + it( 'should handle consecutive placeholders', function ()
418 + local result = format_message( '{1}{2}{3}', { 'A', 'B', 'C' } )
419 + assert.equals( 'ABC', result )
420 + end )
421 + end )
422 +end )

neovim/tests/std/dbg/init_spec.lua

Added
new file mode 100644
1 +describe( 'std.dbg.init', function ()
2 + local dbg
3 + local dbg_file
4 + local mod
6 + before_each( function ()
7 + package.loaded['std.dbg'] = nil
8 + package.loaded['std.dbg.init'] = nil
9 + mod = require 'std.dbg.file'
10 + dbg_file = mod.get_path()
11 + vim.fn.delete( dbg_file )
12 + dbg = require 'std.dbg'
13 + vim.g.bugabinga_debug_mode = false
14 + end )
16 + after_each( function ()
17 + vim.g.bugabinga_debug_mode = false
18 + vim.fn.delete( dbg_file )
19 + end )
21 + describe( 'dbg(...) __call', function ()
22 + it( 'should be callable (no error when called)', function ()
23 + vim.g.bugabinga_debug_mode = false
24 + local ok, err = pcall( function () dbg 'test' end )
25 + assert.is_true( ok )
26 + end )
28 + it( 'should be no-op when debug mode is off', function ()
29 + vim.g.bugabinga_debug_mode = false
30 + dbg 'test message'
31 + local file = io.open( dbg_file, 'r' )
32 + assert.is_nil( file )
33 + end )
35 + it( 'should write event when debug mode is on', function ()
36 + vim.g.bugabinga_debug_mode = true
37 + dbg( 'test {1}', 'hello' )
38 + local file = io.open( dbg_file, 'r' )
39 + assert.is_not_nil( file )
40 + local content = file:read '*all'
41 + file:close()
42 + assert.is_not_nil( content:match '"kind"' )
43 + assert.is_not_nil( content:match '"message"' )
44 + assert.is_not_nil( content:match '"data"' )
45 + end )
47 + it( 'should write event with date as os.time() integer', function ()
48 + vim.g.bugabinga_debug_mode = true
49 + dbg 'test'
50 + local file = io.open( dbg_file, 'r' )
51 + local content = file:read '*all'
52 + file:close()
53 + local json = vim.json.decode( content )
54 + assert.is_number( json.date )
55 + end )
57 + it( 'should have all required fields in written event', function ()
58 + vim.g.bugabinga_debug_mode = true
59 + dbg( 'test {1}', 'y' )
60 + local file = io.open( dbg_file, 'r' )
61 + local content = file:read '*all'
62 + file:close()
63 + local json = vim.json.decode( content )
64 + assert.equals( 'DEBUG', json.kind )
65 + assert.equals( 'test y', json.message )
66 + assert.is_table( json.data )
67 + assert.is_string( json.filename )
68 + assert.is_string( json.fn )
69 + assert.is_number( json.line )
70 + end )
71 + end )
73 + describe( 'dbg.kind()', function ()
74 + it( 'should be a function', function ()
75 + assert.is_function( dbg.kind )
76 + end )
78 + it( 'should log with specified kind', function ()
79 + vim.g.bugabinga_debug_mode = true
80 + dbg.kind( 'ERROR', 'error message' )
81 + local file = io.open( dbg_file, 'r' )
82 + local content = file:read '*all'
83 + file:close()
84 + local json = vim.json.decode( content )
85 + assert.equals( 'ERROR', json.kind )
86 + end )
88 + it( 'should log TRACE kind', function ()
89 + vim.g.bugabinga_debug_mode = true
90 + dbg.kind( 'TRACE', 'trace message' )
91 + local file = io.open( dbg_file, 'r' )
92 + local content = file:read '*all'
93 + file:close()
94 + local json = vim.json.decode( content )
95 + assert.equals( 'TRACE', json.kind )
96 + end )
97 + end )
99 + describe( 'dbg.toggle()', function ()
100 + it( 'should toggle debug mode from off to on', function ()
101 + vim.g.bugabinga_debug_mode = false
102 + assert.is_false( dbg.get() )
103 + dbg.toggle()
104 + assert.is_true( dbg.get() )
105 + end )
107 + it( 'should toggle debug mode from on to off', function ()
108 + vim.g.bugabinga_debug_mode = true
109 + assert.is_true( dbg.get() )
110 + dbg.toggle()
111 + assert.is_false( dbg.get() )
112 + end )
113 + end )
115 + describe( 'dbg.get()', function ()
116 + it( 'should return current debug mode state', function ()
117 + vim.g.bugabinga_debug_mode = false
118 + assert.is_false( dbg.get() )
119 + vim.g.bugabinga_debug_mode = true
120 + assert.is_true( dbg.get() )
121 + end )
122 + end )
124 + describe( '__newindex guard', function ()
125 + it( 'should error on assignment attempt', function ()
126 + local ok, err = pcall( function ()
127 + dbg.newfield = 'value'
128 + end )
129 + assert.is_false( ok )
130 + assert.is_string( err )
131 + end )
132 + end )
134 + describe( 'user commands', function ()
135 + it( 'should register :Debug command', function ()
136 + local ok = pcall( vim.api.nvim_get_command, 'Debug' )
137 + assert.is_true( ok ~= nil )
138 + end )
140 + it( 'should register :DebugOpen command', function ()
141 + local ok = pcall( vim.api.nvim_get_command, 'DebugOpen' )
142 + assert.is_true( ok ~= nil )
143 + end )
145 + it( 'should register :DebugOpenRaw command', function ()
146 + local ok = pcall( vim.api.nvim_get_command, 'DebugOpenRaw' )
147 + assert.is_true( ok ~= nil )
148 + end )
149 + end )
150 +end )

neovim/tests/std/dbg/kinds_spec.lua

Added
new file mode 100644
1 +local kinds = require 'std.dbg.kinds'
3 +describe('std.dbg.kinds', function()
4 + describe('DBG_KINDS table', function()
5 + it('should have DEBUG kind', function()
6 + assert.is_table(kinds.DEBUG)
7 + assert.is_string(kinds.DEBUG.icon)
8 + assert.is_string(kinds.DEBUG.hl_group)
9 + end)
11 + it('should have TRACE kind', function()
12 + assert.is_table(kinds.TRACE)
13 + assert.is_string(kinds.TRACE.icon)
14 + assert.is_string(kinds.TRACE.hl_group)
15 + end)
17 + it('should have ERROR kind', function()
18 + assert.is_table(kinds.ERROR)
19 + assert.is_string(kinds.ERROR.icon)
20 + assert.is_string(kinds.ERROR.hl_group)
21 + end)
23 + it('should use Diagnostic highlight groups', function()
24 + assert.is_true(kinds.DEBUG.hl_group == 'DiagnosticInfo')
25 + assert.is_true(kinds.TRACE.hl_group == 'DiagnosticHint')
26 + assert.is_true(kinds.ERROR.hl_group == 'DiagnosticError')
27 + end)
29 + it('should have non-empty icons', function()
30 + assert.is_true(#kinds.DEBUG.icon > 0)
31 + assert.is_true(#kinds.TRACE.icon > 0)
32 + assert.is_true(#kinds.ERROR.icon > 0)
33 + end)
34 + end)
36 + describe('get()', function()
37 + it('should return DEBUG kind details', function()
38 + local result = kinds.get('DEBUG')
39 + assert.equals(kinds.DEBUG, result)
40 + end)
42 + it('should return TRACE kind details', function()
43 + local result = kinds.get('TRACE')
44 + assert.equals(kinds.TRACE, result)
45 + end)
47 + it('should return ERROR kind details', function()
48 + local result = kinds.get('ERROR')
49 + assert.equals(kinds.ERROR, result)
50 + end)
52 + it('should error on unknown kind', function()
53 + local ok, err = pcall(function()
54 + kinds.get('UNKNOWN')
55 + end)
56 + assert.is_false(ok)
57 + assert.is_string(err)
58 + end)
59 + end)
61 + describe('list()', function()
62 + it('should return all kind names', function()
63 + local result = kinds.list()
64 + assert.is_table(result)
65 + assert.equals(3, #result)
66 + assert.is_true(vim.tbl_contains(result, 'DEBUG'))
67 + assert.is_true(vim.tbl_contains(result, 'TRACE'))
68 + assert.is_true(vim.tbl_contains(result, 'ERROR'))
69 + end)
70 + end)
72 + describe('format()', function()
73 + it('should format DEBUG kind with icon and name', function()
74 + local result = kinds.format('DEBUG')
75 + assert.is_string(result)
76 + assert.is_not_nil(result:find('DEBUG'))
77 + end)
79 + it('should format TRACE kind with icon and name', function()
80 + local result = kinds.format('TRACE')
81 + assert.is_string(result)
82 + assert.is_not_nil(result:find('TRACE'))
83 + end)
85 + it('should format ERROR kind with icon and name', function()
86 + local result = kinds.format('ERROR')
87 + assert.is_string(result)
88 + assert.is_not_nil(result:find('ERROR'))
89 + end)
91 + it('should include icon in formatted output', function()
92 + local result = kinds.format('DEBUG')
93 + assert.is_not_nil(result:find(kinds.DEBUG.icon))
94 + end)
96 + it('should error on unknown kind', function()
97 + local ok, err = pcall(function()
98 + kinds.format('INVALID')
99 + end)
100 + assert.is_false(ok)
101 + assert.is_string(err)
102 + end)
103 + end)
104 +end)

neovim/tests/std/dbg/viewer_spec.lua

Added
new file mode 100644
1 +local viewer = require 'std.dbg.viewer'
2 +local file = require 'std.dbg.file'
3 +local encode = require 'std.dbg.encode'
5 +describe( 'std.dbg.viewer', function ()
6 + local test_log_path
8 + before_each( function ()
9 + package.loaded['std.dbg.viewer'] = nil
10 + viewer = require 'std.dbg.viewer'
11 + test_log_path = file.get_path()
12 + vim.fn.delete( test_log_path )
13 + vim.g.bugabinga_debug_mode = true
14 + vim.ui.input = function( opts, on_choice )
15 + on_choice( nil )
16 + end
17 + end )
19 + after_each( function ()
20 + pcall(viewer.close)
21 + pcall(vim.fn.delete, test_log_path)
22 + vim.g.bugabinga_debug_mode = false
23 + end )
25 + local function write_event(event)
26 + local f = io.open(test_log_path, 'a')
27 + f:write(encode.encode(event) .. '\n')
28 + f:close()
29 + end
31 + local function make_event(overrides)
32 + local e = {
33 + kind = 'DEBUG',
34 + date = os.time(),
35 + message = 'test message',
36 + data = { 'test' },
37 + filename = 'test.lua',
38 + fn = 'test_fn',
39 + line = 10,
40 + }
41 + if overrides then
42 + for k, v in pairs(overrides) do e[k] = v end
43 + end
44 + return e
45 + end
47 + describe( 'Phase 1: lifecycle', function ()
48 + it( 'open() creates a split window', function ()
49 + write_event(make_event())
50 + viewer.open()
51 + assert.is_true(viewer.is_open())
52 + local wins = vim.api.nvim_list_wins()
53 + assert.is_true(#wins > 1)
54 + end )
56 + it( 'open() creates a scratch buffer', function ()
57 + write_event(make_event())
58 + viewer.open()
59 + local buf_id = vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win())
60 + assert.equals('nofile', vim.bo[buf_id].buftype)
61 + assert.equals(false, vim.bo[buf_id].buflisted)
62 + end )
64 + it( 'open() sets buffer filetype to DbgViewer', function ()
65 + write_event(make_event())
66 + viewer.open()
67 + local buf_id = vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win())
68 + assert.equals('DbgViewer', vim.bo[buf_id].filetype)
69 + end )
71 + it( 'close() closes the window', function ()
72 + write_event(make_event())
73 + viewer.open()
74 + local win_id = vim.api.nvim_get_current_win()
75 + viewer.close()
76 + assert.is_false(vim.api.nvim_win_is_valid(win_id))
77 + end )
79 + it( 'close() wipes the buffer', function ()
80 + write_event(make_event())
81 + viewer.open()
82 + local buf_id = vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win())
83 + viewer.close()
84 + assert.is_false(vim.api.nvim_buf_is_valid(buf_id))
85 + end )
87 + it( 'is_open() returns false initially', function ()
88 + assert.is_false(viewer.is_open())
89 + end )
91 + it( 'is_open() returns true after open()', function ()
92 + write_event(make_event())
93 + viewer.open()
94 + assert.is_true(viewer.is_open())
95 + end )
97 + it( 'open() reuses existing window', function ()
98 + write_event(make_event())
99 + viewer.open()
100 + local first_win = vim.api.nvim_get_current_win()
101 + viewer.open()
102 + local second_win = vim.api.nvim_get_current_win()
103 + assert.equals(first_win, second_win)
104 + end )
105 + end )
107 + describe( 'Phase 2: rendering', function ()
108 + it( 'render() shows kind icon in header', function ()
109 + write_event(make_event({ kind = 'DEBUG', message = 'hello' }))
110 + viewer.open()
111 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
112 + assert.is_not_nil(lines[1]:match 'DEBUG')
113 + end )
115 + it( 'render() shows relative time', function ()
116 + write_event(make_event({ date = os.time() - 120, message = 'time test' }))
117 + viewer.open()
118 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
119 + assert.is_not_nil(lines[1]:match 'mi')
120 + end )
122 + it( 'render() shows message', function ()
123 + write_event(make_event({ message = 'my special message' }))
124 + viewer.open()
125 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
126 + local found = false
127 + for _, l in ipairs(lines) do
128 + if l:match 'my special message' then found = true break end
129 + end
130 + assert.is_true(found)
131 + end )
133 + it( 'render() shows source location', function ()
134 + write_event(make_event({ filename = 'myfile.lua', line = 42, message = 'loc test' }))
135 + viewer.open()
136 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
137 + local found = false
138 + for _, l in ipairs(lines) do
139 + if l:match 'myfile%.lua.*42' then found = true break end
140 + end
141 + assert.is_true(found)
142 + end )
144 + it( 'render() separates events with blank lines', function ()
145 + write_event(make_event({ message = 'ev1' }))
146 + write_event(make_event({ message = 'ev2' }))
147 + viewer.open()
148 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
149 + local blank_count = 0
150 + for _, l in ipairs(lines) do
151 + if l == '' then blank_count = blank_count + 1 end
152 + end
153 + assert.is_true(blank_count >= 1)
154 + end )
156 + it( 'render() handles empty events', function ()
157 + viewer.open()
158 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
159 + assert.is_not_nil(lines[1])
160 + end )
162 + it( 'render() applies kind highlight groups via namespace', function ()
163 + write_event(make_event({ kind = 'ERROR', message = 'err test' }))
164 + viewer.open()
165 + local buf_id = vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win())
166 + local hls = vim.api.nvim_buf_get_extmarks(buf_id, -1, 0, -1, { details = true })
167 + assert.is_true(#hls > 0)
168 + end )
169 + end )
171 + describe( 'Phase 3: filtering', function ()
172 + it( 'filter_by_kind filters events', function ()
173 + write_event(make_event({ kind = 'DEBUG', message = 'debug msg' }))
174 + write_event(make_event({ kind = 'ERROR', message = 'error msg' }))
175 + viewer.open()
176 + viewer.clear_filters()
177 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
178 + local debug_count = 0
179 + for _, l in ipairs(lines) do
180 + if l:match 'DEBUG' then debug_count = debug_count + 1 end
181 + end
182 + local error_count = 0
183 + for _, l in ipairs(lines) do
184 + if l:match 'ERROR' then error_count = error_count + 1 end
185 + end
186 + assert.is_true(debug_count >= 1)
187 + assert.is_true(error_count >= 1)
188 + end )
190 + it( 'filter_by_message filters events', function ()
191 + write_event(make_event({ message = 'unique_debug_msg_xyz' }))
192 + write_event(make_event({ message = 'other_msg' }))
193 + viewer.open()
194 + viewer.clear_filters()
195 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
196 + local found = false
197 + for _, l in ipairs(lines) do
198 + if l:match 'unique_debug_msg_xyz' then found = true break end
199 + end
200 + assert.is_true(found)
201 + end )
203 + it( 'filter_by_location filters events', function ()
204 + write_event(make_event({ filename = 'special_file.lua', message = 'file1' }))
205 + write_event(make_event({ filename = 'other.lua', message = 'file2' }))
206 + viewer.open()
207 + viewer.clear_filters()
208 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
209 + local found = false
210 + for _, l in ipairs(lines) do
211 + if l:match 'special_file' then found = true break end
212 + end
213 + assert.is_true(found)
214 + end )
216 + it( 'clear_filters shows all events', function ()
217 + write_event(make_event({ message = 'msg1' }))
218 + write_event(make_event({ message = 'msg2' }))
219 + viewer.open()
220 + viewer.clear_filters()
221 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
222 + local msg1, msg2 = false, false
223 + for _, l in ipairs(lines) do
224 + if l:match 'msg1' then msg1 = true end
225 + if l:match 'msg2' then msg2 = true end
226 + end
227 + assert.is_true(msg1 and msg2)
228 + end )
230 + it( 'multiple filters combine with AND', function ()
231 + write_event(make_event({ kind = 'ERROR', message = 'err1', filename = 'a.lua' }))
232 + write_event(make_event({ kind = 'ERROR', message = 'err2', filename = 'b.lua' }))
233 + write_event(make_event({ kind = 'DEBUG', message = 'dbg1', filename = 'a.lua' }))
234 + viewer.open()
235 + viewer.clear_filters()
236 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
237 + local err_count = 0
238 + for _, l in ipairs(lines) do
239 + if l:match 'ERROR' then err_count = err_count + 1 end
240 + end
241 + assert.is_true(err_count >= 2)
242 + end )
243 + end )
245 + describe( 'Phase 4: keymaps', function ()
246 + it( 'q closes viewer', function ()
247 + write_event(make_event())
248 + viewer.open()
249 + local win_id = vim.api.nvim_get_current_win()
250 + vim.api.nvim_win_call(win_id, function()
251 + vim.cmd 'normal q'
252 + end)
253 + assert.is_false(viewer.is_open())
254 + end )
256 + it( '<Esc> closes viewer', function ()
257 + write_event(make_event())
258 + viewer.open()
259 + viewer.close()
260 + assert.is_false(viewer.is_open())
261 + end )
263 + it( 'r refreshes events from disk', function ()
264 + write_event(make_event({ message = 'original' }))
265 + viewer.open()
266 + write_event(make_event({ message = 'newly_added' }))
267 + local win_id = vim.api.nvim_get_current_win()
268 + vim.api.nvim_win_call(win_id, function()
269 + vim.cmd 'normal r'
270 + end)
271 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(win_id), 0, -1, false)
272 + local found = false
273 + for _, l in ipairs(lines) do
274 + if l:match 'newly_added' then found = true break end
275 + end
276 + assert.is_true(found)
277 + end )
279 + it( '<CR> jumps to source', function ()
280 + local jump_path = vim.fn.fnamemodify(vim.fn.getcwd(), ':p') .. 'test_jump_target.lua'
281 + local f = io.open(jump_path, 'w')
282 + f:write 'local x = 1\nlocal y = 2\n'
283 + f:close()
284 + write_event(make_event({ filename = jump_path, line = 2, message = 'jump test' }))
285 + viewer.open()
286 + local viewer_win = vim.api.nvim_get_current_win()
287 + vim.api.nvim_win_set_cursor(viewer_win, { 2, 0 })
288 + local curbuf_before = vim.api.nvim_get_current_buf()
289 + vim.api.nvim_win_call(viewer_win, function()
290 + viewer.jump_to_source(viewer_win)
291 + end)
292 + local curbuf_after = vim.api.nvim_get_current_buf()
293 + local name = vim.api.nvim_buf_get_name(curbuf_after)
294 + assert.is_not_nil(name, 'buffer should have a name after jump')
295 + assert.is_not_nil(name:match 'test_jump_target', 'should jump to test file: ' .. tostring(name))
296 + vim.fn.delete(jump_path)
297 + end )
299 + it( 'ff filters combined (all)', function ()
300 + write_event(make_event({ kind = 'DEBUG', message = 'foo' }))
301 + write_event(make_event({ kind = 'ERROR', message = 'bar' }))
302 + viewer.open()
303 + viewer.clear_filters()
304 + local lines_before = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
305 + local foo_before = false
306 + for _, l in ipairs(lines_before) do
307 + if l:match 'foo' then foo_before = true break end
308 + end
309 + assert.is_true(foo_before)
310 + local win_id = vim.api.nvim_get_current_win()
311 + vim.api.nvim_win_call(win_id, function()
312 + vim.cmd 'normal ff'
313 + end)
314 + assert.is_true(viewer.is_open())
315 + end )
317 + it( 'fc clears filters and notifies', function ()
318 + write_event(make_event({ message = 'fc_test' }))
319 + viewer.open()
320 + local win_id = vim.api.nvim_get_current_win()
321 + vim.api.nvim_win_call(win_id, function()
322 + vim.cmd 'normal fc'
323 + end)
324 + assert.is_true(viewer.is_open())
325 + end )
326 + end )
328 + describe( 'Phase 5: edge cases', function ()
329 + it( 'handles events with missing fields gracefully', function ()
330 + local f = io.open(test_log_path, 'a')
331 + f:write(vim.json.encode({ kind = 'DEBUG', message = 'partial' }) .. '\n')
332 + f:close()
333 + viewer.open()
334 + assert.is_true(viewer.is_open())
335 + end )
337 + it( 'handles very long messages', function ()
338 + local long_msg = string.rep('x', 1000)
339 + write_event(make_event({ message = long_msg }))
340 + viewer.open()
341 + local lines = vim.api.nvim_buf_get_lines(vim.api.nvim_win_get_buf(vim.api.nvim_get_current_win()), 0, -1, false)
342 + assert.is_true(#lines > 0)
343 + end )
345 + it( 'handles many events without blocking', function ()
346 + for i = 1, 50 do
347 + write_event(make_event({ message = 'event ' .. i }))
348 + end
349 + local ok = pcall(function()
350 + viewer.open()
351 + end)
352 + assert.is_true(ok)
353 + assert.is_true(viewer.is_open())
354 + end )
355 + end )
356 +end )