---Debug logging facade. ---Provides dbg(), dbg.kind(), dbg.toggle(), dbg.get() and user commands. ---All debug output goes to the JSONL file at stdpath('state')/bugabinga_config_debug.jsonl. local file = require 'std.dbg.file' local format = require 'std.dbg.format' local user_command = require 'std.user_command' local viewer = require 'std.dbg.viewer' if vim.g.bugabinga_debug_mode == nil then vim.g.bugabinga_debug_mode = false end ---Returns whether debug mode is currently enabled. ---@return boolean local function is_debug_mode() return vim.g.bugabinga_debug_mode end ---Toggles debug mode on/off and prints a notification. local function toggle_debug_mode() vim.g.bugabinga_debug_mode = not vim.g.bugabinga_debug_mode vim.notify( 'Toggled debug mode to ' .. tostring( is_debug_mode() ) ) end ---Logs a debug event of the specified kind. ---Writes to the debug JSONL file if debug mode is enabled. ---@param kind_name string DEBUG, TRACE, or ERROR ---@param message string format string with {} or {N} placeholders ---@param ... any values to substitute into the format string local function print_debug_kind( kind_name, message, ... ) if not is_debug_mode() then return end local now = os.time() local user_data = { ... } local message = format( message, user_data ) local filename, function_name, line_number = file.get_context() local event = { kind = kind_name, date = now, message = message, data = user_data, filename = filename, fn = function_name, line = line_number, } file.write( event, file.get_path() ) end ---Logs a DEBUG event. ---@param _ any ignored (table receiver when called via metatable) ---@param message string format string with {} or {N} placeholders ---@param ... any values to substitute local function print_debug( _, message, ... ) if not is_debug_mode() then return end print_debug_kind( 'DEBUG', message, ... ) end ---Opens or closes the debug viewer depending on current state. local function toggle_debug_viewer() if viewer.is_open() then viewer.close() else viewer.open() end end ---Opens the raw JSONL debug file in a normal buffer. local function open_raw_debug_file() vim.cmd.edit( file.get_path() ) end user_command.DbgModeToggle 'Toggle global vim config debug mode.' ( toggle_debug_mode ) user_command.DbgViewToggle 'Open or close the debug event viewer' ( toggle_debug_viewer ) user_command.DbgOpenFile 'Opens the JSON debug file in normal buffer' ( open_raw_debug_file ) user_command.DbgClear 'Clears the JSON debug file' ( file.clear_log ) return setmetatable( { kind = print_debug_kind, toggle = toggle_debug_mode, get = is_debug_mode, }, { __call = print_debug, __newindex = function ( ... ) error( 'Assignments are not supported for std.dbg.\n' .. vim.inspect( ... ), 2 ) end, } )